Monitoring a UPS with NUT on the Raspberry Pi?

The Uninterruptible Power Supply, or UPS, is an important piece of equipment that can protect your electronics from unexpected power outages. Connecting your Raspberry Pi to a UPS ensures it shuts down safely during a power cut, avoiding SD card corruption or data loss. This article explains how to monitor a UPS connected to a Raspberry Pi using the Network UPS Tools (NUT) software.

Monitoring a UPS with NUT on the Raspberry Pi?

What is a UPS?

A UPS acts as a backup power source for devices connected to it. It contains a battery that immediately provides power if the mains electricity fails. This gives you chance to safely shut down attached computers, servers, or other electronics. There are two main types of UPS:

  • Standby – Switches to battery power if mains power fails. Cheaper but with a slight interruption during transfer.
  • Online – Continuously provide power from its battery with zero transfer time if outage occurs. More expensive but no transfer interruption.

Online UPS systems provide the highest level of protection but a standby UPS works fine for most home users.

Why monitor a UPS on the Raspberry Pi?

Connecting your Pi to a UPS allows it to detect power failures. Software can then trigger a safe, automatic shutdown before the UPS battery is depleted. This prevents SD card corruption that abrupt loss of power can cause.

Monitoring software like NUT also enables other useful features:

  • Email alerts on power status changes.
  • Logging and graphing of utility power and UPS battery statistics.
  • Automatic server shutdown commands during prolonged outages.

Installing NUT with a few configuration tweaks delivers these benefits for your Pi.

Installing NUT (Network UPS Tools)

NUT is available in the Raspbian package repositories, making installation straightforward:

  1. Update package information: sudo apt update
  2. Install the NUT package: sudo apt install nut

With NUT installed, the upsd monitoring daemon will start automatically on boot.

Connecting the UPS to Raspberry Pi

Most modern UPS units feature a USB port for device control and monitoring. This allows connecting directly to a Pi over USB using a cable like:

Once physically connected, the Pi needs to establish communication using the correct USB driver. Most budget UPS models work out of the box using the standard usbhid-ups driver built into NUT.

Higher-end CyberPower or APC models may require installing an additional USB driver like apcsmart, usbhid-ups, or nutdrv_qx from the NUT upstream drivers page.

Configuring nut monitoring on Raspberry Pi

With NUT installed and a UPS USB connection established, basic config files need creation:

sudo -s

cd /etc/ups

mkdir certs

Next, an upsd.users file defines the owner user account and permissions:

/etc/ups/upsd.users

[admin]

   password = 5e2e1df4cd838754365ac5c799daee9b

   actions = SET

   instcmds = ALL

The password is the MD5 hash of your desired password. Choose something long and complex for security.

Finally, a matching upsd.conf file enables monitoring and the NUT server:

etc/ups/upsd.conf

LISTEN 127.0.0.1 3493

LISTEN ::1 3493

MAXAGE 7

MINSUPPLIES 1

CRED admin “5e2e1df4cd838754365ac5c799daee9b”

LISTEN 127.0.0.1 3493

LISTEN ::1 3493

This listens on all network interfaces so you can remotely check UPS status from another system.

Adjust the MINSUPPLIES value if you want your Pi to auto-shutdown with a higher battery percentage remaining.

Configuring drivers

With basic auth and permissions complete, the local USB-connected UPS device itself needs defining.

This is done in the upsd.conf file by adding a matching driver section.

For a simple CyberPower model, it would resemble:

[cyberpower]

    driver = usbhid-ups

    port = auto

Substitute your UPS make and model’s correct driver name if needed. Run upscmd -l after connecting it to confirm detection.

Finally, test connectivity manually via:

upsc cyberpower@localhost

This should display statistics from your UPS without error. Your device is now linked for monitoring!

Shutting down the Pi on power loss

To enable automatic shutdowns on UPS battery when mains power fails, install and configure two helper tools:

  1. NUT helper script – Handles graceful Pi shutdown command.
  2. Upsmon – NUT’s monitoring daemon that detects power failures.

Install them now:

sudo apt install upsmon nut-monitor

With the packages installed, configure upsmon by editing /etc/default/upsmon to uncomment and set these values:

RUN_UPSMON=”yes”

MONITOR_POWER=”yes”

SHUTDOWNCMD=”sudo /sbin/shutdown -h now”

MONITOR_NUT_CLIENTS=”upscmd”

