Skip to content

Instantly share code, notes, and snippets.

@deviationist
Last active January 13, 2025 12:14
Show Gist options
  • Save deviationist/63741dd7bc13fdac8c33654bbf8b8d4d to your computer and use it in GitHub Desktop.
Save deviationist/63741dd7bc13fdac8c33654bbf8b8d4d to your computer and use it in GitHub Desktop.
Hammerspoon Lua-script for disconnecting/connecting to a Bluetooth device 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"
-- Get the MAC address of your bluetooth device (use command "blueutil --paired")
-- Place this file in your home folder, then open Hammerspoon and click "Reload config"
macAddress="" -- Bluetooth Device MAC Address
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 disconnect(power)
print("Disconnecting Bluetooth Device")
local t = hs.task.new("/opt/homebrew/bin/blueutil", checkBluetoothResult, {"--disconnect", macAddress})
t:start()
end
function connect(power)
print("Connecting Bluetooth Device")
local t = hs.task.new("/opt/homebrew/bin/blueutil", checkBluetoothResult, {"--connect", macAddress})
t:start()
end
function f(event)
if event == hs.caffeinate.watcher.systemWillSleep then
disconnect()
elseif event == hs.caffeinate.watcher.screensDidWake then
connect()
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