Note: This post is part of a series. Each post builds on the previous ones. If you are just trying to add one thing to an existing system that was not built following this series, then I cannot promise that these instructions will work for you, although they probably will. If you’ve started from something other than a non-NOOBS Raspbian image, then you’ll probably need to adjust for that.
Please refer to the series Introduction for a list of all the different posts in the series.
Self-Promotion: I have recorded this series as a screencast for Pluralsight:
If you have a Pluralsight subscription, please consider watching it. Reading the instructions is one thing, but watching it done demystifies the whole process.
My previous home “server” before embarking on this series was just an old laptop of mine. It wasn’t particularly strong, but it could run CrashPlan and serve files. One advantage it had was that, being a laptop, it had a built-in battery and knew how to shut itself down if the power went out. Of course, I had to go downstairs and start it back up once the power was restored, but at least nothing got corrupted.
If you have a desktop computer at home or at work, you may also have an Uninterruptable Power Supply (UPS) under your desk. This is basically a battery big enough to power your computer and monitor long enough for you to save what you are doing and shut down gracefully. Most modern UPS units also have a USB port on them and come with software so that when the power goes out, the UPS can tell the computer to automatically suspend, hibernate, or shut itself down depending on how you’ve configured it.
It shouldn’t surprise you that there are UPS options available for the Raspberry Pi as well. Take the CW2 “Pi UPS” (http://www.piups.net), for example. This product will work fine for most simple Raspberry Pi projects running off of an SD card, but my particular installation has a RAID enclosure hooked up to it. I don’t think AA batteries are going to cut it. What I need is something that will keep the hard drives spinning long enough for the Pi to shut down safely.
I’ve had my Raspberry Pi Home Server plugged into a UPS for well over a year now, and it survives power outages just fine, shutting itself down safely, and restarting automatically. My Raspberry Pi Home Server is attached to a CyberPower SX550G. I chose this model because:
- It has a USB connection to the computer.
- It was on sale for $40.
- I’m cheap.
It’s a 550VA battery backup, which probably wouldn’t get you very far with a full-sized desktop computer, but it should be more than adequate for a Router, a Raspberry Pi, and a couple of drives. It could probably run those devices for a good couple of hours if needed, actually. I haven’t done the math, but if not for the external drives, it could probably run the Pi for days.
So how can we get the Pi to use it intelligently? It certainly didn’t come with a ready-made software package for the Pi, although Linux software is available for it.
Network UPS Tools (NUT)
The Network UPS Tools package, aka “NUT” (http://www.networkupstools.org), is a collection of programs meant to make UPS hardware from different manufacturers work in roughly the same way. It’s available for a wide variety of platforms, one of which happens to be Debian Linux, of which Raspbian is a variant.
NUT consists of three major components
- A driver to communicate with your particular UPS using whatever protocol it supports, and translate that into a common API.
- A daemon (service) that connects via the driver and acts as a communication hub.
- A client program that can perform various tasks such as shutting down the computer when the power state reported by the daemon own sitechanges.
There are a few other components, such as command-line utilities that can tell you about the current state of the UPS, or allow you to make changes to the UPS configuration. For the most part though, we’re only concerned with the three components I just mentioned.
Note: NUT works with a wide range of UPSes, but without owning one from each different manufacturer and/or vintage, I can’t create instructions specific to each model. Questions about how to get NUT working with your particular UPS are best addressed on the project’s own site, or its GitHub site. For the most part, though, they should all work the same way.
If your UPS is older, and doesn’t have a USB port, but has a 9-pin serial port, you are totally on your own. I tried to make an older serial-ported UPS work through an RS232/USB adapter, but as it turns out, the UPS didn’t actually communicate over the serial port. It just shorted two pins together to mean that everything was okay. Maybe you could hack something together using the GPIO pins. If so, you’re a better man than me.
Installing Network UPS Tools (NUT)
Simplicity itself. Like most things we’ve installed in this series, NUT is available through apt-get
sudo apt-get install nut
Select your driver
Find the driver for your particular UPS by looking at the compatibility list on the NUT site (http://www.networkupstools.org/stable-hcl.html). If you can purchase a UPS that’s on the list, then that’s great. If you don’t find your UPS on the list, that doesn’t mean it won’t work, though. For instance, my UPS isn’t on the list, but a ton of other devices from the same company are, and they all seem to use the same driver (usbhid-ups). I gave it a shot, and it works just fine. YMMV
Configure the UPS
Once you’ve identified the driver for your UPS, you’ll need to edit the ups configuration file.
sudo nano /etc/nut/ups.conf
This file, like all of the NUT configuration files, is very well documented inline, and explains all of its different options. At the bottom of the file, you’ll add an entry for your UPS. You’ll need to give it a name, specify a driver, and give it a description. There is also an option to specify a port. For units that connect via a USB cable, this is meaningless, but it’s still required, so use the value “auto”.
[RPHS] driver = usbhid-ups port = auto desc = "CyberPower SX550G"
The name in square brackets is so you can tell multiple UPS devices apart in case you have one NUT server monitoring multiple devices. Unless you’re building something really esoteric, you probably only have one UPS like me, so for lack of anything better to call it, I’ve named mine “RPHS” after the computer it serves. You can put anything you want in the description, so I just put the make and model of the device for reference. The end result should look something like this:
That’s it for configuring the UPS itself. Close and save the file (ctrl-x, y, enter).
Configure the daemon
A daemon is the Unix/Linux term for any invisible background process. Windows folks call these “services”. For NUT, there is a daemon that is in charge of listening to the UPS via the driver, and telling the client applications what to do. Edit its configuration file like this:
sudo nano /etc/nut/nut.conf
For this simple application, where both the client and the server programs will be on the same computer (the Pi), go to the bottom of the file and set the MODE to “standalone”.
Close and save the file.
Verify hardware configuration
To check whether the driver and daemon are configured correctly, you can simply start up the service.
sudo upsdrvctl start
The first time I tried to connect to the UPS I got the error “could not detach kernel driver from interface 0: Operation not permitted”. I rebooted and tried again, and everything was fine.
Notice that this time I got a message about “Duplicate driver instance detected”. This is because now that I have things configured correctly, the driver started up automatically when I rebooted. Not only that, but the daemon should be running now as well. Check it like this:
sudo service nut-server status
You should get a message that the NUT server is running. You can now ask the NUT server questions about the status of the UPS using “upsc”, one of several command line utilities that apt-get installed. Substitute the name you gave your UPS above as needed.
You’ll get quite a long list of information about the configuration and status of your UPS.
Depending on the make and model, you’ll get more or less detailed information.
Configure the monitor
That’s two out of the three layers. Last but certainly not least is the “upsmon” client. This is the part that will actually shut down the computer when the NUT server says so.
Define credentials that the monitor client program will use to connect to the server.
sudo nano /etc/nut/upsd.users
Go to the bottom and define two users, one called “admin” and one called “upsmon”. You can actually name them anything you want, but naming the “monitor” user after the program that will use it (upsmon), seems to be the convention. You give the “admin” user rights to issue commands and change configurations with the “actions” and “instcmds” settings. The “upsmon” user has no such rights, it’s just there to listen and shut the computer down when the power goes out.
[admin] password = mypasswd actions = SET instcmds = ALL [upsmon] password = mypasswd upsmon master
Since this is the computer that’s actually in charge of monitoring the UPS, set the “upsmon” setting to “master”.
Next, edit the configuration file for the upsmon client program.
sudo nano /etc/nut/upsmon.conf
This configuration file is pretty long, and has a lot of options. The one we’re interested in is about five pages down. Look for the example lines that start with “MONITOR”, and create a new entry on the blank line below that section. There are six parts to this setting.
- The keyword “MONITOR”. It does have to be all uppercase, by the way.
- The “system” name in the format UpsName@HostName. I called my UPS “RPHS”, and since we’re running in standalone mode, we can just use “localhost” for the host name, so the resulting “system name” is “RPHS@localhost”.
- The “power value”. This only applies to big servers with multiple redundant power supplies. Just set it to “1”.
- The user name that you established in the upsd.users file (upsmon) .
- The password that you established in the upsd.users file (mypasswd).
- A value indicating whether this computer is the master or slave. You can read about the distinction in the upsmon.conf file itself, but for a standalone system like this, use “master”.
When you’re done, it should look something like this.
This next part is optional, but handy for testing that your system is working. Scroll down a bit further, and look for the NOTIFYFLAG section. There are two entries there, “ONLINE” and “ONBATT”, but they seem to be commented out by default in the current installation. Remove the pound sign from the beginning of these two lines, so that NUT can tell us about the state of the UPS when it changes.
Close and save the file.
Next up, a little permissions wrangling. You need to set up the various configuration files to be readable by the NUT components that use them, but not by other users. This prevents anyone from reading the password, and sending unauthorized commands to the server to shut everything down. It may be overkill for a simple home network, but it’s also really simple to do.
sudo chown nut:nut /etc/nut/* sudo chmod 640 /etc/nut/upsd.users /etc/nut/upsmon.conf
You should get no complaints
Depending on the sophistication of your particular UPS, you may be able to send it commands to do things like initiate a self-test, or simulate a power failure. You can get a list of what your particular UPS supports with
sudo upscmd -l rphs
The number and type of commands will vary by manufacturer and model, so your output may not match mine. There are a few commands here worth mentioning, though. The “load.off” command will shut down the UPS immediately. Think of it as the “goodbye world” command. You generally don’t want to mess with that one. You could actually use this command to turn a second UPS on and off, allowing your Pi to control the power to something else. I’ll leave that one up to your imagination, but there are certainly cheaper ways to automate things.
The “beeper.mute” command will temporarily silence the warning beep that my UPS makes when the power goes out. This will make testing the system a bit less annoying here in the next section. The “beeper.disable” command would probably have the same effect, but on a more permanent basis.
Testing the system
Restart the NUT service and client daemons to ensure that they load all of the configuration changes we’ve made.
sudo service nut-server restart sudo service nut-client restart
At this point, you can unplug your UPS from the wall and, after a short delay, you should get a message that the system is now running on battery power.
IMPORTANT: Wall messages like this don’t seem to show up in Terminal windows on the desktop. If you want to test this part for yourself, connect via SSH using a program like PuTTY on Windows.
If you plug it back in, you’ll get another message that power has been restored.
So far, so good. Now for the real test. Unplug the UPS from the wall and leave it unplugged. If your UPS supports it, now is a good time to issue that “beeper.mute” command. In my case, I issued the “upscmd rphs beeper.mute” command, and was prompted for a user name and password. We established the user name “admin” in the config file above.
You can sit and stare at the screen, wondering when it will shut down, or you can periodically check on the status to see how fast you’re using up the battery. I plugged my laptop charger and a television into the UPS to speed things along. A good, old-fashioned 100-Watt bulb would help, too.
Eventually, when the battery gets low enough, the system should shut itself down.
Plug the UPS back in, and if you’re lucky, everything will start back up again. For some models, even after the power is restored, you may have to physically press a button on the UPS to start everything back up. Mine starts up on its own, so a few minutes later I was back up and running.
Email notifications (optional)
Wall messages are just fine if you’re connected via SSH or looking at a monitor connected directly to the Pi, but if your server is headless or you’re running the desktop, you won’t see them. We need a way to be notified when something goes wrong. NUT can be configured to call any arbitrary command when it has something to say, so we’re going to set it up to send out email messages. This can inform you of power issues even when you’re not connected to the Pi at all.
We’re going to need to install a couple utilities to make this happen. I’ll be using ssmtp because it’s the simplest thing that works. Because it only knows how to send emails, it doesn’t leave any services running in the background using up CPU time. If you’ve already configured some other kind of mail agent on your system, then you’ll need to adjust accordingly.
sudo apt-get install ssmtp mailutils
Next, we’ll edit ssmtp’s configuration:
sudo nano /etc/ssmtp/ssmtp.conf
For this demonstration, I’ll be configuring ssmtp to work with gmail. If you want to use your ISP’s email services, then check out the ssmtp documentation, but most of the concepts should be the same.
Change the “mailhub” setting to point to your email server. For gmail, that will be “smtp.gmail.com:587”. For gmail, you’ll also need to add the “UseSTARTTLS=YES” setting. Scroll to the bottom of the file and add settings for “AuthUser”, “AuthPass”, and uncomment the “FromLineOverride”. The result should look something like this:
Note: If you have two-factor authentication set up with gmail, then the AuthPass setting will need to be an application-specific password. You can read more about that here.
Test your email setup by sending yourself an email from the command line.
echo "Test body" | mail -s "Test subject" [YOUREMAILADDRESS]
Check your inbox for the email. If you get it, then you’re ready to configure NUT to use ssmtp. Some wireless providers have special email addresses you can use to send texts to your phone. I have configured my NUT installation to send me texts rather than plain old emails, so I’ll notice them immediately.
Next, edit the NUT client configuration one more time to set up the email notifications.
sudo nano /etc/nut/upsmon.conf
Scroll down to find the NOTIFYCMD section, and add a line that says
You presumably don’t want to be notified about every single power event that happens, so scroll down to the NOTIFYFLAGS section again, and add “+EXEC” to the end of the messages you want to receive emails for. I’m going to enable emails for the ONLINE and ONBATT events. The end result looks like this:
All that’s left is to create the script that we named in the NOTIFYCMD setting, “upssched-cmd.sh”.
sudo nano /etc/nut/upssched-cmd.sh
Paste in the following, substituting the email address where you want the notifications to go.
#!/bin/sh echo "$*" | mail -s "Message from RPHS" [YOUREMAILADDRESS]
Exit Nano, saving the file (Ctrl-X,Y), and make it executable.
sudo chown nut:nut /etc/nut/upssched-cmd.sh sudo chmod 700 /etc/nut/upssched-cmd.sh
Test the new script by calling it in the same way that NUT will in the event of a power event.
sudo /etc/nut/upssched-cmd.sh "This is a test message"
If you got that message, then everything is configured. Restart the NUT client so that it will pick up on the configuration changes.
sudo service nut-client restart
And now you can test the system again by unplugging the UPS from the wall. If everything is configured correctly, you should get an email (or text message) telling you that the power has gone out. Plug the UPS back in, and you should get another message telling you about it. Now you’ll know about power problems even when you’re not at home.
Adding more Pis to the same UPS (optional)
With Raspberry Pis being so cheap, you may very well have more than one. Perhaps you’ve split CrashPlan or MiniDLNA off onto a Pi all by itself. Maybe you went a little crazy and built a Pi-powered super-computer cluster. If, for any of these reasons, you have multiple Pis, and you’d like them to share the same UPS, how will they all know when the power’s gone out? After all, you can only plug the USB cable into one of them, and buying a separate UPS for each Pi would be overkill, right?
The great thing about NUT being split up into layers is that you can run multiple client instances against one server. Normally, this is the sort of thing you’d only see in a large server rack, where you’ve assigned one computer to watch the battery and tell all the others when the power goes out. It’s not the sort of thing regular home users usually care about, but Raspberry Pi owners are not regular home users.
If you do happen to have multiple Pis, getting them all to share a single UPS and shut down gracefully is actually really simple.
Reconfigure NUT on the server
Earlier, we configured NUT in “standalone” mode, which means that the server and client were on the same machine. It also means that the server isn’t expecting any other clients to be talking to it, so it simply isn’t listening for them. With a little bit of reconfiguration, we can tell the NUT server to listen for clients other than itself.
Edit the NUT configuration file.
sudo nano /etc/nut/nut.conf
Scroll down to the bottom, and change the mode from “standalone” to “netserver” (not “nutsever”, mind you).
Close and save the file (ctrl-x, y, enter)
Next, you’ll need to configure credentials for the remote machines to use when connecting to the server.
sudo nano /etc/nut/upsd.users
Add a new user at the bottom. You can call it anything you like, but I’ve chosen “upsmon-remote”. Give it a password, and specify that it is a upsmon slave.
Next, you need to tell the NUT server to listen for client connections. Edit the UPS daemon configuration file.
sudo nano /etc/nut/upsd.conf
Find the “listen” section, and add a listen directive using the IP address of your server. If you don’t configure anything, the NUT server will listen only to the computer that it’s on, which is localhost, or IP address 127.0.0.1. Since you now want NUT to listen for clients on other systems as well, you’ll need to specify a real IP address.
Adding the server’s own IP address might seem a little redundant, but remember that NUT is made to work on all kinds of equipment, and it’s very common for larger-scale servers to have multiple network interface cards, and you’d only want it to listen for NUT traffic on the “inward” facing one.
Because you will still want to run a ups monitoring client locally on the server itself, and you’ve now overridden the defaults by specifying one IP address, you’ll need to explicitly add an entry for localhost (127.0.0.1) back in as well, otherwise the local ups monitor will stop working. The result should look something like this:
Note: You’ll need to substitute your own Pi’s address in place of 192.168.1.11. That’s just the address where my own Pi server lives. The default port that NUT listens to is 3493. If you wanted to change that, for some reason, you would do that here. I’m going to leave it at the default port, though.
Reboot the server to get things reconfigured and restarted.
Double check that you can still communicate with the NUT locally:
sudo upsc rphs
You should get the same kind of listing of UPS settings and status as you did in standalone mode:
If you get some kind of error instead, make sure that you added an entry for localhost (127.0.0.1) in addition to the Pi’s regular IP address.
You can actually run NUT configured this way, but without any clients connected, and it will behave in pretty much the same way as it did in standalone mode, but it will still be listening for additional clients over the network.
Configure the client machines
Install NUT on each additional Pi that you intend to run from the UPS.
sudo apt-get install nut
For these additional client-only installations, you can skip configuring a UPS driver and proceed directly to configuring the client.
sudo nano /etc/nut/nut.conf
Go to the bottom of the file, and set MODE to “netclient”.
Next, edit the upsmon configuration file.
sudo nano /etc/nut/upsmon.conf
This time, configure the client to talk to the remote server for information, and configure it as a slave. This time, the “system name” will not be “RPHS@localhost”, but “RPHS@192.168.1.11” (again, substitute your server’s IP address).
If you remember from earlier, the first part of this “system name” is the name you gave your UPS, and the second part is the address of the server it’s attached to. The name and password should match the “upsmon-remote” name and password from above, and the final parameter will be “slave” instead of “master”. The result should look like this:
Note: My other Pis are all busy right now, so I’m doing the edits (but not saving them) on my original server for these screenshots. Please ignore the name in the title bar.
The difference between “master” and “slave” has to do with when each one will shut down. When the UPS says the power has dipped below the safe threshold (20% for my UPS), the server (the master), will tell all of the clients (the slaves) to shut down first before shutting down itself.
Like on the server, you’ll need to set up the permissions so that the NUT configuration files are readable by the nut user. Unlike the server, however, you don’t need to touch the upsd.users file because users are defined on the server, not the client.
sudo chown nut:nut /etc/nut/* sudo chmod 640 /etc/nut/upsmon.conf
From the slave system, you can issue the same kinds of commands you could run from the master system. Use this to verify that everything is communicating properly.
sudo upsc RPHS@192.168.1.11
I’ve used the IP address because name resolution didn’t work for me. It’s one of those things I’ll probably learn to set up someday, just not today.
Test the system
Once again, unplug the UPS, and you should see warning messages appear on both the server and client(s) right away. Again, you may want to mute the beeper if your hardware supports it, and plug something in to help the battery drain faster.
Apart from the name of the server sending the message, and the fact that the client shut down first, you wouldn’t be able to tell the difference between the client and server installations, even though only the server is actually attached to the UPS.
Lather, Rinse, Repeat
Repeat as necessary for each additional Raspberry Pi you are plugging in to the same UPS. That’s all there is to it. When the power goes out, all your Pis can now shut themselves down safely.
You know the drill by now. Shut down the server, and back up the SD card.
In the next post, we’ll reconfigure the Pi to boot from the hard drive instead of the SD card.
Mel, great instructions and very useful; thank you. However, I can’t see where you linked upsmon to the script. I needed to add in upsmon.conf, NOTIFYCMD “/etc/nut/upssched-cmd.sh” to get the email notifications working.
I’ll take a look this weekend. I seem to have lost a few things when creating the new versions of these posts. Thanks for telling me.
I just checked the article, and those instructions are there, or am I misunderstanding your comment. Search on the page for “upssched”, and you should find the part you were looking for.
Mel, please accept my apologies; I must have overlooked it.
Thanks you very much for these detailed instructions!
I’m trying to get this setup for a CyberPower CP1500PFCLCD, but I’m not able to get NOTIFYCMD to fire. I can run the script manually and it works, but it won’t fire with I unplug the USB cable. I **do** get the SYSLOG+WALL message, but the NOTIFYCMD script never fires. Did you run into any issues with it? Below is the segment of my upsmon.conf file. Do you have any ideas?
MONITOR cyberpower1@localhost 1 upsmon_local local1 master
NOTIFYFLAG ONLINE SYSLOG+WALL
NOTIFYFLAG ONBATT SYSLOG+WALL
NOTIFYFLAG LOWBATT SYSLOG+WALL+EXEC
NOTIFYFLAG FSD SYSLOG+WALL+EXEC
NOTIFYFLAG COMMOK SYSLOG+WALL+EXEC
NOTIFYFLAG COMMBAD SYSLOG+WALL+EXEC
NOTIFYFLAG SHUTDOWN SYSLOG+WALL+EXEC
NOTIFYFLAG REPLBATT SYSLOG+WALL+EXEC
NOTIFYFLAG NOCOMM SYSLOG+WALL+EXEC
NOTIFYFLAG NOPARENT SYSLOG+WALL
Offhand, I’d say it’s unplugging the USB cable if that’s what you really meant. Without the USB cable the UPS can’t communicate with the computer. If that’s not what you meant, sorry, but that would definitely explain it. You want to unplug the power cable to the ups.
Looking at your config though, you need to add “exec” to the events you want to fire the script like onbatt and online.
Thanks for the reply! I actually figured it out right after I posted this. It was a typo on my part, stupid mistake but it’s working now. Thanks!
This was super helpful in setting up my Raspberry Pi to configure NUT with my CyberPower OR500 1U UPS. It has been quite a struggle configuring NUT to work properly. With your detailed instructions, I am finally able to get basic UPS online/on battery emails sent to me. THANK YOU so much for taking the time to write a detailed setup and configuration guide.
Thanks for the comment. I’m glad the post was helpful.
Pingback: Upgrading from Jessie to Stretch | MelGrubb.ToBlog()
I too found your instructions useful and helpful.
I’m having an issue with the LISTEN command.
If I run LISTEN on localhost, I have no issues.
If I run LISTEN on localhost AND my static (private) IP address, I get a “not listening” error.
Nov 12 09:28:11 PiNUT upsd: not listening on 192.x.x.4 port 3493
I’m running latest Raspbian (stretch) with all updates/upgrades.
I’m only running NUT – this is the only package I have installed.
Do you think there’s some kind of firewall or anything stopping this from working?
Sorry for the late reply. This one missed my inbox somehow. Normally I get email notifications for all the comments. Can you describe how you have the two addresses represented in upsd.conf? I have two LISTEN entries in mine, on two separate lines like this:
LISTEN 127.0.0.1 3493
LISTEN 192,168,1,10 3493
The second one should be changed to be the IP address of the Pi that is running the NUT server, the one that you’re configuring.
Pingback: Raspberry Pi and a UPS (Battery Backup) – Arduino Boards News
When I get my Pi to send an email I get a bounced email as well, saying
The response was:
DNS Error: 10739207 DNS type ‘mx’ lookup of raspberrypi responded with code NXDOMAIN Domain name not found: raspberrypi
I am terribly sorry. I just found this comment sitting in my “Pending” folder after all this time. I usually get notifications about all comments, and approve or reply from there, but this one somehow got “lost in the mail”. Hopefully you figured out what was going on. I’d have to go into research mode, but off the top of my head, it sounds like the Pi is trying to send the email itself rather than using a third-party service like Gmail. There’s all kind of configuration that has to go into making yourself a real email sender, and then you just get swallowed up by other people’s spam filters because no-one’s ever heard of your server before. That’s why I’ve never bothered trying to do that. It’s easier and more generally successful to just use an existing service that servers already trust.
Mel, This is a fantastic little set-up. It works very well. Are you aware of any graphical tools that would display the information on screen in a window also? Perhaps a dashboard panel style app?
Information about the UPS? Not that I know of. You might see if there are any NUT plugins for Nagios, but that’s a whole blog post on its own, and is very fiddly to set up. I have the Pi send an email to my phone when the power goes out or comes back. Since the cable modem and Pi are both on the UPS, they keep on working… at least for a little while.
Mel, I’ve found a little Python utility that seems to do a perfect job. I have a headless set-up most of the time, and to be honest, I have to try to remember the commands to check the status.
The utility can be found here.
This is a great guide, and still relevant and accurate as of Nov 2018. I used these procedures to setup a server that is connected to the UPS’s, and 3 raspberry pi clients and one pfsense client. Upon testing, graceful shutdowns happened as expected after some time. Not the fault of this guide, but I would also have liked to have my windows 10 box which manages a video surveillance system power down gracefully as a client, but it doesn’t look like the windows version of nut are anywhere near ready for use. The windows binarieis are labeled as “beta” as of Nov 2018, but doesn’t even install and run without hackery and bandages.
Thanks Mel I finally saw the example!! I truly appreciate this post. Thanks for sharing your knowledge.
Thank you!!!! Thank you! I am having a problem with this section:
The keyword “MONITOR”. It does have to be all uppercase, by the way.
The “system” name in the format UpsName@HostName. I called my UPS “RPHS”, and since we’re running in standalone mode, we can just use “localhost” for the host name, so the resulting “system name” is “RPHS@localhost”.
The “power value”. This only applies to big servers with multiple redundant power supplies. Just set it to “1”.
The user name that you established in the upsd.users file (upsmon) .
The password that you established in the upsd.users file (mypasswd).
A value indicating whether this computer is the master or slave. You can read about the distinction in the upsmon.conf file itself, but for a standalone system like this, use “master”.
Would it be possible for you to list the exact commands, as I cant tell the syntax from the examples in the file. I used your usernames and passwords by the way. Thanks again
The sections you’ve quoted are breaking down the example in the screen shot that immediately follows. I think that has what you’re looking for. It would be hard to give the complete line since I don’t know for sure that your system has the same name as mine. Also, I don’t know what password you’ve chosen.
I finally installed the system and it works. The problem is I continuously get a message from the raspberry that the UPS Cabin@localhost is unavailable.
The messages are sent every 5 min and seem to stop shorty after a reboot. Then they start up again. The raspberry does not appear to lose network connectivity, nor is the USB cable to the UPS disturbed.
Configuration. Are you able to query the ups with the upsc command? Start there and work forward. If it’s not the physical connection, then it must be the connection from that layer to the monitor layer. NUT is very modular. It’s also possible that something about it has changed since I wrote the article. I’ll have to work through it all again to be sure, but that won’t happen for at least a couple weeks.
Great tutorial, easy to follow.
I’ve got the master and a few slaves set up and everything works properly as defined, but I am having some trouble adding some extra functionality.
I have a server that I would like to shutdown as soon as the master detects that the system is on battery. The server I want to shutdown is not critical and shutting it down would extend the life of the battery and my network devices (modem, router, switch, etc).
What would I need to do to achieve this?
Followed your guide step by step and I have it set up as such. I would like to expand this a bit and I am having troubles figuring it out. I’ve got a server that I would like to shutdown immediately when the UPS goes into battery mode. I can’t seem to figure it out.
(Also, if this ends up being my second post with this same question, whoops. I don’t see it so I’m assuming it didn’t stick.)
Comments require approval before they show up publicly so that I can filter out the spam. Without further research, my guess is that it would take a second server and UPS. You might try the NUT forums, maybe someone knows a trick, but my understanding is that all the decisions are made by the server, and it’s either happy or unhappy about the current state of the battery. There’s no tiered shutdown that I’m aware of.
Ah, sorry for the double post.
Thanks, I’ll do some digging and try the NUT forums.
What is missing is the same explanatory instruction, “how to configure the web interface (nut-cgi).”
Busy working on a DYI project and got this working awhile ago and had to retackle this project.
Using the guide a second time just wanted to say a massive thanks for all the effort you went through here. You made my task way less of a nightmare.
Thank you for the kind words. I’m glad the series was helpful for you. Hopefully it’s all still up to date enough. Each new release seems to invalidate some part or another, and I haven’t had the time to go through it all end to end in a while. Hopefully soon I can make another pass at it.
Addendum to this setup for Rpi from 10-09-2019
If the Gnome/Raspbian Pi desktop widget called “Nut Monitor” starts and “can” monitor.. but it cannot execute Device commands. Then “stop” the connection first by clicking the glade-ish Upper “Grey” Button bar under the words –[Nut Server]– that says “Disconnect”. The client will automatically disconnect and close its connection and present a [Logon] dialog window where you can insert the [Login / Password]. But Step 1, be sure to use the drop down to select the Device: clicking on the drop down should auto-populate the UPS device already setup. Then Step 2, check the box ‘Use authentication’. Then Step 3. type in the Username and Password of the Nut Daemon account with permission to Set or Execute commands. In this example: username = admin ; password=mypasswd Then Step 4. Press the [Connect] button bar.
It will then reconnect with authentication and all the Glade-ish strobing Up and Down command lists can be picked form and actually executed on the UPS.
And a little more detail.
The Gnome nut-client has a feature to “store” the username and password for the UPS management as a ‘favorite’. I didn’t find any detailed documentation.. but on Rpi the primary startup item is under [Pi] button, [Internet], [Nut Monitor].
Right click on [Nut Monitor], click on ‘properties’ and then the [Desktop Entry] tab.
By default it will only have [Nut-Monitor] as the Command:
Change that to [Nut-Monitor -H -F upsname] and then click OK to save it.
The -H will autohide the client so when it starts it shrinks to the taskbar system tray area.
The -F will autoconnect using the last saved ‘Favorites’ username and password.
And now when it start up and you open the GUI client and try to execute commands on the UPS they will simply work as expected.
First time, you start it with no Favorites you will have to “define” a Favorite before you can use it. You have to disconnect from the UPS with the Disconnect button. Then select a Host, Device, Use authentication, Login, Password
Example: localhost (you cannot use 127.0.0.1)
> hit Refresh button
> check box ‘Use authentication’
> “do not” click Connect yet
> click Favorite menu
> click “Add”
> Enter a name for this fvorite
> Example: cyberhome1
> click “Add”
Its a Glade’y Python widget kind of app so the usually awkward dialog behaviors apply.. you sort of have to accomodate and coax the app to accept the new Favorite.. but it finally saves it.
Hi Mel, thanks for the extensive write-up. As many have mentioned it is very useful and good to follow. We appreciate your time.
I have tried to apply this to my Pi (v2) with Noobs running and Eaton UPS. The Nut server/client appear to be working and giving back information when queried. The email script (to SMS) works when I run it via the command line. However, it won’t execute the script/email when there is a power failure. I have the +EXEC on the two commands and notifycmd with the script. I am not sure what I am missing, any ideas?
I wouldn’t suspect that NOOBS has anything to do with it, but in general I can’t really guarantee results if the basic system isn’t set up from a stock Raspbian image. Still, if everything else appears to be working, then I don’t think that’s the cause. As a first step, I’d make sure NUT is reacting at all. Unplug the UPS from the wall and make sure you’re getting the “Wall” messages so you know that NUT has at least noticed the power outage. If you know that it’s reacting, then that only leaves the notification itself, and you’ve established that the email portion seems to be working. That leaves just the running of the command itself. A typo in the upssched-cmd.sh file itself, or in the commands to make it executable might result in the script not working. You could also try running the script directly from the command line. I’m not sure if you mean that you’ve run the sample echo command, or if you’ve run the .sh file as shown in the article directly after the “chown” and “chmod” commands. If running ‘sudo /etc/nut/upssched-cmd.sh “This is a test message”‘ doesn’t work, then it’s almost definitely a problem with the script or the permissions assigned to it. I suppose NUT itself could be running with lower privileges than the script requires, but if everything else is working, I wouldn’t think so. That only leaves the configuration file itself, and if the NOTIFYFLAG lines look like the ones in the screenshot (not commented, with +EXEC added onto the existing contents), then I’m afraid I’m out of ideas. It’s probably time to hit the NUT forums because we’re no probably not talking about anything specific to the Raspberry Pi or this guide at that point. If you get it to work, please reply with the solution so that others and “future you” can find it.
Hi Mel, thanks for the quick reply. Firstly, the “future you” comment made my day! 🙂 These posts and questions help me so often. Basically I had to change your config to use msmtp instead of ssmtp (so that I could define the from account/user, etc). The email/text message notification via your script was working in my testing, the problem was I was testing with sudo before it. This was the problem. The script was only working as root, not as the user who would be executing it (nut I assume). So when I changed the permissions for msmtp to 0644 it worked. Ie. sudo chmod 0644 /etc/msmtprc
Hopefully that makes sense for me, or any future me’s who may read this issue… Thanks
Great post. I used nut some year back with a UPS connected to a desktop.
I have some low power thin terminals I run 24/7/365 for various tasks, such as weather monitoring. A new 24/7/365 is to monitor seismic activity. Initially I used a laptop as I worked out many software coding aspects I needed to do. As usual what was to be a month or so of coding work turned out to be about 9 months! You know the drill of what think will take in time and effort for a DIY project is not what seems. I have now powered off the laptop I was using as decided just too long using as “temporary”.
I bought a Pi Hat to provide UPS function to the Pi. Sadly I have found it has many design defects such that cannot even do the basics of charge the battery as the charge LED flashes for over 36 hours and flashes frequent random manner constantly.
I decided I like to consider a “classic” UPS. The one challenge I see is if the UPS software, NUT, in this case is configured to shut down the Pi at some configured UPS battery level, it appears the Pi will not restart on own as the UPS still has power via battery. This means when power is restored the UPS switches back to mains supply from battery supply. With the Pi shut down via the NUT configuration I cannot see how the Pi will power back on as I see it and have read your excellent write up above. It just seems from a concept point of any UPS or UPS software related to the Pi the Pi will not restart. I find that difficult to believe and hope maybe I missed reading your write up or what I am assuming that a battery protected outlet would have no power gap so the device power off via UPS software would power on on own again. To my thinking this is simply due to using an external UPS and not a shortfall of any UPS software or how any USP software is configured.
I think it depends on the ups. At least one that I’ve used turned itself off at the end of the shutdown cycle. When the power was restored, it came back on by itself. To the Pi, this just looks like being plugged in again, so it restarts on it’s own. Some are configurable. Check your manual or read up on the model you’re considering.
I’m glad I found your writeup! It was the first one I was able to get this working on my Raspberry Pi. Thank you!
I’m glad it helpd. I had trouble putting everything together the first time too. That’s why I assembled this whole series.
Thanks for such a comprehensive tutorial. Everything seems to work as you described with the exception of the email setup…I am on Debian 10 (Buster) and I keep getting the message that the process exited unsuccessfully…any ideas of the commands to get that to work…I am relatively new to Linux and Raspberry Pi, but trying to learn.
Well, that’s not really a lot to go on, unfortunately. So that’s basically one of the commands just saying “nah”. Which step are you on, exactly? Have you managed to send an email manually from the command line? If you’re following along with the instructions, then one of the first things I’d do is make sure you’re typing all the commands by hand rather than copying them directly from the blog posts. WordPress can somtimes change what I’ve written, changing hypens to em-dashes, and messing with the quotes. I thought I’d gotten them all fixed, and hadn’t heard of any problems in, well… years really. If you were typing them in manually already, then proofread very carefully, or perhaps even give the copy/paste route a shot just to eliminate any typing mistakes. As I said, I thought I’d gotten all the formatting problems worked out years ago. If none of that helps, please let me know what command you were running at the time.
I tried to leave a detailed comment yesterday, but it seems to have vanished. I will try again
I can’t get out of an endless error loop with WordPress thinking I have multiple accounts. Is there a direct way I can contact you? “sarasotajon” (above) is not working. I am trying from another email address.
I should have given you a more-detailed description of what was happening. Here it is:
I am running Debian 10 Buster.
I followed your setup instructions, but I am now repeating them as you suggested, typing in the commands rather than copying and pasting.
The admin and upsmon users are configured.
I checked the configuration of the Monitor:
MONITOR UPS@localhost 1 upsmon 52Peppermill55 master
And the two flags “online” and “onbatt” are set
When I test the server restart, I get this:
sudo service nut-server restart
Broadcast message from nut@raspberry-pi (somewhere) (Sat Feb 27 11:04:51 2021):
Communications with UPS UPS@localhost lost
Broadcast message from nut@raspberry-pi (somewhere) (Sat Feb 27 11:05:01 2021):
Communications with UPS UPS@localhost established
Then I unplugged the power cord, and after about 15 minutes, the RPi shutdown, just as it was supposed to, and I got messages that battery was low, and that the system was shutting down.
So on to email…ssmtp version 2.64-8, and mailutils version 1:3.5-4 installed fine.
Then configured ssmtp:
# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
# Where will the mail seem to come from?
# The full hostname
# Are users allowed to set their own From: address?
# YES – Allow the user to specify their own From: address
# NO – Use the system generated From: address
and finally tried to send a test email:
echo “Test body” | mail -s “Test subject” email@example.com
mail: cannot send message: Process exited with a non-zero status
I edited the ssmtp config file thinking that “AuthUser” is looking for perhaps just “jhkinne1”, but making that change produced the same
mail: cannot send message: Process exited with a non-zero status
I appreciate your help.
ssmtp has been basically deprecated. I need to update this post, but I did work out the replacement steps as part of my last Pluralsight course update. I’ll try to summarize the changes here, although it won’t be properly “wordy”. We’ll be using msmtp instead in this version.
sudo apt-get install msmtp msmtp-mta
Configuration (Details at https://wiki.archlinux.org/index.php/Msmtp)
sudo nano /etc/ssmtp/ssmtp.conf
Update the contents to look like this:
account default : gmail
If you have two-factor authentication enabled on your gmail, then you’ll need to create an app-specific password for this to use, just like the original instructions outlined.
Test email with
echo “Test email body” | mail -s “Test email subject” YOUREMAILADDRESS
Edit NUT again
sudo nano upsmon.conf
Update configuration as before
Create/Update the shell script
sudo nano upssched-cmd.sh
Paste in the following text
echo “$*” | mail -s “Message from RPHS” YOUREMAILADDRESS
Everything else should be the same. Hopefully I can update the instructions soon.
Hey Mel, thanks very much…that works really well, and it’s nice getting a text message as well. One piece I should mention…if a person is using gmail, there may be a message to the effect that the user cannot be authenticated, in which case “Allow apps from less-trusted sources” needs to be turned on in Google settings.
Thanks again, now on to locking down SSH and configuring the Pi to be a WOL server.
I had a issue with the nut permission to open the port, them I solved this adding nut user to dialout group, them the server work fine, until I add LISTEN 192.168.0.123 to use monitoring in another machine, even if I remove 127.0.0.1 from the LISTEN line, the system doesn´t work, and if I return the LISTEN to 127.0.0.1 everything come back to work again.
What is wrong with that?
Can you describe more about the setup? I assume you’re trying to run two systems from the same UPS here, right? Otherwise, I don’t think you’d need to communicate through any ports at all.
If I had to guess though, make sure the IP address you add a Listen section for is the server’s own address, not the secondary client that’s trying to connect. You’re telling the NUT server to listen ON that IP address since it’s possible to have multiple network addresses (wireless and wired, for instance). You can also tell it to listen to multiple interfaces at the same time, such as when listening to 192.168.?.? as well as 127.0.0.1. You never want to remove the 127.0.0.1 entry, unless the server were somehow not wanting to listen to monitor its own power supply as well. I suppose there might be a reason for that, but not at this scale.
Also, make sure you’ve specified the port (3493) as well as the IP address.
Yes, but after so much digging I discovered the problem, it was the option of not waiting for the network to go up before booting, this gave the ups-server an error when it tried to listen the IP before the network went up.
Found that only LISTEN 0.0.0.0 3493 works better for me than LISTEN 127.0.0.1 3493 and LISTEN 192.168.x.x 3493.
Technically, that tells NUT to listen on every interface. If you’ve only got one then I suppose the end result is the same though.
I was delighted to run across your blog on NUT. Have been contemplating something like this for awhile but wasn’t sure I had the chops to make it happen. Your instructions have gotten me on the path.
I have been able to get the UPS device to talk to the Nut-server; thank you. The problem I’m having at the moment is with the mail element. I’ve used the instructions in your update of 3/2/2021 re: switching from ssmtp to msmtp but I cannot get the msmtp broker [I guess that’s what it is] to send mail to my gmail account. I’m getting the message “mail: cannot send message: Process exited with a non-zero status”. Some background:
* I’ve gone to my Google Account and gotten a password for an application I called “mail”. I’ve entered that password to the ssmtp.conf file.
* I’ve modified the ssmtp.conf file per your 3/2/2021 instructions. That file is in the /etc/ssmtp directory with permission set to -dw-r—–.
* I’ve created the ~/.msmtp.log file. As far as I can tell it is not being written to. It’s permission is set to -dw-r—–.
* I’ve run sudo find -name *log to see if I can find another log file that will tell me what’s going on. The mail.log file is empty as is .msmtp.log. Clearly I’m not looking the the right place.
I’m realizing that I just don’t know enough to competently debug this and, now, am just flailing.
I’d sure appreciate some guidance.
Thank you very much,
Nothing is jumping out at me immediately. I’d have to walk through the whole thing again to be sure, but I actually did that just a couple weeks ago when I had to rebuild, but I was following my Pluralsight instructions at the time. They should be identical though. The first thing I’d do is debug msmtp in isolation. There’s nothing pi-specific about that, so I’d search for problems with msmtp. Once you can send an email to yourself from the command line, then you need to get NUT calling the right thing.
One thing to make sure of is that, if you copied and pasted anything from the blog post, that quotes didn’t get turned into smart quotes or hyphens into emdashes. That sadly happens a lot on blog posts. I thought I had weeded all of those out of mine, but maybe you’ve found a new one. I’d go through all the code and configs, and write over any dashes or quotes they contain to make sure they’re just “plain old” characters. It’s just a shot in the dark, but has turned out to be the source of a few mysteries over the course of this series.
Thank you so much for this, best tutorial out there!
Pingback: Information to Community UPS Instruments (NUT) on a number of Raspberry PI’s (Openhab 2.5 and different methods) – Tutorials & Examples – PiGurus
Absolutely great write-up, I and many others appear to have used this succefully – kudos! This setup worked perfectly on one Pi which is monitoring a Cyberpower 650VA UPS.
However, On a second Pi, monitoring an older 625VA I’ve had problems for some reason. Biggest appears to be that NUT doesn’t recognize my older 625VA UPS – when I run “sudo upscmd -l pi-ups” I get “Error: Unknown UPS.” I’m using the usbhid-ups driver.
I tried substituting “powerpanel” as the driver name in the ups.conf file but that didn’t work at all. Any suggestions, or am I just SOL w/using this UPS with NUT?
Without a more specific model number, I’d just be guessing. 625VA is just a capacity. The model number would be something more like “ST625U”. If you can figure out the model, then you should be able to look it up here: https://networkupstools.org/stable-hcl.html and that should tell you the driver that it needs.
Pingback: Tutorial – Shutdown Script USV / Raspiblitz | Hosting and Scripts