#!/usr/bin/perl

#term11.pl

# A linux to hc11 dev. board terminal
# Peter Walsh July 2011

$|=1;

use AnyEvent;
use Device::SerialPort;

my $line; my $ch_count; my $ch_string; my $command; my @stdin_fifo; 
my @stdout_fifo; my @task_fifo;

my $sp = Device::SerialPort->new("/dev/ttyS0");

$sp->baudrate(9600); $sp->parity("none"); $sp->handshake("none");
$sp->databits(8); $sp->stopbits(1); $sp->read_char_time(0);
$sp->read_const_time(1);

$z_event = AnyEvent->condvar;

$process_stdout_ref = sub {while (@stdout_fifo != 0) {
                              print(shift(@stdout_fifo));
                           }
                      };

$process_stdin_ref = sub  {$command = shift(@stdin_fifo);
                           chop($command);
                           $sp->write($command . "\r");

                     }; 

$a_event = AnyEvent->io (fh => \*STDIN,
                   poll => "r",
                   cb => sub {$line = <>;
                              push(@stdin_fifo, $line);
                              push(@task_fifo, $process_stdin_ref);
                         });


$e_event= AnyEvent->idle(cb => sub {if (@task_fifo !=0) {;
                                 $sr = shift(@task_fifo);
                                 $sr->();
                              }
                         });
               
$f_event = AnyEvent->timer (after => 1,
                   interval => 0.02,
                   cb => sub {($ch_count, $ch_str) = $sp->read(5);
                              if ($ch_count > 0) {
                                 push(@stdout_fifo, $ch_str);
                                 push(@task_fifo, $process_stdout_ref);
                              }
                         });


$z_event->recv;

