Join current_power_w of all switch

Hi!
How can i join current_power_w of all of my switch to see in one sensor

  • platform: template
    sensors:
    dryer_current:
    friendly_name: ‘Consumo atual’
    value_template: ‘{{ states.switch.cozinha_maquina_lavar_roupa_38.attributes[“current_power_w”] }}’
    unit_of_measurement: ‘W’

how can i join more switch in this?

is this possible??

Here is how to do it:

platform: template
  sensors:
    dryer_current:
      friendly_name: 'Consumo atual'
      entity_id:
        - switch.cozinha_maquina_lavar_roupa_38
        - switch.another_1
        - switch.another_2
      value_template: >
        {% set a = state_attr('switch.cozinha_maquina_lavar_roupa_38', 'current_power_w') | float %}
        {% set b = state_attr('switch.another_1', 'current_power_w') | float %}
        {% set c = state_attr('switch.another_2', 'current_power_w') | float %}
        {{ a + b + c }}
      unit_of_measurement: 'W'

this dont work

  • platform: template
    sensors:
    energia_casa:
    friendly_name: ‘Casa Energia’
    entity_id:
    - switch.cozinha_maquina_lavar_roupa_38
    - switch.escritorio_servidor_cpu_22
    - switch.cozinha_cilindro_24
    - switch.cozinha_frigorifico_34
    - switch.sala_multimedia_32
    value_template: >
    {% set a = state_attr(‘switch.cozinha_maquina_lavar_roupa_38’, ‘current_power_w’) | float %}
    {% set b = state_attr(‘switch.escritorio_servidor_cpu_22’, ‘current_power_w’) | float %}
    {% set c = state_attr(‘switch.cozinha_cilindro_24’, ‘current_power_w’) | float %}
    {% set d = state_attr(‘switch.cozinha_frigorifico_34’, ‘current_power_w’) | float %}
    {% set e = state_attr(‘switch.sala_multimedia_32’, ‘current_power_w’) | float %}
    {{ a + b + c + d + e }}
    unit_of_measurement: ‘W’

error https://imgur.com/a/YyuoOY2

is working now… thanks!!!

Glad to hear it works.

In the future, please format the code you post. Without proper formatting, it it difficult for others to determine if it contains any indentation errors.

Use the </> icon in the editor to format the code.

