Prevent sleep while streaming from Plex in Linux - take 2

Sun 16 October 2016

I recently upgraded my home server from Linux Mint 17.3 to Mint 18 (effectively moving the Ubuntu codebase from 14.04 to 16.04). Despite some nice changes, the update broke the earlier script I threw together that prevents the system from sleeping while streaming media through Plex. Sometime around Ubuntu 15.04, there was a change from using sleep.d to using systemctl to handle these sorts of things. I'm not really sure what that means or why the change was made. All I know is it broke the script so it again falls asleep while streaming.

To save energy, I don't want the server running all the time. It's set to wake-on-LAN so I can call it up when I need it. Then, if not actively streaming, I want it to go to sleep after 15 minutes. After bit of googling, I came up with this solution that works with Mint 18 (and presumably any Ubuntu using systemctl rather than sleep.d).

Systemd service

The new system uses a systemd service, which is completely different from the old sleep.d method. We can still take the approach of checking the Plex server's status webpage and parsing out the number of active sessions, but it must be run as a service. Here's what to do.

The Code

Description=Inhibit suspend if Plex is streaming media

ExecStart=/bin/sh -c "if [ `curl localhost:32400/status/sessions 2>/dev/null | sed -n 's/.*MediaContainer size=\"\(.*\)\".*/\1/p'` -gt 0 ]; then exit 1; else exit 0; fi"


Notice the ExecStart line looks a lot like the meat of the previous sleep.d script, but condensed into a single line. This is what checks the Plex status to pull out how many "MediaContainers" are active, and if more than 0, it exits with an error code of 1.  The "RequiredBy" tag here says that the sleep target service needs this script to finish successfully (error code 0) before running.

Save the code to a file in /etc/systemd/system (use sudo for root permissions). I called it /etc/systemd/system/plexkeepawake.service. Then activate the service with:

systemctl enable plexkeepawake.service

And that's it! You could add other services in a similar way to prevent sleep while serving Samba shares, running backups, etc. by changing what's in the if-block.