orgnizedmess


Better switching between WiFi connections on macOS

I have two access points for better coverage across rooms at home, but the switch between them doesn’t happen as seamlessly as I’d like on my Mac. This is fine for regular browsing, but the lag gets more noticeable when I join a Zoom call. In those cases, I have to switch connections manually and lose a few seconds of what the other person was saying.

WiFi is already configured to do this automatically on the basis of certain metrics, one of them being the RSSI or Received Signal Strength Indicator. When this value passes a certain threshold, the device starts looking for other connections to switch to. On macOS, the threshold is -75dBm. Based on my observations of the RSSI while switching across rooms, I’d like the switch to happen earlier, at -70dBm, same as iOS devices.

Shell scripting attempt

I started writing a shell script for this, but ran into limitations:

  1. wdutil requires sudo to run, which would mean giving my entire script sudo access while running. A workaround that worked without sudo was to write inline Swift code that calls the underlying API, CoreWLAN, as a shell function.

  2. Joining a WiFi network is done using the networksetup command. It requires a password even when joining a previously joined network, and it takes the password as a command line argument, which is an unsafe way of passing passwords. The workaround here was also to write inline Swift code that would take the password from stdin via a pipe.

Since I was writing the core bits of the application in Swift, it made sense to write the entire script in Swift and call out to shell commands where needed.

The Swift script

Starting with the core of the script: it checks if the signal is consistently weak, gets the name of the current network connection (SSID) and switches to the other one as defined in a map, and connects to the target.

#!/usr/bin/env swift

import CoreWLAN
import Foundation

let ssidMap: [String: String] = [
	"A": "B",
	"B": "A",
]

if isSignalWeak() {
	do {
		if let current = try getCurrentSsid(),
			let target = ssidMap[current]
		{
			try joinWifi(ssid: target)
		}
	} catch {
		fputs("\(error.localizedDescription)\n", stderr)
		exit(1)
	}
}

The signal weakness is checked with an initial reading, followed by three more readings if the initial check is past the threshold. If the signal is past the threshold for 2 out of those three readings, then the signal is considered weak enough to switch.

let threshold = -70
let samples = 3
let minWeakSamples = (samples / 2) + 1
guard
	let interface = CWWiFiClient.shared().interface(),
	let interfaceName = interface.interfaceName
else {
	fputs("WiFi interface not found\n", stderr)
	exit(1)
}

func isSignalWeak() -> Bool {
	if interface.rssiValue() > threshold {
		return false
	}
	var count = 0
	for _ in 1...samples {
		sleep(1)
		if interface.rssiValue() <= threshold {
			count += 1
		}
	}
	return count >= minWeakSamples
}

The SSID would have been provided by iface.ssid(), but macOS versions starting from Sonoma redact this information, and require an app to enable Location services permissions to access it. Some workarounds still exist, so I used ipconfig in my script.

I also created helper functions to get a shell command’s output in Swift and to return errors that are caught and printed in the catch loop from earlier.

func makeError(_ message: String) -> NSError {
	NSError(
		domain: basename, code: 0,
		userInfo: [NSLocalizedDescriptionKey: message])
}

func exec(cmd: String, args: [String]) throws -> String {
	let process = Process()
	process.executableURL = URL(fileURLWithPath: cmd)
	process.arguments = args

	let stdout = Pipe()
	process.standardOutput = stdout
	let stderr = Pipe()
	process.standardError = stderr

	try process.run()
	process.waitUntilExit()

	guard process.terminationStatus == 0 else {
		let errorData = stderr.fileHandleForReading.readDataToEndOfFile()
		let error = String(decoding: errorData, as: UTF8.self).trimmingCharacters(
			in: .whitespacesAndNewlines)
		guard !error.isEmpty else {
			throw makeError("\(cmd) exited with status \(process.terminationStatus)")
		}
		throw makeError(error)
	}

	let outputData = stdout.fileHandleForReading.readDataToEndOfFile()
	let output = String(decoding: outputData, as: UTF8.self)
	return output
}

func getCurrentSsid() throws -> String? {
	let output = try exec(cmd: "/usr/sbin/ipconfig", args: ["getsummary", interfaceName])
	guard
		let line =
			output
			.split(separator: "\n")
			.first(where: { $0.contains(" SSID : ") }),
		let value = line.components(separatedBy: ": ").dropFirst().first
	else {
		return nil
	}
	if value == "<redacted>" {
		throw makeError("SSID is redacted, run `sudo ipconfig setverbose 1` and try again")
	}
	return value
}

Once I have the target SSID, the script gets its password from the System Keychain via the security command line tool, and attempts to scan and connect to the network.

func getPassword(for account: String) throws -> String {
	let output = try exec(
		cmd: "/usr/bin/security",
		args: ["find-generic-password", "-wa", account, "-D", "AirPort network password"])
	let password = output.trimmingCharacters(in: .whitespacesAndNewlines)
	return password
}

