Switched: Detect state changes in pipe

I am sitting in a café and the internet is flaky. The wifi is stable, though, so my dumb Xubuntu thinks that all is well, while a sturdy ping in a terminal window tells me otherwise.

This sucks.

A few minutes (cough) later, I am getting Desktop notifications when the internet connectivity drops, or gets re-established.

A Desktop notification telling me that Internet just got back on.

This is all thanks to switched, a Python script that detects state changes.

Example for the ON state, when I am connected to the internet:

64 bytes from tf-in-f100.1e100.net ( icmp_seq=3259 ttl=47 time=125 ms

Example for the OFF state, when I am not:

ping: sendmsg: Network is unreachable

Whenever one changes into the other: That's a state change.

Stitching this all thogether: Ping exposes internet connectivity, switched script detects state changes, and notify-send makes a notification pop up.

The essence of switched:

is_on = False
while True:
    line = sys.stdin.readline()
    match = pattern.match(line)
    if bool(match) ^ bool(is_on):
        is_on = not is_on
        print_on_change(line, "ON" if is_on else "OFF")

And I can use it like so:

ping google.com 2>&1 \
| ./switched.py '.*time=\d+' 'Internet is ' -print0 \
| xargs -0 -n 1 notify-send

The gist is on github.