Skip to content

Instantly share code, notes, and snippets.

@deviationist
Last active January 13, 2025 12:15
Show Gist options
  • Save deviationist/a0e28a06ea4c1280ec78a1ce37007b74 to your computer and use it in GitHub Desktop.
Save deviationist/a0e28a06ea4c1280ec78a1ce37007b74 to your computer and use it in GitHub Desktop.
Hammerspoon Lua-script for disabling/enabling Bluetooth when the lid is closed/opened
require "string"
-- Make sure to install Hammerspoon (brew install --cask hammerspoon) and blueutil (brew install blueutil).
-- Ensure to give sufficient access in macOS so that the commands can be ran:
-- -- System Settings -> Privacy & Security -> Accessibility -> Allow Hammerspoon
-- -- System Settings -> Privacy & Security -> Bluetooth -> Select app "Hammerspoon"
-- Place this file in your home folder, then open Hammerspoon and click "Reload config"
function checkBluetoothResult(rc, stdout, stderr)
-- Use for debugging
--print(string.format("Command executed with rc=%d", rc))
--print(string.format("stdout: '%s'", stdout or "nil"))
--print(string.format("stderr: '%s'", stderr or "nil"))
if rc ~= 0 then
print(string.format("Error executing `blueutil`: rc=%d stderr=%s stdout=%s", rc, stderr, stdout))
end
end
function bluetooth(power)
print("Setting Bluetooth to " .. power)
-- Convert power to 0/1 instead of on/off
local powerState = power == "on" and "1" or "0"
local t = hs.task.new("/opt/homebrew/bin/blueutil", checkBluetoothResult, {"--power", powerState})
t:start()
end
function f(event)
if event == hs.caffeinate.watcher.systemWillSleep then
bluetooth("off")
elseif event == hs.caffeinate.watcher.screensDidWake then
bluetooth("on")
end
end
watcher = hs.caffeinate.watcher.new(f)
watcher:start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment