#!/usr/bin/perl

use POSIX;
use Socket;

$address = '10.195.70.218';
$port = 80;
$timeout = 20; # in seconds


# This is a internal routine
#
# usage
#  switchbox_request(uri)
#
# returns
#  undef   - if no connect or timeout expired
#  html    - if OK
#
sub switchbox_request
{
    my $uri = shift;
    my $request;
    my $answer = undef;

    socket( SOCKET, PF_INET, SOCK_STREAM, getprotobyname('tcp') );

    my $inetaddr = inet_aton($address);

    connect( SOCKET, sockaddr_in( $port, $inetaddr ) );

        $request =
            "GET $uri HTTP/1.0\n".
            "\n";

    defined( send( SOCKET, $request, 0 ) );

    my $rout, $rin = '';
    vec( $rin, fileno(SOCKET), 1) = 1;
    $nfound = select( $rout=$rin, undef, undef, $timeout );

    while( vec( $rout, fileno(SOCKET), 1) )
    {
        my $buf;
        last unless recv( SOCKET, $buf, 0x100, 0 );
        last if 0==length($buf);
        $answer .= $buf;
    }
    close( SOCKET );

    $answer = substr($answer,-4);
    $switches = substr($answer,0,1);
    $inreset  = substr($answer,1,1);
    $canwrite = substr($answer,2,1);
    $canread  = substr($answer,3,1);
    return ($switches,$inreset,$canwrite,$canread);
}

 # =======================================================================
#
# This is a sample
#
# =======================================================================
										  
print "  Read    Write    Read\n";

for( $i=0; $i<20; $i++ )
{
#    sleep(1) if $i!=0;

    @ack = switchbox_request('/k0');
        printf "%6x  ", $ack[0];

	if ($i & 1)
	{
	   @ack = switchbox_request('/k11101')
	}  else
	{
	   @ack = switchbox_request('/k10101');
	}

    printf "%6X ", $ack[0];

    @ack = switchbox_request('/k0');
        printf "%6X ", $ack[0];
    print "\n";
}


# reset 
print "\n";
print "Output    Reset     R Rights    W Rights\n";

    @ack = switchbox_request('/k11010');

for( $i=0; $i<20; $i++ )
{
    @ack = switchbox_request('/k0');
        printf "  %2X        %2X        %2X          %2X", $ack[0],$ack[1],$ack[2],$ack[3];
    print "\n";
    sleep (1)   
}
