#!/usr/bin/perl -w
# NAME: chk4key.pl
# AIM: Find a way to POLL the keyboard
# 05/09/2010 - Added seconds waited, and cycles...
# 14/12/2008 geoff mclane http://geoffair.net/mperl
use strict;
use warnings;
use Term::ReadKey;

#ReadMode('cbreak');
#ReadMode 1;     # cooked mode

sub show_hex {
    my ($i) = shift;
	print sprintf( "%03d ", $i );
	if ($i == 0) {
		print "z ";
	} elsif ($i == 8 ) {
		print "d ";
	} elsif ($i == 9 ) {
		print "9 ";
	} elsif ($i == 7 ) {
		print "b ";
	} elsif ($i == 10 ) {
		print "c ";
	} elsif ($i == 13 ) {
		print "l ";
	} else {
		print sprintf( "%c ", $i );
	}
	print sprintf( "%02X ", $i );
    print sprintf( "%03o\n", $i );
}

sub got_keyboard {
    my ($rc) = shift;
    if (defined (my $char = ReadKey(-1)) ) {
		# input was waiting and it was $char
        $$rc = $char;
        return 1;
	}
    return 0;
}

sub delay {
    my ($secs) = shift;
    select(undef, undef, undef, $secs);
}

print "Show keyboard, until ESC to exit ...\n";
my $add_delay = 0;
my $begin_time = time();
my $wait_secs = $begin_time;
my $cycles = 0;

my ($i, $char, $ch, $len, $j, $dif1, $dif2);
for ($i = 0; ; $i++) {
    $cycles++;
    if (got_keyboard(\$char)) {
        my $time_now = time();
        $dif1 = $time_now - $begin_time;
        $dif2 = $time_now - $wait_secs;
        print "Elapsed $dif1: Waited $dif2 seconds for key... $cycles cycles... Got ";
        $len = length($char);
        for ($j = 0; $j < $len; $j++) {
            $ch = substr($char,$j,1);
            show_hex( ord($ch) );
        }
        if ($char eq "\033") {
            print "Got ESC char ...\n";
            last;
        }
        $wait_secs = $time_now;
        $cycles = 0;
    }
    #sleep(1);
    delay(0.1) if ($add_delay);
}

exit(0);

# eof
