uspino
February 25, 2024, 12:25pm
1
I have 15 power sensors measuring the consumption of 15 different devices. I want to show the 4 or 5 highest-cunsumption devices in real time in Lovelace.
I’ve tried min-max, statistics, etc., but they don’t seem to solve what I’m looking for. Anybody can point me in the right direction? Thanks.
123
(Taras)
February 25, 2024, 2:09pm
2
Copy-paste the following template into the Template Editor and experiment with it.
{% set ns = namespace(sensors=[]) %}
{% for s in states.sensor
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'power')
| rejectattr('state', 'in', ['unavailable', 'unknown'])
| list -%}
{% set ns.sensors = ns.sensors + [{"id": s.entity_id, "state": s.state|int(0)}] %}
{% endfor %}
{% for s in (ns.sensors | sort(attribute='state', reverse=true))[:4] -%}
{{ s.id }}, {{ s.state }}
{% endfor %}
EDIT
Correction. Truncate list produced by first for-loop as opposed to within it.
Edwin_D
(Edwin D.)
February 25, 2024, 2:22pm
3
Shouldn’t the list be limited to 4 after sorting?
{% set ns = namespace(sensors=[]) %}
{% for s in (states.sensor
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'power')
| rejectattr('state', 'in', ['unavailable', 'unknown'])
| list) -%}
{% set ns.sensors = ns.sensors + [{"id": s.entity_id, "state": s.state|int(0)}] %}
{% endfor %}
{% for s in (ns.sensors | sort(attribute='state', reverse=true))[:4] -%}
{{ s.id }}, {{ s.state }}
{% endfor %}
uspino
February 25, 2024, 2:26pm
4
This definitely looks like the way to go, I’ll start working from there. Two quick questions: Can the code be modified to point only ant the 15 sensors I want to monitor? Can I choose what sensor in the list I show? (Let’s say the third sensor in the top 5 devices, per consumption). Thanks.
123
(Taras)
February 25, 2024, 2:40pm
5
Yes, good point. The example I posted went through several iterations and the [:4]
got moved around several times … and ended up in the wrong place.
I have corrected the example posted above.
123
(Taras)
February 25, 2024, 2:47pm
6
Yes.
{% set ns = namespace(sensors=[]) %}
{% for s in expand('sensor.one', 'sensor.two', 'sensor.etc')
| rejectattr('state', 'in', ['unavailable', 'unknown']) -%}
{% set ns.sensors = ns.sensors + [{"id": s.entity_id, "state": s.state|int(0)}] %}
{% endfor %}
{% for s in (ns.sensors | sort(attribute='state', reverse=true))[:4] -%}
{{ s.id }}, {{ s.state }}
{% endfor %}