This enables the upsmon background process, monitors UPS + utility power status, and links in the system shutdown command when issues are detected.

The NUT_CLIENTS directive allows the helper script to receive updates too.

Speaking of the script, it handles the actual Pi shutdown sequence – locate it at /usr/local/bin/nut-monitor. By default this file waits 300 seconds (5 minutes) after input power loss before shutting down.

You may want to adjust this delay by editing the script file directly.

For example, to reduce the grace period before shutdown to 60 seconds / 1 minute, alter this section:

   if [ $POWER_IS_ON -eq 1 ]; then

         power is on – nothing we need to do

        …(lines ommitted for brevity)…

    else 

        power is out – shutdown in 300 seconds

        /bin/sleep 60

        $SHUTDOWN

Automating on Reboot

To enable nut monitoring and auto shutdowns automatically on every Raspberry Pi boot:

  1. Enable the NUT monitoring daemon: sudo systemctl enable nut-server
  2. Enable the NUT client helper: sudo systemctl enable nut-monitor
  3. Reboot to confirm both start as desired on system initialization!

Monitoring with auto-shutdown protection is now active.

Remote UPS Monitoring

Accessing UPS statistics from another networked Linux/Windows PC is also possible by installing a NUT client. This forwards status values from the Pi’s instance over the network.

On Debian/Ubuntu install with:

sudo apt install nut-client

For Fedora/RHEL/CentOS systems use:

sudo yum install nut nut-devel

On the remote PC, edit /etc/ups/upsmon.conf adding a MONITOR line:

MONITOR [email protected] 1 admin password master

Substitute your Pi’s IP, username, and password credentials configured previously.

Restart the upsmon process:

sudo systemctl restart upsmon

After a few moments, type upsc and remote UPS data should display! The connection is active for monitoring over the network.

Understanding upsmon process status

Use systemctl commands to check, start, and stop both key processes:

sudo systemctl status upsmon

sudo systemctl status nut-server

sudo systemctl start upsmon

sudo systemctl start nut-server

sudo systemctl stop upsmon  

sudo systemctl stop nut-server

Watch logs in /var/log/upsmon and /var/log/syslog for related activity and errors after making changes.

Securing NUT

As a precaution, verify the file permissions for NUT’s configuration directory adhere to security best practices:

sudo chown -R root:nut /etc/ups

sudo chmod -R 750 /etc/ups

This removes unnecessary read or execute access for regular users.

Also configure the Pi’s built-in firewall UFW to only allow the UPS monitoring services from trusted administrator IP addresses:

sudo ufw allow from 192.168.1.100 to any port 3493 comment ‘Allow NUT upsmon access’

sudo ufw enable

Adapt the IP address and port based on your preferences. Lastly watch for NUT security notices and updates applying any recommended fixes to maximize resilience.

Using NUT alternative tools

If you prefer an all-in-one shutdown + UPS watchdog tool alternative to nut-monitor, upscut is an option combining every key capability:

https://github.com/rabrams/upscut

It’s configured via basic INI-style values making it quick to customize shutdown delays and battery levels.

For a lightweight UPS dashboard on the Pi itself, the UPS PIco screen utility has a sharp interface:

https://github.com/ups-pico/ups-pico

This uses a small ePaper or OLED display module via GPIO for glanceable power metrics without relying on a network connection.

Key Takeaways

  • Network UPS Tools (NUT) reliably monitors a connected UPS device over USB.
  • upsmon, nut-monitor, and helper scripts enable safe shutdowns during power events.
  • Carefully configure NUT and test functionality periodically to ensure redundancy.
  • Remote administration plus dashboards give insight into UPS and utility power states.
  • Follow security best practices for permissions, firewall policies, and updates.

Conclusion

Pairing a UPS with automated power monitoring software like Network UPS Tools is crucial for protecting your Pi from corruption, data damage, or hardware faults during an outage.

Carefully setting up and verifying NUT’s shutdown helpers gives robust protection. Remote UPS oversight also assists troubleshooting or alerts you to utility power incidents.

What battery backup and monitoring provisions do you utilize for resilient Raspberry Pi projects?

