Skip to content

Instantly share code, notes, and snippets.

@don-code
Created January 3, 2021 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save don-code/14406518b58844e87b7f2daa948ae07a to your computer and use it in GitHub Desktop.
Save don-code/14406518b58844e87b7f2daa948ae07a to your computer and use it in GitHub Desktop.
Script to detect connectivity loss on a Raspberry Pi and notify with the LEDs
#!/bin/bash
# This script will provide visual feedback that a Raspberry Pi 2B/3B has lost
# local network or Internet connectivity by blinking the two LEDs. Link state
# and Internet connectivity are represented as two different blink patterns,
# to help determine whether the Pi or the switch has had its cable fall out.
# The following table describes the LED flash patterns:
# Local | Internet | LED Flash Pattern
#=======|==========|=========================================================
# OK | OK | Unaltered (red = power, green = storage)
# OK | Fail | Red blinks; green is turned off.
# Fail | OK | This is an invalid state. Red and green set to solid on.
# Fail | Fail | Red and green both blink.
#
# Change INTERNET_HOST to any pingable host appropriate for your use case.
# I used my ISP's (Comcast's) DNS server.
#
# Intended to be run on a 1-minute cron, e.g.:
# [don@hermes ~]$ cat /etc/cron.d/connectivity_alert
# * * * * * root /usr/local/bin/connectivity_alert.sh
set -euo pipefail
DEFAULT_TRIGGER_LED0=mmc0
DEFAULT_TRIGGER_LED1=input
INTERNET_HOST=75.75.75.75
function set_led() {
echo $2 > /sys/class/leds/led$1/trigger
}
function set_leds_default() {
set_led 0 $DEFAULT_TRIGGER_LED0
set_led 1 $DEFAULT_TRIGGER_LED1
}
LINK_UP=0
if [ "$(cat /sys/class/net/eth0/operstate)" == "up" ]; then
LINK_UP=1
fi
INTERNET_REACHABLE=0
if ping -c 1 $INTERNET_HOST > /dev/null 2>&1; then
INTERNET_REACHABLE=1
fi
if [ $LINK_UP -eq 1 -a $INTERNET_REACHABLE -eq 1 ]; then # All normal.
set_leds_default
elif [ $INTERNET_REACHABLE -eq 0 ]; then # No Internet connectivity - flash LED1.
set_led 1 heartbeat
if [ $LINK_UP -eq 0 ]; then # No network connectivity - flash LED0.
set_led 0 heartbeat
else
set_led 0 none
fi
else # Link up but no internet - should never get here. Complain loudly by setting both solid.
set_led 0 default-on
set_led 1 default-on
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment