Home Assistant and NUT
Prompted by Jeff Geerling’s recent post about NUT (Network UPS Tools), I finally finished setting up my home server UPS. Jeff’s post is wonderfully comprehensive so there’s not much to add to the basic setup, but I found I wanted slightly custom behaviour with Home Assistant. As this proved a little more nuanced than I might have hoped, I thought I’d document it here.
The goal of a UPS is to safely respond to power outages by (in the worst case scenario) safely powering down all attached systems to avoid data loss. Ideally this would be the default behavior but, unfortunately, the NUT plugin for Home Assistant seems to be more about displaying and recording the UPS state than about either managing the UPS itself or responding to state changes, offering no easy way to simply power down Home Assistant when it receives an FSD event (full shutdown).
Thankfully, Home Assistant provides pretty comprehensive automation support, so it’s possible to set up an automation to send a notification and initiate a shutdown if ever the UPS state changes to include ‘FSC’.
States are reported from NUT as space-separated codes in a single string; things like OL
(online), OL CHARGING
(online and charging), LB
(low-battery), FSD
(full shutdown), FSB OL CHARGING
(full shutdown, online, and charging), etc. Since the string can contain multiple states, it’s insufficient to use a simple string comparison and we need to lean on Home Assistant’s template-based triggers.
Specifically we can craft a template which will evaluate to true
when the UPS' status data contains FSD
and false
otherwise and use this as the trigger:
{% if 'FSD' in states('sensor.apc_status_data') %}true{% else %}false{% endif %}
You’ll need to tweak this for your own setup: the status data for my UPS (named ‘apc’) turns up as sensor.apc_status_data
; you should be able to find your own in ‘Developer tools > States’ in the Home Assistant by searching for the ‘sensordata’ text.
Adding the automation itself can be done from ‘Settings > Automations’ by clicking the ‘Create Automation’ button. From there you can select ‘Create new automation’ and then ‘Add trigger’, ‘Other triggers’, ‘Template’ (you may need to scroll down for this).
You can now fill in your version of the template above in the ‘Value template’ field.
After that, it’s a matter of adding the action. A simple action it to just shutdown Home Assistant: ‘Add Action’. Simply searching for ‘shutdown’ should reveal the shutdown action.
With this set up, your Home Assitant device should shut down when you run upsmon -c fsd
from your NUT admin account.
Needless to say, if you know a simpler way to approach this, I’d love your feedback!