FAQS

  1. What type of UPS works best with a Raspberry Pi?
    Most affordable “standby” UPS models with USB connectivity properly interface for NUT software monitoring on a Pi. CyberPower, APC, and other common brands are typically compatible.

  2. Does the UPS require special drivers for the Raspberry Pi?
    Sometimes – the default usbhid-ups driver handles many UPS units out of the box. But certain high-end CyberPower and APC models need additional drivers installed from the NUT project first.

  3. How do I find the correct NUT driver for my UPS device?
    Consult the Network UPS Tools Hardware Compatibility List for your UPS make/model and required matching driver name. The list covers thousands of tested devices.

  4. What DC output voltage should the UPS supply the Pi?
    The optimal UPS output voltage is 5 volts DC, matching most Raspberry Pi power adapters. This avoids any issues with undervoltage reaching the Pi’s SoC.

  5. Does older Raspberry Pi models work with a UPS?
    Yes – the recommended Nut software is compatible back to early single-core Pi models. The key requirement is an available USB port for connecting the UPS data/monitoring cable.

  6. How do I secure NUT’s configuration from unauthorized changes?
    Set the root user as owner of NUT’s /etc/ups directory and configure strict filesystem permissions. Also limit network access to upsmon via firewall policies on ports it exposes.

  7. Why enable NUT on public network interfaces?
    Exposing the nut-server ports allows remotely monitoring the Pi’s UPS statistics from another trusted computer. This centralizes visibility of power status without logging directly into the Pi.

  8. What happens if the UPS battery reaches critically low capacity?
    Once the remaining runtime hits a threshold set in nut-monitor or upscut, the system initiates a shutdown command to avoid sudden power loss. This prevents SD card or filesystem corruption.

  9. How long can my Pi run on a typical UPS battery?
    Factors like Pi model, connected peripherals, UPS battery capacity (VA rating), and runtime efficiency impact this. In general plan 30 minutes of runtime for smaller 350-500VA home/office UPS units under 50% load.

  10. Does using a UPS impact Raspberry Pi performance?
    No – once properly communicating via USB, the UPS simply monitors line power and provides backup DC voltage when an AC outage occurs. It delivers power identically to your existing Pi adapter so no slowdown.

  11. Should I run a headless Pi off a UPS for resilience?
    Definitely – headless (monitor-less) Pi servers gain the same corruption prevention during outages a desktop Pi does. The OS safely halts itself regardless of whether a display is attached or not.

  12. Why connect the Pi USB port directly to the UPS instead of the wall adapter?
    Communicating directly with the UPS enables the Pi to detect a wall power failure itself and trigger shutdown scripts. Relying on just the wall adapter battery provides no smart monitoring.

  13. Does NUT software work for UPS brands besides CyberPower?
    Yes! The Network UPS Tools project supports over 2000 UPS models from dozens of brands – APC, Eaton, Tripp Lite, Power Walker, and more. The hardware compatibility list details every model and required configuration.

  14. How can I graph trends from my UPS data over time?
    NUT optionally records metrics like load, voltages, battery charge, temperatures, and runtime predictions to a logging directory. This data can be imported into monitoring tools like Grafana or Kibana to visualize trends.

  15. Is an online vs standby UPS better for my Pi project?
    An online UPS with dual AC to DC stages provides perfectly stable output voltage during heavy loads or electrical storms. But for most Pi use cases, an affordable standby unit avoids that complexity unless large current spikes are expected.

  16. Can I monitor a USB-connected UPS in Home Assistant or Node-RED?
    Yes! Helper add-ons like node-red-contrib-nut expose UPS statistics directly into Node-RED flows for easy dashboarding. Or the HA UPS Monitor integration surfaces metrics within Home Assistant.

  17. Does NUT auto shutdown work if SSH or the network fails?
    Yes – upscut and the nut-monitor scripts handle initiating shutdown via direct systemctl commands. So even during network outage or before SSH finishes disconnecting, the OS itself directly receives the power off signal.

  18. My UPS monitoring shows wildly unstable output voltages – why?
    This typically indicates a failing battery nearing its service lifespan. As cells weaken, the smoothing and regulation circuitry struggles to maintain steady voltage levels. Replace older lead-acid batteries exceeding ~3 years, or 2 years for lithium variants.

  19. Can I remotely manage my Nut client on the Pi from another computer?
    Yes – options like the Official NUT Admin Client or the NUT Web Monitor app allow securely connecting to remotely change settings, assign permissions, tweak driver config, or update firmware.

  20. Does NUT software work outside Raspberry Pi OS and Linux?
    macOS, Windows 10/11, and BSD clients do exist enabling consolidating monitoring onto servers running those operating systems. But for automatically shutting down the Pi itself, running the nut-server natively under Raspbian or Raspberry Pi OS is required.

Leave a Comment