gmlupatelli / blueprints_repo

GNU General Public License v3.0
21 stars 16 forks source link

Include unavailable entities for Low Battery Detection (it being the final stage of a low battery) #5

Open melyux opened 2 years ago

melyux commented 2 years ago

You can simply paste in this modification by Pedolsky on the Home Assistant forums:

sensors: >-
    {% set result = namespace(sensors=[]) %}
    {% set exclude = [] %}
    {% set threshold = 40 |int(0) %}
    {% for state in states.sensor | selectattr('attributes.device_class', '==', 'battery') %}
      {% if (0 <= state.state | int(-1) < threshold or state.state in ['unavailable', 'unknown', 'none']) and not state.entity_id in exclude.entity_id -%}
        {% set result.sensors = result.sensors + [state.name ~ ' (' ~ state.state ~ ' %)'] %}
      {% endif %}
    {% endfor %}
    {% for state in states.binary_sensor | selectattr('attributes.device_class', '==', 'battery') | selectattr('state', '==', 'on') %}
      {% if not state.entity_id in exclude.entity_id -%}
        {% set result.sensors = result.sensors + [state.name] %}
      {% endif %}
    {% endfor %}
    {{result.sensors|join('\n') }}

I would go beyond this and do two more things:

  1. Get rid of the space in front of the percentage sign, it's unnecessary.
  2. Don't show the percentage sign if the state is unavailable/unknown (i.e. not a number).

You can do this by using this following one instead:

  sensors: >-
    {% set result = namespace(sensors=[]) %}
    {% set exclude = [] %}
    {% set threshold = 40 |int(0) %}
    {% for state in states.sensor | selectattr('attributes.device_class', '==', 'battery') %}
      {% if (0 <= state.state | int(-1) < threshold or state.state in ['unavailable', 'unknown', 'none']) and not state.entity_id in exclude.entity_id -%}
        {% set result.sensors = result.sensors + [state.name ~ ' ' ~ (('(' ~ state.state ~ '%)') if state.state not in ['unavailable', 'unknown', 'none'] else ('(' ~ state.state ~ ')'))] %}
      {% endif %}
    {% endfor %}
    {% for state in states.binary_sensor | selectattr('attributes.device_class', '==', 'battery') | selectattr('state', '==', 'on') %}
      {% if not state.entity_id in exclude.entity_id -%}
        {% set result.sensors = result.sensors + [state.name] %}
      {% endif %}
    {% endfor %}
    {{ result.sensors | join('\n') }}

(This includes the newline separation as requested in #4)