MacOS Power Management with Hammerspoon

03 Jun 2020 in Odds and Ends

I've been using caffeine to prevent my machine from sleeping for as long as I can remember, but whilst setting up a new machine I realised that I didn't have it installed and wondered if I could replicate the functionality using Hammerspoon.

It turns out that you can! Hammerspoon has a caffeinate module for changing power management settings. You can use the module to lock the screen, start the screensaver and a whole set of other power related actions. To control the machine sleeping automatically, we use the set method which expects three parameters: sleepType, aValue (boolean, should the type of sleep be prevented) and acAndBattery (boolean, should this be applied on battery power too).

I want it to apply on AC and on battery, so I always set the third parameter to true.

Here's the code from my init.lua file:

lua
hs.hotkey.bind({"cmd", "alt", "ctrl", "shift"}, "I", function()
hs.caffeinate.set("displayIdle", true, true)
hs.caffeinate.set("systemIdle", true, true)
hs.caffeinate.set("system", true, true)
hs.alert.show("Preventing Sleep")
end)
hs.hotkey.bind({"cmd", "alt", "ctrl", "shift"}, "O", function()
hs.caffeinate.set("displayIdle", false, true)
hs.caffeinate.set("systemIdle", false, true)
hs.caffeinate.set("system", false, true)
hs.alert.show("Allowing Sleep")
end)

To prevent sleeping I press cmd+alt+ctrl+shift+I and to enable it I press cmd+alt+ctrl+shift+O. I chose I and O as they're the standard power management symbols.

Using a Streamdeck

You may have noticed that cmd+alt+ctrl+shift+I isn't particularly easy to press. That's because I don't actually use that shortcut myself, but instead use a streamdeck button to run that hotkey.

This provides a nice visual indicator if I have disabled my machine from sleeping and means that I don't accidentally press the key combination.