Another way is to enter three back-quotes ``` on a separate line before your code. Then enter another three back-quotes on a separate line after your code.

Its possible to pick the higher value of watts then pick the entity_id and turn it off?

Yes but it requires a fair amount of effort to achieve it. There’s a Min/Max Sensor but it can’t be used for your application because it reports the highest value of a sensor’s state and not the highest value of a sensor’s attribute.

Most available solutions focus on determining the highest value of state or an attribute. For example, paste this into Home Assistant’s Template Editor and it will report the highest value of the current_power_w attribute:

{% set x = state_attr('switch.cozinha_maquina_lavar_roupa_38', 'current_power_w') | float,
           state_attr('switch.escritorio_servidor_cpu_22', 'current_power_w') | float,
           state_attr('switch.cozinha_cilindro_24', 'current_power_w') | float,
           state_attr('switch.cozinha_frigorifico_34', 'current_power_w') | float,
           state_attr('switch.sala_multimedia_32', 'current_power_w') | float %}
{{ x | max }}

The trick is to report which entity has the highest value. I don’t know how to do that (yet).


EDIT

Are you aware that what you are requesting, an automation that turns off the switch with the highest value of current_power_w, will quickly turn off all the switches?

For example, if you have 3 switches:

  • it will turn off the highest power consumer of the 3 switches, leaving 2 switches on.
  • it will turn off the highest power consumer of the 2 switches, leaving 1 switch on.
  • it will turn off the highest power consumer of the 1 switch, leaving no switches on.

Are you sure this is how you want it to work?

@nelsonamen This should get the entity_id.

{% set switches = [ 'switch.cozinha_maquina_lavar_roupa_38',
                    'switch.escritorio_servidor_cpu_22',
                    'switch.cozinha_cilindro_24',
                    'switch.cozinha_frigorifico_34',
                    'switch.sala_multimedia_32', ] %}
{% set current_power_list = states.switch | selectattr('entity_id','in', switches) %}
{% if current_power_list | length > 0 %}
  {% set max = current_power_list | map(attribute='attributes.current_power_w') | list | max %}
  {% set stateobj = current_power_list | selectattr('attributes.current_power_w', 'eq', max) | list %}
  {{ stateobj[0].entity_id }}
{% else %}
  None
{% endif %}
1 Like

Very nice! Contains many things I’ve seen, even a few I’ve used, but the concepts haven’t gelled sufficiently to be assembled into a solution like that!

I assume some sort of power threshold is needed otherwise the end-result is all switches will be turned off (in the order of highest consumer).

Well yeah, this template only give you the max entity_id or None, what you do with it is up to you! EDIT: I Haven’t tested it either, it might require tweeking

thanks!! i will try it later, the idea is to turn off only one switch like stove, cylinder or heater because many times in my house the lights all go down because it reaches 4.6 kwh or 4600w so i have a automation for energy protection that will turn off one of this switch if the energy reaches 4400 for a period of time them turn on again, i already have this in use, but I want automatic choice for higher value of watts

Unknown error rendering template

whats the error and link your config

Tue Jun 11 2019 13:36:47 GMT+0100 (Hora de verão da Europa Ocidental)
Error handling request
Traceback (most recent call last):
File “/usr/local/lib/python3.7/site-packages/aiohttp/web_protocol.py”, line 418, in start
resp = await task
File “/usr/local/lib/python3.7/site-packages/aiohttp/web_app.py”, line 458, in _handle
resp = await handler(request)
File “/usr/local/lib/python3.7/site-packages/aiohttp/web_middlewares.py”, line 119, in impl
return await handler(request)
File “/usr/src/homeassistant/homeassistant/components/http/real_ip.py”, line 33, in real_ip_middleware
return await handler(request)
File “/usr/src/homeassistant/homeassistant/components/http/ban.py”, line 67, in ban_middleware
return await handler(request)
File “/usr/src/homeassistant/homeassistant/components/http/auth.py”, line 216, in auth_middleware
return await handler(request)
File “/usr/src/homeassistant/homeassistant/components/http/view.py”, line 115, in handle
result = await result
File “/usr/src/homeassistant/homeassistant/components/api/init.py”, line 371, in post
return tpl.async_render(data.get(‘variables’))
File “/usr/src/homeassistant/homeassistant/helpers/template.py”, line 191, in async_render
return self._compiled.render(kwargs).strip()
File “/usr/local/lib/python3.7/site-packages/jinja2/asyncsupport.py”, line 76, in render
return original_render(self, *args, **kwargs)
File “/usr/local/lib/python3.7/site-packages/jinja2/environment.py”, line 1008, in render
return self.environment.handle_exception(exc_info, True)
File “/usr/local/lib/python3.7/site-packages/jinja2/environment.py”, line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File “/usr/local/lib/python3.7/site-packages/jinja2/_compat.py”, line 37, in reraise
raise value.with_traceback(tb)
File “”, line 7, in top-level template code
TypeError: object of type ‘generator’ has no len()

try

{% set switches = [ 'switch.cozinha_maquina_lavar_roupa_38',
                    'switch.escritorio_servidor_cpu_22',
                    'switch.cozinha_cilindro_24',
                    'switch.cozinha_frigorifico_34',
                    'switch.sala_multimedia_32', ] %}
{% set current_power_list = states.switch | selectattr('entity_id','in', switches) %}
{% if current_power_list | list | length > 0 %}
  {% set max = current_power_list | map(attribute='attributes.current_power_w') | list | max %}
  {% set stateobj = current_power_list | selectattr('attributes.current_power_w', 'eq', max) | list %}
  {{ stateobj[0].entity_id }}
{% else %}
  None
{% endif %}

sorry but error

2019-06-11 13:36:47 ERROR (MainThread) [aiohttp.server] Error handling request
Traceback (most recent call last):
File “/usr/local/lib/python3.7/site-packages/aiohttp/web_protocol.py”, line 418, in start
resp = await task
File “/usr/local/lib/python3.7/site-packages/aiohttp/web_app.py”, line 458, in _handle
resp = await handler(request)
File “/usr/local/lib/python3.7/site-packages/aiohttp/web_middlewares.py”, line 119, in impl
return await handler(request)
File “/usr/src/homeassistant/homeassistant/components/http/real_ip.py”, line 33, in real_ip_middleware
return await handler(request)
File “/usr/src/homeassistant/homeassistant/components/http/ban.py”, line 67, in ban_middleware
return await handler(request)
File “/usr/src/homeassistant/homeassistant/components/http/auth.py”, line 216, in auth_middleware
return await handler(request)
File “/usr/src/homeassistant/homeassistant/components/http/view.py”, line 115, in handle
result = await result
File “/usr/src/homeassistant/homeassistant/components/api/init.py”, line 371, in post
return tpl.async_render(data.get(‘variables’))
File “/usr/src/homeassistant/homeassistant/helpers/template.py”, line 191, in async_render
return self._compiled.render(kwargs).strip()
File “/usr/local/lib/python3.7/site-packages/jinja2/asyncsupport.py”, line 76, in render
return original_render(self, *args, **kwargs)
File “/usr/local/lib/python3.7/site-packages/jinja2/environment.py”, line 1008, in render
return self.environment.handle_exception(exc_info, True)
File “/usr/local/lib/python3.7/site-packages/jinja2/environment.py”, line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File “/usr/local/lib/python3.7/site-packages/jinja2/_compat.py”, line 37, in reraise
raise value.with_traceback(tb)
File “”, line 7, in top-level template code
TypeError: object of type ‘generator’ has no len()

That’s the same error. Are you sure you updated the code? If yes, then the error is coming elsewhere as the template explicitly converts the generator into a list and length is only used after list. So please post your whole yaml.

@petro

I created 5 switches with the appropriate attribute (containing values from 1000 to 5000 watts). I deconstructed your updated template to identify the source of the error message.

I’m seeing some head-scratching behavior from the Jinja interpreter. For example, this works and shows the highest value of 5000 watts:

However, when I do this seemingly innocuous change, it falls apart:

I would expect to see this result:

5
5000

but not have the result of the last line (which worked above) suddenly become unable to find any matching items in the list (suggesting indicating the resulting list is now empty, as mentioned in the error message).

Whats annoying about the template editor is that errors wipe out everything. remove the max and see what the list is.

I’m guessing the mapped list is a bunch of nulls or something.