Our 'net connection is soooo bad that I wrote this

Ovid on 2008-08-12T13:59:36

At the hotel, our 'net connection goes up and down constantly. Rather than keep switching over to a terminal to ping something, I wanted to be alerted whenever the 'net was back. Searching for tools for OS X to do this for me was problematic because, well, the 'net kept going down. Now I get Growl alerts.

#!/usr/bin/perl

use strict;
use warnings;

use Mac::Growl ':all';
use Net::Ping;
use Getopt::Long;

# set up options
my ( $sleep, $sticky ) = ( 60, 1 );
GetOptions(
    "sleep=i" => \$sleep,     # number of seconds
    "sticky!" => \$sticky,    # sticky growl notifications?
);

# set up MacGrowl
RegisterNotifications( $0, [qw/ping/], [qw/ping/], );
my ($image) = grep { -e } (
    '/Applications/Utilities/Installer.app/Contents/Resources/Caut.tiff',
'/Applications/Utilities/Installer.app/Contents/Plugins/TargetSelect.bundle/Contents/Resources/Caut.tiff'
);


# set up ping
my $host = shift || 'www.google.com';
my $p = Net::Ping->new( "tcp", 3 );
$p->{port_num} = ( getservbyname( "http", "tcp" ) || 80 );

# do that first ping
my $HOST_LAST_STATUS = !!( $p->ping($host) );
show_status( $host, $HOST_LAST_STATUS, $sticky, $image );

while (1) {
    my $host_status = !!( $p->ping($host) );
    if ( !$host_status ) {
        $host_status = retry( $p, $host );
    }

    if ( $host_status ne $HOST_LAST_STATUS ) {
        show_status( $host, $host_status, $sticky, $image );
    }
    $HOST_LAST_STATUS = $host_status;
    sleep $sleep;
}

sub retry {

    # because it might just be a flaky, intermittant connection
    my ( $p, $host ) = @_;
    for ( 1 .. 3 ) {
        if ( $p->ping($host) ) {
            return 1;
        }
    }
    return '';
}

END { $p->close() }

sub show_status {
    my ( $host, $status, $sticky, $image ) = @_;
    $status = $status ? 'up' : 'down';
    PostNotification( 
        $0, 
        'ping', 
        "$host status", 
        "$host is $status", 
        $sticky,
        -1,
        $image
    );
}


Whoa!

CromeDome on 2008-08-12T16:22:26

Holy crap, that rocks! :)

HardwareGrowler?

elliot on 2008-08-12T19:55:11

Doesn't this already handle what you want? It's in the Extras included with Growl.

Re:HardwareGrowler?

Ovid on 2008-08-13T00:29:41

I've no idea if that handles that or not. Until today, I've never touched Growl aside from third-party software which uses it. I'll look into that though. Thanks for the tip :)