PLEX server should keep Mac awake after wake-on-lan

Also, as @Ekomax mentions, after your last Plex activity, you have to wait for 5-10 minutes before the Mac will sleep of its own accord.

But you should still be able to manually sleep your Mac, even if caffeinate is running.

@ Parnty

is it safe to delete the caffinate log file under logs PMS? Not that it is disturbing. But it will grow continously. Best regards

@Ekomax yes it’s fine to delete it at any time.

I’ve created an improved version of my script. The benefit is that it now only keeps the Mac awake if a user is actually using Plex.

The old version simply checked if the Plex log file had changed. If so, it ran caffeinate to prevent the Mac from sleeping for 5 minutes. But Plex quite often carries out background tasks while no-one is using it. This meant it was updating its log file many times a day, and my script was then preventing the Mac from sleeping too often.

The new version does an additional check to see if a new message containing ā€œauthenticated userā€ has been written to the log. Only then does it run caffeinate. So far it’s been working great. No more ā€œfalse positivesā€!

Here are the steps to update your script:


  1. From the Dock, click Launchpad > Other > Terminal

  2. In the Terminal window that pops up, copy-paste the following (and hit return):

echo "" >> ~/Library/Scripts/PlexCaffeinate.sh && open -a TextEdit ~/Library/Scripts/PlexCaffeinate.sh
  1. In the TextEdit window that pops up, delete all of the existing text, then copy-paste the following:
#!/bin/bash

defaults write com.plexapp.plexmediaserver logDebug true

plexLog=~/Library/Logs/Plex\ Media\ Server/Plex\ Media\ Server.log
caffeinateLog=~/Library/Logs/Plex\ Media\ Server/Plex\ Caffeinate.log

prevLastModified=`stat -f %m "$plexLog" 2>/dev/null`
prevLastAuthenticated=`tail -20 "$plexLog" | \
                       grep "authenticated user" | \
                       tail -1 2>/dev/null`
while true; do
    lastModified=`stat -f %m "$plexLog" 2>/dev/null`
    if [ -z "$lastModified" ] || \
       [ "$lastModified" = "$prevLastModified" ]; then
        sleep 30
    else
        lastAuthenticated=`tail -20 "$plexLog" | \
                           grep "authenticated user" | \
                           tail -1 2>/dev/null`
        if [ -z "$lastAuthenticated" ] || \
           [ "$lastAuthenticated" = "$prevLastAuthenticated" ]; then
            sleep 30
        else
            echo "`date` Caffeinate..." >> "$caffeinateLog"
            caffeinate -s -t 300 &
            sleep 299
            echo "`date` Caffeinated." >> "$caffeinateLog"
        fi
        prevLastAuthenticated=$lastAuthenticated
    fi
    prevLastModified=$lastModified
done
  1. In the TextEdit menu bar, click File > Save, then File > Close

  2. Go back to the Terminal window, and copy-paste the following (and hit return):

launchctl unload ~/Library/LaunchAgents/PlexCaffeinate.plist && sleep 3
launchctl load ~/Library/LaunchAgents/PlexCaffeinate.plist

That’s it - the new script is now being used, and you can safely quit Terminal.

This is a great idea; and I really hoped it would solve my problem. Unfortunately; OpenPHT seems to regular ping and re-auth with the server to make a GET request to /channels/all when just sitting there idling at the home area, thus keeping the Mac awake indefinitely. No idea why though. It seems odd. I thought it might be the rotating background art PHT does; but that doesn’t seem to be it.

I tried logging OpenPHT out (so it wouldn’t auth), and then allowing localhost connections without auth on Plex, but OpenPHT didn’t seem to be able to locate or connect to my media server, so I guess that option is out. :confused:

Anyone have any ideas on this one?

@voiceinsideyou said:

Anyone have any ideas on this one?

Do you require to have OpenPHT always open? Depends how you are running the mac, as a HTPC?

I’m running a mini as HTPC with a Harmony Remote, and when switching activities or turning off, I get OpenPHT to close, therefore the mini goes to sleep shortly after (if no other Plex server activity).

@Jad_23 said:
Do you require to have OpenPHT always open? Depends how you are running the mac, as a HTPC?

I’m running a mini as HTPC with a Harmony Remote, and when switching activities or turning off, I get OpenPHT to close, therefore the mini goes to sleep shortly after (if no other Plex server activity).

