#!/usr/bin/env perl

## This file Copyright 2000 <contact@gbppr.org> under the GPL
## NO WARRANTY. Please send bug reports / patches / reports.

use POSIX;

if ($ARGV[0] eq "") {
   print STDERR "\nUsage: $0 [1|2]\n\n\tWhere 1 or 2 is the communications port to use.\n\n";
   exit 1;
}

$port = $ARGV[0] - 1;

sub PortSetup {
  my ($fd) = @_;
  
  $termios = POSIX::Termios->new;
  $termios->getattr($fd);
  $termios->setispeed( &POSIX::B9600 );
  $termios->setospeed( &POSIX::B9600 );
  $termios->setcflag( ($termios->getcflag & ~(&POSIX::CSIZE)) | CS8 );
  $termios->setcflag( $termios->getcflag | &POSIX::CLOCAL | &POSIX::CREAD);
  $termios->setiflag( &POSIX::IGNBRK );
  $termios->setlflag( 0 );
  $termios->setoflag( 0 );
  $termios->setcc( 1, &POSIX::VMIN );
  $termios->setcc( 5, &POSIX::VTIME );
  $termios->setiflag( $termios->getiflag & ~(&POSIX::IXON|&POSIX::IXOFF) );
  $termios->setcflag( $termios->getcflag & ~(&POSIX::PARENB|&POSIX::PARODD) );
  $termios->setattr( $fd, &POSIX::TCSANOW );
  return;
}

sub inFlush {
  my ($fd) = @_;
  POSIX::tcflush($fd, POSIX::TCIFLUSH);
  return;
}

sub outFlush {
  my ($fd) = @_;
  POSIX::tcflush($fd, POSIX::TCOFLUSH);
  return;
}

# open the port
$fd = POSIX::open ("/dev/ttyS$port", 2) || die "Could not open communications port\n";

# setup the port
PortSetup($fd);
$| = 1;
inFlush($fd);

# data to send
$buffer = sprintf "Testing and stuff....\r\n";

# write to port
POSIX::write ($fd, $buffer, (length $buffer));
outFlush($fd);

print "Sending data to port /dev/ttyS$port\n";

#POSIX::read ($fd, $data2, 128);
#print "$data2\n";

# close the port
POSIX::close ($fd);
