Hello.
I am studying Home Assistant and Jinja. I’m trying to create different sensors and other things.
I made a sensor that collects battery sensors readings and then sorts entities and their status in ascending order into a list.
After that, in the form of a table in the Markdown, they are output to the HA interface.
Can someone comment on whether I did everything logically?
P.S. I know about custom cards like auto entities… But I want to learn to do something myself.
Sensor:
- trigger:
- platform: homeassistant
event: start
- platform: time_pattern
# hours: "/3"
#seconds: "/15"
minutes: "/20"
sensor:
- name: State of battery
unit_of_measurement: entities
state: "{{ 'non' }}"
attributes:
list_of_bat: >
{% set nmsp = namespace(dict_nm_st = {}) %}
{% for entity in states.sensor if is_state_attr(entity.entity_id, 'device_class', 'battery')
and (entity.entity_id.endswith("_battery"))
and states(entity.entity_id) not in ['unavailable','unknown','none'] %}
{% set nmsp.dict_nm_st = dict(nmsp.dict_nm_st, **{entity.name: entity.state |int(0) }) %}
{% endfor %}
{% set lst_dct_srt = nmsp.dict_nm_st |dictsort(false, 'value') %}
{{ lst_dct_srt }}
In Lovelace (necessarily with empty lines):
- type: markdown
content: >-
<center> <h3>State of battery device, % </center> <center>
| | |
|:------- | -------:|
{% for ent_nm, st_ent in state_attr('sensor.state_of_battery', 'list_of_bat')
-%} | {{ ent_nm }} | {{ "  " ~ st_ent }}
{% endfor %} </center>
Or, if, you need, with battery icons:
- type: markdown
content: >-
<font color=DarkSlateGray size=2><center> <h3>State of battery device, %
</center> <center>
| | | |
|:----|:----|----:|
{% for ent_nm, st_ent in state_attr('sensor.state_of_battery','list_of_bat')-%}
{% if st_ent < 15 %}
{% set icon = '<ha-icon icon="mdi:battery-10"></ha-icon>' %}
{% elif st_ent < 25 %}
{% set icon = '<ha-icon icon="mdi:battery-20"></ha-icon>' %}
{% elif st_ent < 35 %}
{% set icon = '<ha-icon icon="mdi:battery-30"></ha-icon>' %}
{% elif st_ent < 45 %}
{% set icon = '<ha-icon icon="mdi:battery-40"></ha-icon>' %}
{% elif st_ent < 55 %}
{% set icon = '<ha-icon icon="mdi:battery-50"></ha-icon>' %}
{% elif st_ent < 65 %}
{% set icon = '<ha-icon icon="mdi:battery-60"></ha-icon>' %}
{% elif st_ent < 75 %}
{% set icon = '<ha-icon icon="mdi:battery-70"></ha-icon>' %}
{% elif st_ent < 85 %}
{% set icon = '<ha-icon icon="mdi:battery-80"></ha-icon>' %}
{% elif st_ent < 95 %}
{% set icon = '<ha-icon icon="mdi:battery-90"></ha-icon>' %}
{% else %}
{% set icon = '<ha-icon icon="mdi:battery"></ha-icon>' %}
{% endif %}
| {{ icon }} | {{ ent_nm }} | {{ " " ~ st_ent }}
{% endfor %} </center></font>