Thanks for the suggestion - I guess I could try that (as much as I loathe tinkering with Harmony configs :slight_smile: ). I’m using it in a similar Mac Mini HTPC setup; also with a Harmony remote. I don’t require OpenPHT to be open. Currently switching activities sends the sleep command to OpenPHT which sleeps the Mac Mini itself; but doesn’t close OpenPHT.

@voiceinsideyou said:
Currently switching activities sends the sleep command to OpenPHT which sleeps the Mac Mini itself; but doesn’t close OpenPHT.

I think there is an option in the OpenPHT config (rather than Hamony config), that closes the program rather than sleeps/shuts down the mini. Then the power saving config of the mini allows it to sleep afterwards (other than for any PMS activity as defined by the scripts in this thread of course!).

Having it configured this way for me has had several other benefits. OpenPHT (and PHT before that) starts ā€˜fresh’ every time the activity starts, which seems to help with earlier issues of the software crashing or freezing from either been left open for long periods of time or waking direct from sleep. The other advantage is that I use ControlPane to monitor what software is running, and when it detects OpenPHT start, it can send a wake-on-lan packet to my NAS where my media is stored.

@Jad_23 said:
I think there is an option in the OpenPHT config (rather than Hamony config), that closes the program rather than sleeps/shuts down the mini. Then the power saving config of the mini allows it to sleep afterwards (other than for any PMS activity as defined by the scripts in this thread of course!).

Yeah, I’m aware of that setting and have been playing with it on ā€œquitā€ for a couple of days. Also needed an extra Harmony step to press the ā€˜play’ button to actually restart OpenPHT after Mac resume; which relies on the PlexHTHelper background process that listens even when Plex isn’t running. There’s a setting in OpenPHT to allow that too :slight_smile:

@Jad_23 said:
Having it configured this way for me has had several other benefits. OpenPHT (and PHT before that) starts ā€˜fresh’ every time the activity starts, which seems to help with earlier issues of the software crashing or freezing from either been left open for long periods of time or waking direct from sleep. The other advantage is that I use ControlPane to monitor what software is running, and when it detects OpenPHT start, it can send a wake-on-lan packet to my NAS where my media is stored.

Haven’t had any such stability problems with OpenPHT in general; even with it open long periods of time; but having it start and stop every time has caused some other annoyances for me, so not sure if I will stick with this experiment. A couple of times (probably Harmony timing issues with infrared) it has resumed the mini but Plex hasn’t started. Once somehow OpenPHT started in the background and other windows were on top. Irritations I guess.

Starting of thinking of giving up and going for an Nvidia Shield setup instead :slight_smile:

@voiceinsideyou said:
Haven’t had any such stability problems with OpenPHT in general; even with it open long periods of time; but having it start and stop every time has caused some other annoyances for me, so not sure if I will stick with this experiment. A couple of times (probably Harmony timing issues with infrared) it has resumed the mini but Plex hasn’t started. Once somehow OpenPHT started in the background and other windows were on top. Irritations I guess.

Yes, OpenPHT does seem to have fixed up many bugs and memory leaks - amazing what the community can do! The issues I mentioned were back when it was still PHT and not so actively worked on by PLEX in regard to these fixes.

I too very occasionally find OpenPHT doesn’t open from the activity or opens up in a smaller window, but these are small, expected irritations when running a mini as a HTPC I guess. Mostly can be fixed from the remote and don’t need to resort to remotely logging in. I find the setup runs well and gets a high WAF so that is important!

@voiceinsideyou said:
Starting of thinking of giving up and going for an Nvidia Shield setup instead :slight_smile:

Wait, so no tinkering with scripts and terminal commands? Where’s the fun in that! :wink:
(To be honest, if I had a 4K TV I’d probably consider this too!)

After I use the improved script nothing is no longer written to the Caffeinated.log. And it doesn’t work anymore. What could be wrong? :slight_smile: the old PlexCaffeinate.sh works.

Hi. First of all, thank you for the script Parnty! I really appreciate it since this topic was driving me crazy.

I followed your steps for the updated script and while I do see ā€œCaffeinateā€¦ā€. and ā€œCaffeinated.ā€ in the Caffeinate.log (as expected), I still have the issue that my Plex Media Server randomly disappears, sometimes even while watching an episode. I’m using RasPlex to access my media.

Since MALmen mentioned that the old PlexCaffeinate.sh works, I changed it back to the original one and will now pay attention to how my PMS behaves. I do like the premise of your updated script though and I was wondering if you could take a look at the script again to figure out what might not work as it should. I’d be happy to help you out any way I can but I’m no developer by any means. The problem could very well be on my side too of course but I followed your two guides pretty closely and have no idea where I could’ve done something wrong. In that case, I’d appreciate some pointers in the right direction if you don’t mind.

