Like TazUk and febalci said, an UPS would be the best solution, but that’s something nice to play with.
Create a file sensor
sensor:
- platform: file
name: Restart Log
file_path: "/config/restart.log"
and a file notification
notify:
- name: restart_notify
platform: file
filename: /config/restart.log
timestamp: true
Maybe you need to whitelist the /config
directory in configuration.yaml.
homeassistant:
...
allowlist_external_dirs:
- /config
Now one automation for HA shutdown
- id: "1612867115303"
alias: HA Shutdown
description: ""
trigger:
- platform: homeassistant
event: shutdown
condition: []
action:
- service: notify.restart_notify
data:
message: shutdown
mode: single
and one for HA start
- id: "1612867183386"
alias: HA Start
description: ""
trigger:
- platform: homeassistant
event: start
condition: []
action:
- choose:
- conditions:
- condition: template
value_template: "{{ 'shutdown' in states('sensor.restart_log') }}"
sequence:
- service: notify.restart_notify
data:
message: start
default:
- service: notify.your_phone
data:
message: unclean shutdown
mode: single
Now, on a normal shutdown ‘shutdown’ is written to /config/restart.log.
Home Assistant notifications (Log started: 2021-02-09T10:39:55.205115+00:00)
--------------------------------------------------------------------------------
2021-02-09T10:39:55.205146+00:00 shutdown
2021-02-09T10:40:19.670550+00:00 start
2021-02-09T10:46:33.052513+00:00 shutdown
If HA starts and ‘shutdown’ is in the last line of the log, it was a clean shutdown and ‘start’ is written to it.
If not, a message is sent to another notify service.