Here’s a Trigger-based Template Sensor I recently created that reports one of two states on startup:
-
start
if Home Assistant was shutdown normally prior to starting.
-
interrupt
if Home Assistant was not shutdown normally prior to starting.
It also maintains a history of the ten most recent stop/started events, sorted in reverse chronological order (i.e. most recent is first). This attribute is optional.
- trigger:
- platform: event
event_type:
- homeassistant_started
- homeassistant_stop
sensor:
- name: Start Stop
state: >
{% if trigger.event.event_type == 'homeassistant_started' %}
{{ iif(this.state|default('unknown') == 'shutdown', 'start', 'interrupt') }}
{% else %}
shutdown
{% endif %}
attributes:
history: >
{% set current = this.attributes.get('history', []) %}
{% set new = [{
"event": trigger.event.event_type[14:],
"time": now().isoformat() }] %}
{{ (new + current)[:10] }}
After creating the Trigger-based Template Sensor, it will initially report unknown
. Initialize it by restarting Home Assistant (Developer Tools> YAML > Restart). On startup, it should now report start
.
Here’s what it looks like on startup after Home Assistant was interrupted (i.e. not shutdown properly). The sensor reports interrupt
. The history
attribute shows there was no stop
event prior to the most recent started
event, indicating Home Assistant had been interrupted and didn’t get a chance to shutdown normally.
You can create an automation with a State Trigger to monitor the sensor when it changes to: interrupt
and have it notify you that there was a recent interruption (potentially due to a power failure).
NOTE 1
Originally I tried to have the Event Trigger detect homeassistant_start
which occurs before homeassistant_started
but it failed to be detected. I assume it may be because the Template integration is loaded after the homeassistant_start
event occurs so the Trigger-based Template Sensor never gets the opportunity to detect it.
NOTE 2
The history
attribute is optional and can be eliminated without affecting the sensor’s operation. It’s included merely as a convenience; the sensor’s recorded History (i.e. in the database) shows the same information.