I'm working on a raspberry project with a RPi B+, running Debian stretch. I've included a LED which should turn on when the Pi establishes an internet connection, and should turn off when this connection is lost. To do this, I have written a small python script which checks the connection in increasing time-intervals. To test connectivity I'm using this function:
def test_internet(timeout = 5): try: urlopen('http://www.google.com/',timeout =timeout) return True except: return False
After each check the program sleeps for a fixed time (5 seconds), and then re-checks. Every check is logged to a log-file.
The loop works fine when testing on my computer. I've tested with the RPi by starting the loop, and after a few positive returns, plug-out the ethernet cable. I expected the log to keep recording entries every 5 seconds, although now stating 'False', and turning the LED off.
Unfortunately, whenever I unplug the ehthernet cable, the log shows the
test_internet is initiated, but then hangs untill I replug the cable. If I wait really long (like a full minute), it does record a 'False' and turn off the LED. In that case, re-inserting the cable brings the LED back up within a few secs, so no delays there.
It seems like the script is somehow freezing when connectivity drops. Is that possible? How could I circumvent this?
EDIT I've created a simple check bash script which sleeps for five seconds after execution (giving me time to unplug the ethernet cable) and then checks for connectivity. If there's no interwebs, it turns off the LED:
#!/bin/bash sleep 5 if [ ! -d /sys/class/gpio/gpio27 ] then echo "27" > /sys/class/gpio/export sleep 0.1; fi echo "out" > /sys/class/gpio/gpio27/direction wget -q --spider http://google.com if [ $? -eq 0 ]; then echo "Online" #Turn on connectivity LED echo "1" > /sys/class/gpio/gpio27/value else echo "Offline" #Turn off connectivity LED echo "0" > /sys/class/gpio/gpio27/value fi
If I run this and unplug the cable, after 5s the LED is turned off. However if I replug it, the LED jumps back on, and the terminal prints 'online'. Seems like it repeats the code when it comes back online. Seems like the plugging/unplugging does something to the Pi, cluttering the view.