#!/usr/bin/perl -W
# V4

use strict;
use Device::SerialPort;
use Time::HiRes qw(sleep);

my $port = "/dev/ttyUSB0";
my $link = Device::SerialPort->new($port) || die("coult not open port: $port - $!"); # <-- match to right com port

$link->databits(8);
$link->baudrate(4800); # <-- match to arduino settings
$link->parity("none");
$link->stopbits(1);
$link->dtr_active(0);
$| = 1; # buffers disabled

my @history = (0,0,0,0,0,0,0,0);

while(1) {
	my $loadavg = `iostat -c 1 2 | tail -n 2 | head -n 1 | gawk '{print \$6}'`;
	##my $loadavg = rand(50);
	
	#scroll data from right to left:
	push @history, round((100-$loadavg)/14); # add latest value at the end 
	shift @history;	# remove first entry (rotate array to the left)
	
	#scroll data from left to right:
	# unshift @history, round((100-$loadavg)/14); # add latest value at the beginning 
	# pop @history;	# remove last entry (rotate array to the right)
	
	# HSV: usually 0-360, just 1 byte per transfer, mapped to 0-255

	my $bottomhue = 160; # blue-ish int(240/1.41)
	my $tophue = 0; # red-ish

	my $tx_column = 0;
	
	foreach my $value (@history) {	
		$link->write(pack("C",1)); # start byte
		sleep(0.01);
		$link->write(pack("C",$ARGV[0] || 4)); # command: huebar
		sleep(0.01);
		$link->write(pack("C",$ARGV[1] || $value)); # draw up to row ? (0..7)
		sleep(0.01);
		$link->write(pack("C",$ARGV[2] || $tx_column)); # which column to update
		sleep(0.01);
		$link->write(pack("C",$ARGV[2] || $bottomhue)); # bottom HUE (0)
		sleep(0.01);
		$link->write(pack("C",$ARGV[3] || $tophue)); # top HUE (7)
		sleep(0.01);
		$link->write(pack("C",1)); # stop byte
		sleep(.02);
		$tx_column++;
	}
}

sub round {
	my $number = shift;
	return int($number + 0.5);
}

