Reliable power detection

Running HASSOS on a Raspberry Pi 4B, connected to a small UPS with USB passthrough. I’d like to reliably detect when the Pi loses power, so Home Assistant can shut down gracefully and the SSD is protected.

There’s several topics on ESP-home or smart switch solutions, but these all rely on a WiFi/Zigbee network to function properly. I don’t want HA to shut down on network failure.

I was thinking to add something like an optocoupler connected to the Pi via USB. Or connect a USB charger with voltage converter, and make a USB connection to the Pi in order to monitor power.

I have some basic experience reading serial within Home Assistant, but none in creating or adapting a detectable USB peripheral to read power status. Thoughts and tips are very welcome!

In the end I solved this by connecting a phone charger to an optocoupler: Optocoupler Isolation Module - 2 Channels - ISOBOARD2CH (tinytronics.nl)

  1. The optocoupler is connected to a spare Arduino Nano on the other end, the Arduino goes into the Raspberry via USB.

  2. Modified a MySensors script to setup the Nano as a gateway and sensor in one: Building a Serial Gateway | MySensors - Create your own Connected Home Experience Just wrote my own small script .ino file:

const int DIN_PIN = 3;

void setup(){
    pinMode( DIN_PIN, INPUT_PULLUP );
    Serial.begin( 9600 );
}

void loop(){
    int value;
    
    value = digitalRead( DIN_PIN );
    Serial.println( value );

    delay( 100 );
}
  1. Created a serial sensor in home assistant .config to read the mains power status (I didn’t want to bother with the MySensors integration, which probably also works:
  - platform: serial
    serial_port: /dev/serial/by-id/usb-1a86_USB_Serial-if00-port0
    baudrate: 9600
    name: PowerArduinoOutput

My system will now gracefully shutdown in a power outage, saving the SSD. Best part that this solution is safe and very cheap.

If you’d like all config files, just drop a message and i’ll paste them here.