Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save deviationist/83ac383056ccbf13b6822b5343a3915f to your computer and use it in GitHub Desktop.

Select an option

Save deviationist/83ac383056ccbf13b6822b5343a3915f to your computer and use it in GitHub Desktop.
A script that will disable bluetooth when the lid of a Macbook is closed.
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