func joinWifi(ssid: String) throws {
	let password = try getPassword(for: ssid)
	let networks = try interface.scanForNetworks(withName: ssid)
	guard let network = networks.max(by: { $0.rssiValue < $1.rssiValue }) else {
		throw makeError(
			"No network named '\(ssid)' found in scan"
		)
	}
	try interface.associate(to: network, password: password)
}

Putting the parts together, here’s the full script:

wifi-autoswitch.swift
#!/usr/bin/env swift

import CoreWLAN
import Foundation

let basename = URL(fileURLWithPath: CommandLine.arguments[0]).lastPathComponent
let threshold = -70
let samples = 3
let minWeakSamples = (samples / 2) + 1
let ssidMap: [String: String] = [
	"A": "B",
	"B": "A",
]
guard
	let interface = CWWiFiClient.shared().interface(),
	let interfaceName = interface.interfaceName
else {
	fputs("WiFi interface not found\n", stderr)
	exit(1)
}

func exec(cmd: String, args: [String]) throws -> String {
	let process = Process()
	process.executableURL = URL(fileURLWithPath: cmd)
	process.arguments = args

	let stdout = Pipe()
	process.standardOutput = stdout
	let stderr = Pipe()
	process.standardError = stderr

	try process.run()
	process.waitUntilExit()

	guard process.terminationStatus == 0 else {
		let errorData = stderr.fileHandleForReading.readDataToEndOfFile()
		let error = String(decoding: errorData, as: UTF8.self).trimmingCharacters(
			in: .whitespacesAndNewlines)
		guard !error.isEmpty else {
			throw makeError("\(cmd) exited with status \(process.terminationStatus)")
		}
		throw makeError(error)
	}

	let outputData = stdout.fileHandleForReading.readDataToEndOfFile()
	let output = String(decoding: outputData, as: UTF8.self)
	return output
}

func makeError(_ message: String, code: Int = 0) -> NSError {
	NSError(
		domain: basename, code: code,
		userInfo: [NSLocalizedDescriptionKey: message])
}

func getPassword(for account: String) throws -> String {
	let output = try exec(
		cmd: "/usr/bin/security", args: ["find-generic-password", "-wa", account])
	let password = output.trimmingCharacters(in: .whitespacesAndNewlines)
	return password
}

func getCurrentSsid() throws -> String? {
	let output = try exec(cmd: "/usr/sbin/ipconfig", args: ["getsummary", interfaceName])
	guard
		let line =
			output
			.split(separator: "\n")
			.first(where: { $0.contains(" SSID : ") }),
		let value = line.components(separatedBy: " : ").dropFirst().first
	else {
		return nil
	}
	if value == "<redacted>" {
		throw makeError("SSID is redacted")
	}
	return value
}

func joinWifi(ssid: String) throws {
	let password = try getPassword(for: ssid)
	let networks = try interface.scanForNetworks(withName: ssid)
	guard let network = networks.max(by: { $0.rssiValue < $1.rssiValue }) else {
		throw makeError(
			"No network named '\(ssid)' found in scan"
		)
	}
	try interface.associate(to: network, password: password)
}

func isSignalWeak() -> Bool {
	if interface.rssiValue() > threshold {
		return false
	}
	var count = 0
	for _ in 1...samples {
		sleep(1)
		if interface.rssiValue() <= threshold {
			count += 1
		}
	}
	return count >= minWeakSamples
}

if isSignalWeak() {
	do {
		if let current = try getCurrentSsid(),
			let target = ssidMap[current]
		{
			try joinWifi(ssid: target)
		}
	} catch {
		fputs("\(error.localizedDescription)\n", stderr)
		exit(1)
	}
}

From manual to auto-switching

The script in its current form would require running the script manually, and entering a username and password for the Keychain each time the switch happens.

To run the script in the background, I created a LaunchAgent that runs every 30 seconds, saved at ~/Library/LaunchAgents/local.wifi-autoswitch.swift.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>local.wifi-autoswitch.swift</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Users/orgnizedmess/bin/wifi-autoswitch.swift</string>
  </array>
  <key>StandardErrorPath</key>
  <string>/Users/orgnizedmess/logs/wifi-autoswitch.stderr.log</string>
  <key>StartInterval</key>
  <integer>30</integer>
  <key>KeepAlive</key>
  <true/>
</dict>
</plist>

For the keychain prompt, it is possible to provide apps access to specific Keychain items without a prompt. In this case, the access would be provided to security as that’s the binary that access the keychain from my script.

I’m not fully sure if its a good idea, because any application calling security can now access these passwords without the keychain prompt. However, it is also possible to copy the password from the networks list in System Settings, and this is the CLI equivalent of that. If anyone has other suggestions, let me know.

This command updates the existing keychain item for the SSID password and adds security to the item’s access list (a password prompt will appear for confirmation):

security add-generic-password -U \
    -a "$ssid" -l "$ssid" \
    -D "AirPort network password" \
    -T "$(which security)"