Unavailable Sensors Template Sensor

I’ve added a template sensor, courtesy of this webpage to list all entities reporting a state of unavailable, and it works as expected.

However, is there a way I can change the template sensor code to only list sensors that are unavailable, rather than having to edit a group, as this would need to be done every time a new device is added to HA, and I’m only interested in reporting sensors.

Template Sensor

- platform: template
  sensors:
    unavailable_entities:
      friendly_name: Unavailable Entities
      unit_of_measurement: entities
      icon_template: "{{ 'mdi:check-circle' if is_state('sensor.unavailable_entities','0') else 'mdi:alert-circle' }}"
      value_template: >
          {{ states|selectattr('state','in',['unavailable','unknown','none'])|rejectattr('domain','eq','group')
            |rejectattr('entity_id','in',state_attr('group.ignored_entities','entity_id'))|list|count }}
      attribute_templates:
        entities: >
            {{ states|selectattr('state','in',['unavailable','unknown','none'])|rejectattr('domain','eq','group')
                |rejectattr('entity_id','in',state_attr('group.ignored_entities','entity_id'))|map(attribute='entity_id')|list }}

Thanks @123 but I’ve made the amendments suggested and it returns unknown.

Below is my full sensor and I’ve tried it both including the last 4 lines and commenting them out and it still returns unknown

- platform: template
  sensors:
    unavailable_entities:
      friendly_name: Unavailable Entities
      unit_of_measurement: entities
      icon_template: "{{ 'mdi:check-circle' if is_state('sensor.unavailable_entities','0') else 'mdi:alert-circle' }}"
      value_template: >
              {{ states.sensor
                | selectattr('state', 'in', ['unavailable','unknown','none'])
                | map(attribute='entity_id') | list }}
      attribute_templates:
        entities: >
            {{ states|selectattr('state','in',['unavailable','unknown','none'])|rejectattr('domain','eq','group')
               |rejectattr('entity_id','in',state_attr('group.ignored_entities','entity_id'))|map(attribute='entity_id')|list }} 

Yes, this returns a number in Template Editor so I tried it in the dashboard card and it worked, so thank you.

I’ve changed it slightly because I want a list instead of a count and the below works

{{ states.sensor
          | selectattr('state', 'in', ['unavailable','unknown','none'])
          | map(attribute='name') | list }}

but is there a way of displaying a list of the devices that are unavailable or devices that have an unavailable entity instead of the individual entities?

So, the value_template works in the template editor but the sensor returns ‘Unknown’ when I use the below in markdown card.

Template Sensor:

- platform: template
  sensors:
    unavailable_entities:
      friendly_name: Unavailable Entities
      unit_of_measurement: entities
      value_template: >
        {{ states.sensor
          | selectattr('state', 'in', ['unavailable','unknown','none'])
          | map(attribute='name')| list }} 

Markdown card:

type: markdown
      content: >-  
         {{ states('sensor.unavailable_entities')   
            |replace(",","<br>")    
            |replace("[","")    
            |replace("]"," ")    
            |replace("\x27","")    
            |replace("\x22","")  
         }}

It’s still returning unavailable.

I wasn’t aware of the Reload Templates requirement but I did that and it returned unavailable and the 2 below errors in the log:

Logger: homeassistant.components.sensor
Source: core.py:1225 
Integration: Sensor (documentation, issues) 
First occurred: 8:31:29 PM (4 occurrences) 
Last logged: 8:34:59 PM

Error adding entities for domain sensor with platform template
Error while setting up template platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 455, in async_add_entities
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 731, in _async_add_entity
    await entity.add_to_platform_finish()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 844, in add_to_platform_finish
    await self.async_added_to_hass()
  File "/usr/src/homeassistant/homeassistant/components/template/sensor.py", line 224, in async_added_to_hass
    await super().async_added_to_hass()
  File "/usr/src/homeassistant/homeassistant/helpers/template_entity.py", line 408, in async_added_to_hass
    await self._async_template_startup()
  File "/usr/src/homeassistant/homeassistant/helpers/template_entity.py", line 379, in _async_template_startup
    result_info.async_refresh()
  File "/usr/src/homeassistant/homeassistant/helpers/event.py", line 953, in async_refresh
    self._refresh(None)
  File "/usr/src/homeassistant/homeassistant/helpers/event.py", line 1133, in _refresh
    self.hass.async_run_hass_job(self._job, event, updates)
  File "/usr/src/homeassistant/homeassistant/core.py", line 607, in async_run_hass_job
    hassjob.target(*args)
  File "/usr/src/homeassistant/homeassistant/helpers/template_entity.py", line 348, in _handle_results
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 585, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 706, in _async_write_ha_state
    hass.states.async_set(entity_id, state, attr, self.force_update, self._context)
  File "/usr/src/homeassistant/homeassistant/core.py", line 1576, in async_set
    state = State(
  File "/usr/src/homeassistant/homeassistant/core.py", line 1225, in __init__
    raise InvalidStateError(
homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.unavailable_entities. State max length is 255 characters.
Logger: homeassistant
Source: core.py:1225 
First occurred: 8:31:30 PM (2 occurrences) 
Last logged: 8:35:00 PM

Error doing job: Exception in callback None()
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/asyncio/events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "/usr/src/homeassistant/homeassistant/helpers/event.py", line 1133, in _refresh
    self.hass.async_run_hass_job(self._job, event, updates)
  File "/usr/src/homeassistant/homeassistant/core.py", line 607, in async_run_hass_job
    hassjob.target(*args)
  File "/usr/src/homeassistant/homeassistant/helpers/template_entity.py", line 348, in _handle_results
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 585, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 706, in _async_write_ha_state
    hass.states.async_set(entity_id, state, attr, self.force_update, self._context)
  File "/usr/src/homeassistant/homeassistant/core.py", line 1576, in async_set
    state = State(
  File "/usr/src/homeassistant/homeassistant/core.py", line 1225, in __init__
    raise InvalidStateError(
homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.unavailable_entities. State max length is 255 characters.

No, it didn’t but it all appears to be working correctly now as it’s showing all entities and no errors so some entities must have come back on line, I guess.

Is it possible, instead, to report the devices instead of the individual entities? This would make the list much easier to work with and readable in a dashboard card.