I realise this question is a bit old... however, as there are multiple ways of accomplishing the same result, I thought it worth sharing one more: using Hammerspoon and a couple of snippets of Lua code.
Hammerspoon is a tool to automate various operations on a Mac. I'm not associated to it in any way, I literally installed it to try and achieve the same purpose as the OP.
For anything you want to automate, you write little Lua scripts; in this case, I created a network.lua
file which I saved next to the main configuration file, $HOME/.hammerspoon/init.lua
. Here's the contents of both:
# init.lua
-- Imports
local homeNetwork = require "network"
-- Toggle WiFi based on Ethernet being connected or not
homeNetwork.setEthernetInterface("USB 10/100/1000 LAN")
systemWatcher = hs.caffeinate.watcher.new(homeNetwork.handleWifi)
systemWatcher:start()
# network.lua
local M = {}
local ethernetInterface
local function isEthernetConnected()
ipv4 = hs.network.primaryInterfaces()
activeInterfaceName = hs.network.interfaceName(ipv4)
return activeInterfaceName == ethernetInterface
end
local function toggleWifi()
desiredState = not isEthernetConnected() and true or false
if hs.wifi.interfaceDetails()['power'] ~= desiredState then
hs.wifi.setPower(desiredState)
newState = desiredState and "on" or "off"
hs.alert.show("Turning wifi " .. newState)
else
hs.alert.show("Wifi already in the desired state")
end
end
function M.setEthernetInterface(ethernetInterfaceName)
ethernetInterface = ethernetInterfaceName
end
function M.handleWifi(event)
if event == hs.caffeinate.watcher.systemDidWake then
toggleWifi()
elseif event == hs.caffeinate.watcher.screensDidUnlock then
toggleWifi()
end
end
return M
The only thing you'll have to customise is the name of your Ethernet interface in init.lua
; in my case it's "USB 10/100/1000 LAN"
because I'm using a dock. You can find the name for yours in the Network
section of your System Preferences.