package Interface6051::LinuxHack;
use strict;
use Interface6051;
use Device::SerialPort;
our @ISA = ('Interface6051');
1;

sub new {
    my $class = shift;
    my $self = $class->SUPER::new(@_);
    $self->{port} = '/dev/ttyS0';
    open($self->{fh}, '+<', $self->{port}) or die "Can't open port: $!\n";
    system("stty 2400 -echo -crtscts -parenb cs8 cstopb raw < $self->{port}"); # ew, we should do this ourselves
    return $self;
}

sub transmit {
    my $self = shift;
  #print 'transmitting: ';
    foreach (@_) {
  #printf('writing: %08b (0x%02x, %03d)  ', $_, $_, $_);
        # syswrite($self->{fh}, $_); # this ends up buffering! wtf
        system(sprintf('echo -ne \\\\%03o > %s', $_, $self->{port})); # ew, horrible hack
    }
    select(undef, undef, undef, 0.05); # XXX this is the death of us
  #print "\n";
}

sub receive {
    my $self = shift;
  #print 'receiving   : ';

    # prepare fields
    my $fh = '';
    vec($fh, fileno($self->{fh}), 1) = 1;

    # read one character at a time until no more data is forthcoming
    my $data = '';
    my $ready;
    while (select($ready = $fh, undef, undef, 0.15) and vec($fh, fileno($self->{fh}), 1)) {
        # select can return true for filehandles that aren't in the
        # list, so that's why we check the right filehandle is there
        # in the returned $ready variable.
	sysread($self->{fh}, $data, 1, length($data));
    }

  #foreach (split(//, $data)) {
  #    printf('%08b ', ord($_));
  #}
  #print "\n";
    return $data;
}
