Skip to content

Instantly share code, notes, and snippets.

@tanc
Created December 17, 2012 17:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tanc/4320379 to your computer and use it in GitHub Desktop.
Save tanc/4320379 to your computer and use it in GitHub Desktop.
An Applescript which checks for a working WiFi connection and on failure restarts WiFi. I use it with launchd and run it every 30 seconds as I have a sometimes inconsistent 3G tethered connection.
# Airport toggling based on a script by nomadcoder:
# Toggle WiFi: https://github.com/nomadcoder/launchbar-scripts/blob/master/Toggle%20WiFi.applescript
#
# The purpose of this script is to check to see whether the wifi connection can reach the
# internet and if unsuccessful restarts the wifi connection.
#
# I personally run it every 30 seconds as a launchd job.
# Fetch the name of your AirPort Device
set airPortDevice to do shell script "/usr/sbin/networksetup -listallhardwareports | awk '{if($3==\"Wi-Fi\"){getline;print}}' | awk '{print $2}'"
# Fetch the current state of the AirPort device
set airPortPower to do shell script ("networksetup -getairportpower " & airPortDevice & " | awk '{print $4}'")
if airPortPower is equal to "on" then
try
do shell script "ping -c 1 -t 3 www.google.com"
set internetavailable to true
on error -- can't reach google, lets try another site.
try
do shell script "ping -c 1 -t 8 www.yahoo.com"
set internetavailable to true
on error -- can't reach this site either so reset connection.
set internetavailable to false
notifyFailure()
toggleWifi("off", airPortDevice)
toggleWifi("on", airPortDevice)
end try
end try
if internetavailable is equal to true then
do shell script ("terminal-notifier -remove 'icc'")
end if
end if
on toggleWifi(value, device)
do shell script ("/usr/sbin/networksetup -setairportpower " & device & " " & value)
end toggleWifi
# Uses the terminal-notifier gem to place a message in notification centre
# https://github.com/alloy/terminal-notifier
on notifyFailure()
do shell script ("terminal-notifier -group 'icc' -title 'Internet down' -message 'There was a problem accessing the internet. WiFi has been restarted.'")
end notifyFailure
@tanc
Copy link
Author

tanc commented Dec 17, 2012

Note: requires https://github.com/alloy/terminal-notifier for notification centre support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment