#!/usr/bin/perl -w

# Joystick Test Toy
# Waider November 12 2000
# Because I didn't have jstest on my system.

# Open the joystick device
if ( open( JS, "/dev/input/js0" )) {
  # Fine, no worries
} else {
  print STDERR "$!, retrying...";
  sleep 2; # Give drivers a chance to get up and running
  open( JS, "/dev/input/js0" ) || die "js0: $!";
}

print "Joystick opened\n";
my ( $rin, $rout, $rerr );
$rin = '';
vec( $rin, fileno( JS ), 1) = 1;
$rout = $rerr = $rin;

# Have a quick chat with the stick
my $val = pack( "i", 0 );
if ( ioctl( JS, 0x01, $val )) {
  $val = unpack( "i", $val );
  print "Version $val\n";
} else {
  print "Old version\n";
}

$val = pack( "c", 0 );
if ( ioctl( JS, 0x011, $val )) {
  print "$val axes\n";
}

$val = pack( "c", 0 );
if ( ioctl( JS, 0x012, $val )) {
  print "$val buttons\n";
}

my $js_event;
while ( 1 ) {
  $js_event = "";
#  my ( $nfound, $timeleft ) = select( $rout = $rin, undef, $rerr = $rerr,
#									  undef );
#  print "$nfound in the queue\n";
  while ( length( $js_event ) < 64 ) {
	my $nb = sysread( JS, $js_event, 64 - length( $js_event ),
					  length( $js_event ));
	print "read $nb bytes: ";
	die "$!" if $nb == -1;
  }

  my ( $time, $value, $type, $number ) =
	unpack( "LsCC", $js_event );
  print $time;

  # Decode event
  print " BUTTON" if $type & 0x01;
  print " AXIS" if $type & 0x02;
  print " INIT" if $type & 0x80;

  # Decode number
  print " X1" if ( $number == 0 && $type & 0x02 );
  print " Y1" if ( $number == 1 && $type & 0x02 );
  print " X2" if ( $number == 2 && $type & 0x02 );
  print " Y2" if ( $number == 3 && $type & 0x02 );

  print " $number" if $type & 0x01;

  # Decode value
  print " moved to $value" if $type & 0x02;
  print " pressed" if ( $type & 0x01 && $value == 1 );
  print " released" if ( $type & 0x01 && $value == 0 );
  print "\n";
}

close( JS );
