#!/opt/bin/perl -w

use strict;

use lib '/pub/rrd/lib';
use OwfsSensors;

use lib '/pub/src';
use RokuUI;

my $rokuIP   = "192.168.0.43";
my $rokuPort = 4444;

my $display = RokuUI->new(host => $rokuIP, port => $rokuPort);

for my $int ('INT','QUIT','HUP','TRAP','ABRT','STOP') { 
   $SIG{$int} = 'interrupt';
}   

$display->open || die("Could not connect to Roku Soundbridge Port 4444: $!");

# Get weather for Partille from yahoo. Assume failure(code == 3200)
my $today    = 3200;
my $tomorrow = 3200;
my $tod_desc = "Väder";
my $tom_desc = "Väder";
my $tod_temp = 0;
my $tom_low  = 0;
my $tom_high = 0;

my $weatherdata = `wget -q -O - "http://xml.weather.yahoo.com/forecastrss?p=SWXX0024&u=c"`;
if (not(($weatherdata eq "") or (substr($weatherdata, 0, 4) eq "wget"))) {
  $weatherdata =~ /yweather:condition(.*)text=\"(.*)\"(.*)code=\"(\d*)\"(.*)temp=\"(\d*)\"/;
  $today    = $4;
  $tod_desc = $2;
  $tod_temp = $6;

  $weatherdata =~ /yweather:forecast(.*)low=\"(\d*)\"(.*)high=\"(\d*)\"(.*)text=\"(.*)\"(.*)code=\"(\d*)\"(.*)/;
  $tomorrow = $8;
  $tom_desc = $6;
  $tom_low  = $2;
  $tom_high = $4;
}

# If SB is in standby then display status. Otherwise, do nothing!
if (not $display->ison) {
#  print "Roku is in standby\n";
  my $rokgas  = OwfsSensors::temp("rokgas");
  my $stigare = OwfsSensors::temp("stigare");
  my $inne    = OwfsSensors::temp("inne");
  my $ute     = OwfsSensors::temp("ute");

  $display->clear();

  # Display temp sensors
  $display->cmd("sketch -c color 0");
  $display->cmd("sketch -c font 14");
  $display->cmd("sketch -c text 0 0  \"Inne        $inne     Ute           $ute\"");
  $display->cmd("sketch -c text 0 16 \"Stigare  $stigare     Rökgas  $rokgas\"");

  # Display weather and forecast
  $display->cmd("sketch -c font 1");
  $display->cmd("sketch -c text 160  0  \"$tod_desc\"");
  $display->cmd("sketch -c text 160  8  \"$tod_temp\"");
  $display->cmd("sketch -c text 160 16  \"$tom_desc\"");
  $display->cmd("sketch -c text 160 24  \"$tom_low"."/"."$tom_high\"");

  $display->cmd("exit");
}
$display->close();

sub interrupt {exit(@_)};

END {
  undef $display;
}