I’m on a Mac Mini (2011) running macOS Sierra in case that matters.

Thank you in advance!

@MALmen @Lyrad87

Both scripts (old and new) are extremely simple. They entirely depend on what the Plex server chooses to write to its log files. So the key to diagnosing any problem is to view Plex’s log files while you browse your Plex library or watch a movie (see instructions below).

With the old script, as long as the Plex log file gets updated with any message when you browse your Plex library or watch a movie, then the script will prevent sleeping.

With the new script, the Plex log file must get updated with a message containing the words authenticated user when you browse your Plex library or watch a movie. If these words do not appear, it’s not going to work.

With my Plex installation, a message containing authenticated user always gets written when I browse/watch. However, on your Plex installation, those magic words may not appear. So the solution is for you to look at the Plex logs while you browse/watch, and see if you can pick out a word/phrase that always gets written to the logs. Ideally, that same word/phrase should not get written to the logs when you are not browsing/watching (i.e. when Plex is just doing its general background housekeeping stuff). This will avoid the script incorrectly keeping your Mac awake when you’re not browsing/watching Plex.

Once you’ve found a suitable word/phrase, you need to modify the new version of the PlexCaffeinate.sh script and replace the 2 occurrences of authenticated user with your magic word/phrase. Once you’ve made the change, you need to restart the script using the launchctl unload and launchctl load commands as per my earlier post.


To view the Plex log files, do as follows:

  1. From the Dock, click Launchpad > Other > Console

  2. In the Console application, on the left-hand side click the triangle to expand ~/Library/Logs then Plex Media Server then click on Plex Media Server.log (make sure you click the file with this exact name)

  3. Keep this window open, then browse your Plex library, or watch a movie. New messages should now continuously appear in the log in Console. Study these messages until you find a suitable word/phrase that keeps reappearing whenever you browse/watch Plex.

Thank you for the insight @Parnty! That was very helpful and I think that is indeed the issue. I’ll check out the log now and hopefully find something that I can use as my trigger word. Thanks again for taking your time to exlain it!

Sorry for the double-post but the issue is somehow still not solved for me. However, I’m not sure if it’s even related to the newly updated PlexCaffeinate.sh script (I’ve used my username as the magic word this time). It could be a whole different issue. At some point, I’m getting the error that my client disconnected, see the bold text in the quote below.

Feb 24, 2017 20:13:22.537 [0x700002b0e000] DEBUG - Auth: We found auth token (xxxxxxxxxxxxxxxxxxxx), enabling token-based authentication.
Feb 24, 2017 20:13:22.537 [0x700002b0e000] DEBUG - Auth: authenticated user 1 as Lyrad87
Feb 24, 2017 20:13:22.537 [0x700002b0e000] DEBUG - Auth: Came in with a super-token, authorization succeeded.
Feb 24, 2017 20:13:22.537 [0x700003132000] DEBUG - Request: [192.168.178.20:37736 (Subnet)] GET /library/parts/15781/1487932105/file.mkv (6 live) TLS Signed-in Token (Lyrad87)
Feb 24, 2017 20:13:22.538 [0x700003132000] DEBUG - Request range: 1431385069 to 0
Feb 24, 2017 20:13:22.541 [0x700003132000] DEBUG - Content-Length of /path/to/TV/show.mkv is 1431441099.
Feb 24, 2017 20:13:22.572 [0x700002a8b000] DEBUG - Completed: [192.168.178.20:37736] 200 GET /library/parts/15781/1487932105/file.mkv (6 live) TLS 34ms 56030 bytes
Feb 24, 2017 20:13:22.573 [0x700002b0e000] DEBUG - Failed to stream media, client probably disconnected: 32 - Broken pipe
Feb 24, 2017 20:13:22.573 [0x700002b0e000] DEBUG - Completed: [192.168.178.20:37734] 200 GET /library/parts/15781/1487932105/file.mkv (6 live) TLS 366ms 2867200 bytes
Feb 24, 2017 20:13:22.604 [0x700002b0e000] DEBUG - Auth: We found auth token (xxxxxxxxxxxxxxxxxxxx), enabling token-based authentication.
Feb 24, 2017 20:13:22.605 [0x700002b0e000] DEBUG - Auth: authenticated user 1 as Lyrad87
Feb 24, 2017 20:13:22.605 [0x700002b0e000] DEBUG - Auth: Came in with a super-token, authorization succeeded.

