Automate your Mac with Hammerspoon

You maybe know these situations. You just left your home and commute to work by the public transport. While traveling you connect your MacBook with your personal hot spot or maybe with a hotspot that is provided by the train or bus company. Anyway, you start to work and you're maybe listening to music with a pair of headphones on. Suddenly you realize you forgot to mute your MacBook and passengers around you might be entertained by audio feedbacks of your terminal or other applications.

Would it be nice to automatically mute the Mac when I connect to foreign Wifi hotspots? And turn the volume back up when I return home? Well this can be easily achieve with Hammerspoon. Hammerspoon allows you to implement such an use case using Lua. The script below welcomes you with a message and sets the volume to 80% when you connect to your Wifi at home. When you connect to another Wifi, it mutes the MacBook.

wifiWatcher = nil
homeSSID = "my-wifi"
lastSSID = hs.wifi.currentNetwork()

function ssidChangedCallback()
    newSSID = hs.wifi.currentNetwork()

    if newSSID == homeSSID and lastSSID ~= homeSSID then
        -- We just joined our home WiFi network
        hs.audiodevice.defaultOutputDevice():setVolume(80)
        hs.alert.show("Welcome home")
    elseif newSSID ~= homeSSID and lastSSID == homeSSID then
        -- We just departed our home WiFi network
        hs.audiodevice.defaultOutputDevice():setVolume(0)
        hs.alert.show("You are now connected to " .. newSSID)
    end

    lastSSID = newSSID
end

wifiWatcher = hs.wifi.watcher.new(ssidChangedCallback)
wifiWatcher:start()

I hope you found the short article helpful and enjoyed it.