#!/usr/bin/perl

require IO::Socket;
require IO::Select;
require Device::SerialPort;

$serial_port = shift || "/dev/ttyS0";
$port = shift || 6556;

$serial = Device::SerialPort->new($serial_port);

die "Couldn't open $serial_port" if(!$serial);

$serial->baudrate(600);
$serial->parity("none");
$serial->databits(7);
$serial->stopbits(1);
$serial->handshake("none");
$serial->rts_active(0);
$serial->dtr_active(1);
$serial->read_const_time(1);
$serial->read_char_time(1);
$serial->write_settings;

$timeout = 0;


$main_socket = IO::Socket::INET->new( LocalPort => $port,
				      Listen => 5,
				      Reuse => 1,
				      Proto => 'tcp');

die "Couldn't open port $port (already running?)" if (!$main_socket);

$select = new IO::Select($main_socket);
$current_len = 0;


if(fork()) {
	# parent
	$SIG{'CHLD'} = IGNORE;
	exit(0);
} else {
	$SIG{'PIPE'} = IGNORE;
	$SIG{'CHILD'} = IGNORE;
	$serial->write("D"); # prime the pump
	$alive = 1;

	while($alive) {

	@readable = $select->can_read(0.01);

	foreach $sock (@readable) {
		if($sock eq $main_socket) {
			$sock = $main_socket->accept();
			print $sock "VOLTS>";
			$select->add($sock);
		} else {
			$sock->recv($in,255,0);

			if(! defined $in) {
				$select->remove($sock);
				$sock->close();
			} else {
				print $sock "$current_data\nVOLTS>";
				# some command set we have ;-)
			}
		}
	}

	$timeout++;

	($len,$data) = $serial->read(15);
	$page_data .= $data;
	$current_len += $len;

	if($page_data =~ /\r/) {
		$current_data = $page_data;
		$page_data = "";
	}

	if(($timeout > 20)) {
		$current_len = 0;
		$serial->write("D");
		$timeout = 0;
	}
	}
}	
