#!/usr/bin/perl -w
#
# Audible ping. GNEE!
#
use POE;
use POE::Component::Client::Ping;

my $acksound ='/usr/share/xemacs/xemacs-packages/etc/sounds/the-ping.wav';
my $naksound = '/mnt/win2k/Games/winlemms/sound/ohno.wav';

my $address = shift;
my $timeout = 5;
my $fail = 0;

POE::Component::Client::Ping->spawn(
									Alias     => 'pingthing',  # defaults to 'pinger'
									Timeout   => 10,           # defaults to 1 second
									OneReply  => 1             # defaults to disabled
								   );

POE::Session->create( inline_states => {
									   _start => \&start,
										_stop => \&stop,
										ping => \&ping,
									   pong => \&got_pong });

$poe_kernel->run();

sub start {
  my ( $kernel, $session ) = @_[KERNEL, SESSION];

  $kernel->call( $session,
				 ping => $address );
}

sub ping {
  my ( $kernel, $session ) = @_[KERNEL, SESSION];
  $kernel->post( 'pingthing', 'ping', 'pong', $address, $timeout );
}

sub stop {
  print "It appears we're stopping\n";
}

# This is the sub which is called when the session receives a 'pong'
# event.  It handles responses from the Ping component.
sub got_pong {
  my ( $kernel, $session ) = @_[KERNEL, SESSION];
  my ($request_packet, $response_packet) = @_[ARG0, ARG1];

  my ($req_address, $req_timeout, $req_time)      = @{$request_packet};
  my ($resp_address, $roundtrip_time, $resp_time) = @{$response_packet};

  # The response address is defined if this is a response.
  # Otherwise, an undefined response address indicates that the
  # timeout period has ended.
  if (defined $resp_address) {
	printf( "ping to %-15.15s at %10d. pong from %-15.15s in %6.3f s\n",
			$req_address, $req_time,
			$resp_address, $roundtrip_time
		  );
	`aplay $acksound`;
	$fail = 0;
  }
  else {
	printf( "ping to %-15.15s is done (timeout).\n",
			$req_address
		  );
	$fail++;
	if ( $fail > 4 ) {
	  `aplay $naksound`;
	}
  }

  $kernel->delay_set( 'ping', 1 );
}
