Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save Mr-Groch/bf073b142b507e3b6f8154223f81803b to your computer and use it in GitHub Desktop.
Save Mr-Groch/bf073b142b507e3b6f8154223f81803b to your computer and use it in GitHub Desktop.
Home Assistant Blueprint: Offline detection for Z2M devices with last_seen
blueprint:
name: Offline detection for Z2M devices with last_seen
description: Regularly test all sensors with 'last_seen' in name and 'timestamp' device_class
('last seen' Z2M sensors) to detect offline and if so execute an action.
domain: automation
input:
hours:
name: Hours not seen
description: Sensors not seen this amount of time are assumed to be offline.
default: 24
selector:
number:
min: 1.0
max: 168.0
unit_of_measurement: h
mode: slider
step: 1.0
time:
name: Time to test on
description: Test is run at configured time
default: '10:00:00'
selector:
time: {}
day:
name: Weekday to test on
description: 'Test is run at configured time either everyday (0) or on a given
weekday (1: Monday ... 7: Sunday)'
default: 0
selector:
number:
min: 0.0
max: 7.0
mode: slider
step: 1.0
exclude:
name: Excluded Sensors
description: "'last seen' sensors (from devices that you want to exclude) to
exclude from detection. Only entities with 'last seen' in name and 'timestamp'
in device_class are supported, devices must be expanded!"
default:
entity_id: []
selector:
target:
entity:
domain: sensor
actions:
name: Actions
description: Notifications or similar to be run. {{sensors}} is replaced with
the names of sensors being offline.
selector:
action: {}
source_url: https://gist.github.com/Mr-Groch/bf073b142b507e3b6f8154223f81803b
variables:
day: !input 'day'
hours: !input 'hours'
exclude: !input 'exclude'
sensors: "{% set result = namespace(sensors=[]) %}\
\ {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %}\
\ {% if 'last_seen' in state.entity_id and not state.entity_id in exclude.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((hours | int) * 60 * 60))) %}\
\ {% set result.sensors = result.sensors + [state.name | regex_replace(find=' last seen', replace='') ~ ' (' ~ relative_time(strptime(states(state.entity_id), '%Y-%m-%dT%H:%M:%S%z', 'unavailable')) ~ ')'] %}\
\ {% endif %}\
\ {% endfor %}\
\ {{ result.sensors | join(', ') }}"
trigger:
- platform: time
at: !input 'time'
condition:
- '{{ sensors != '''' and (day | int == 0 or day | int == now().isoweekday()) }}'
action:
- choose: []
default: !input 'actions'
mode: single
@mikhail5555
Copy link

Can you change line 58 to the next snippet:

    \ {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %}\

I noticed i was getting the error UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class' otherwise

@Mr-Groch
Copy link
Author

Mr-Groch commented Sep 4, 2022

Can you change line 58 to the next snippet:

    \ {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %}\

I noticed i was getting the error UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class' otherwise

Updated, thanks

@mikhail5555
Copy link

And maybe one more small request:

    \     {% set result.sensors = result.sensors + [state.name | regex_replace(find='_last_seen', replace='') | regex_replace(find=' last seen', replace='') ~ ' (' ~ relative_time(strptime(states(state.entity_id), '%Y-%m-%dT%H:%M:%S%z', 'unavailable')) ~ ')'] %}\

for line 60, since in my case (and i assume also with other people) the name is not necessary space separated.

Thanks anyway for fixing the previous bug! (and so quickly)

@Mr-Groch
Copy link
Author

Mr-Groch commented Sep 6, 2022

This is strange... Have you manually changed friendly name of yours devices? entityid will have underscores naurally, but by default there is space in name...

@mikhail5555
Copy link

image
I did manually change the entity id, but not the name

@VivantSenior
Copy link

Hi, thanks for the blueprint. Unfortunately I got an error:

Error rendering variables: ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template
'{% set result = namespace(sensors=[]) %} {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %
 {% if 'last_seen' in state.entity_id and not state.entity_id in exclude.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((hours | int) * 60 * 60))) %} {% set result.sensors = result.sensors + [state.name | regex_replace(find=' last seen', replace='') ~ ' (' ~ relative_time(strptime(states(state.entity_id), '%Y-%m-%dT%H:%M:%S%z', 'unavailable')) ~ ')'] %} {% endif %} {% endfor %} {{ result.sensors | join(', ') }}' but no default was specified

@gdgeist
Copy link

gdgeist commented Apr 14, 2023

Default for mine as well doesnt make the name different from the entity id i.e. the name has the underscores not the spaces, Receiving the following error same as @VivantSenior above. Will see if i can fix it and will post.

FYI - thanks for this code - always standing on the shoulder of giants like you!

2023-04-14 12:29:00.257 ERROR (MainThread) [homeassistant.components.automation.offline_detection_for_z2m_devices_with_last_seen] Error rendering variables: ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{% set result = namespace(sensors=[]) %} {% for state in states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', '==', 'timestamp') %} {% if 'last_seen' in state.entity_id and not state.entity_id in exclude.entity_id and (states(state.entity_id) == 'unavailable' or ((as_timestamp(now()) - as_timestamp(states(state.entity_id))) > ((hours | int) * 60 * 60))) %} {% set result.sensors = result.sensors + [state.name | regex_replace(find=' last seen', replace='') ~ ' (' ~ relative_time(strptime(states(state.entity_id), '%Y-%m-%dT%H:%M:%S%z', 'unavailable')) ~ ')'] %} {% endif %} {% endfor %} {{ result.sensors | join(', ') }}' but no default was specified

@Rmh1978
Copy link

Rmh1978 commented Jun 22, 2023

Hey Mr-Groch
Thank you for the nice blueprint.

Is there a way to include the device/s that are offline on the notification message?

@xekil
Copy link

xekil commented Jan 22, 2024

Hello @Mr-Groch and thank you for this Blueprint that I have been using for months.

Is it possible to have a line break in the notification for each device?
This would be much more readable when there are a lot of devices offline.

thanks again

@DChe47
Copy link

DChe47 commented Feb 22, 2024

I have HA supervised + Z2M, but I don't see last_seen in the attributes. My sensors in HA have these attributes only (examlpe):
state_class: measurement unit_of_measurement: °C device_class: temperature friendly_name: Датчик на улице Температура
But in the Z2M, I see an attribute last_seen, so for the sensor from the example, I see this:
{ "humidity": 86, "last_seen": "2024-02-22T12:38:26+03:00", "linkquality": 29, "temperature": -0.2 }
How do I transfer the last_seen attribute from Z2M to HA to use this blueprint? It's not working right now.

Sorry, I figured it out myself. I've added objects that are deactivated by default. Now I see it in HA. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment