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

# Why does this buffer?!?!?!

sub new {
    my $class = shift;
    my $self = $class->SUPER::new(@_);
    $self->{port} = new Device::SerialPort('/dev/ttyS0') or die "Can't open port: $^E\n";
    $self->{port}->handshake('none');
    $self->{port}->baudrate(2400);
    $self->{port}->databits(8);
    $self->{port}->stopbits(2);
    $self->{port}->parity('none');
    $self->{port}->write_settings() or die "Can't establish connection: $^E\n";
    return $self;
}

sub DESTROY {
    my $self = shift;
    $self->{port}->close();
}

sub transmit {
    my $self = shift;
    print 'transmitting: ';
    foreach (@_) {
        printf('%08b (0x%02x, %03d)  ', $_, $_, $_);
        $self->{port}->write($_);
    }
    $self->{port}->purge_tx() or die "Can't flush port";
    select(undef, undef, undef, 0.15);
    print "\n";
}

sub receive {
    my $self = shift;
    print 'receiving   : ';
    $self->{port}->purge_rx() or die "Can't flush port";
    my $data = $self->{port}->input;
    foreach (split(//, $data)) {
        printf('%08b (0x%02x, %03d)  ', ord($_), ord($_), ord($_));
    }
    print "\n";
    return $data;
}