Does anyone know or have a hunch why this message would appear? For now, I’m switching back to the old PlexCaffeinate.sh script again as I haven’t noticed this error with it so far.

I can see the words authenticated user do indeed appear in your log messages, so in theory my script should work as-is.

However, it’s possible that a message containing authenticated user is not being written to the log file repeatedly while you are browsing/watching (as is the case with my Plex installation).

So what you can do is to click Clear Display in the Console application while you’re viewing the Plex logfile. Then watch a Plex movie. Keep clicking Clear Display every 30 seconds, and check that a new message containing authenticated user keeps re-appearing.

Another thought is, my script includes an optimisation to scan only the last (i.e. most recent) 20 messages in the logfile, looking for authenticated user. If your logfile is being bombarded with messages, it’s possible the authenticated user message is getting lost.

So it could be a question of either too few or too many log messages!

The final thing to do (or maybe the first thing) is to monitor the Plex Caffeinate.log file while you’re watching a movie, and make sure that the Caffeinate... Caffeinated. messages keep getting logged every 5 minutes.

I thought I’ll share my update on this matter. I followed your instructions and checked the console while playing and browsing Plex:

  • authenticated user kept re-appearing often enough - in fact, it appears every 10 seconds.
  • It was also within 20 messages in the log file.
  • Plex Caffeinate.log also did its job accordingly, updating every 5 minutes while watching/browsing or pausing.

Yet I still have random server disconnections stating:

Feb 26, 2017 11:20:49.291 [0x7000021df000] DEBUG - Failed to stream media, client probably disconnected: 32 - Broken pipe

I don’t know what exactly triggers it though. I can watch a TV show, pause it for a moment and lose connection. Sometimes, I watch a TV show, pause it several times and the connection remains steady. It’s really odd and I don’t see a common thread. At this point, I’m not even sure if it’s the script or my computer.

I found some new log messages though that may pinpoint the issue:

Feb 26, 2017 11:20:15.141 [0x700002780000] DEBUG - NetworkServiceBrowser: SSDP departed after not being seen for 21.985055 seconds: 192.168.178.1
Feb 26, 2017 11:20:18.467 [0x700002056000] DEBUG - EventSource: Failure in IdleTimeout (0 - Undefined error: 0).
Feb 26, 2017 11:20:18.467 [0x700002056000] DEBUG - MyPlex: We appear to have lost Internet connectivity, resetting device URL cache.
Feb 26, 2017 11:20:18.467 [0x700002056000] ERROR - EventSource: Retrying in 15 seconds.
Feb 26, 2017 11:20:28.144 [0x700002780000] WARN - NetworkServiceBrowser: Error sending out discover packet from 192.168.178.43 to 192.168.178.255: Can’t assign requested address
Feb 26, 2017 11:20:31.682 [0x700002056000] DEBUG - Failed to stream media, client probably disconnected: 32 - Broken pipe

If anyone has an idea what I could try out, please let me know. I’m reverting back to the original PlexCaffeinate.sh script for now and will monitor if the issue is still happening throughout the day. If it does, I know it’s not the script.

In my opinion, this is unlikely, but it’s a possibility:

The script (both old and new versions) tests if it needs to re-run caffeinate when 299 seconds has elapsed (i.e. 4 minutes 59 seconds) since it originally launched caffeinate for a duration of 300 seconds (5 minutes).

The script then has 1 second to decide if it needs to re-run caffeinate for a further 5 minutes.

Could it be possible that since your CPU is maxed-out doing Plex transcoding, the test whether or not to re-run caffeinate gets slowed-down/delayed, so takes longer than 1 second to run? With the new version of the script, the logic to decide whether or not to re-run caffeinate is more complex (although only slightly!). Could the greater complexity mean it is slower to run on an old system that is already maxed-out doing transcoding?

You can test this by replacing ā€˜299’ in the new version of my script with a lower value: say, ā€˜270’ (that is, 4 minutes 30 seconds). It’s a long shot, but it could solve your problem.

@Parnty
do i have to remove the old script in order to use the new one? and when i want to use the old script again in case the new one does not work on my side, how do i remove it? with the same inputs in terminal as the old one or new ones?

best regards
Ekomax

@Ekomax
No you don’t need to remove the old script. Just follow the instructions in my post that starts with the words: ā€œI’ve created an improved version of my scriptā€.

To change back to the old version, follow the exact same steps, but in step (3) use the original PlexCaffeinate.sh script instead of the new one.

(The original PlexCaffeinate.sh is shown in step (2) of my post that starts with the words: ā€œThis solution no longer works in El Capitanā€.)