#!/usr/bin/perl -w
# vim: set sw=4 ts=4 et: 
# lcddate.pl - display time and day on an external LCD display
# Copyright GPL  2005, Guido Socher
use IO::Socket;
use Fcntl;
use strict;
use Net::Address::IP::Local;
use Unix::Uptime;
#
print "script started"; #debug info
sleep 2; #wait for lcdproc server to start
my $remote = IO::Socket::INET->new(
    Proto     => "tcp",
    PeerAddr  => "localhost",
    PeerPort  => 13666)|| die "Cannot connect to LCDd\n";
$remote->autoflush(1);
sleep 1; # give the server time to notice us...
print "connected"; #debug info

print $remote "hello\n";
# we must read the response even if we ignore it:
my $lcdresponse = <$remote>;

# Turn off blocking mode...
fcntl($remote, F_SETFL, O_NONBLOCK);
# Set up some screen widgets...
print $remote "client_set name lcdtime\n";
print $remote "screen_add scr1\n"; #new screen with name scr1
print $remote "widget_add scr1 str1 string\n"; #new widget for scr1 with name str1 and type string (simple text)
print $remote "widget_add scr1 str2 string\n"; #new widget for second line
#
my $date;
my @ltime;
my $address;
my $uptime;
while(1)
{
    $lcdresponse = <$remote>;
    #$date = scalar localtime; # this is 24 char long. The following is bettter:
    @ltime = localtime;
    #return a date in yyyy-mm-dd hh:mm format
    $date = sprintf("%04d-%02d-%02d %02d:%02d",
          1900+$ltime[5],$ltime[4]+1,$ltime[3],$ltime[2],$ltime[1]);

    $address = eval {Net::Address::IP::Local->public}; 
    $uptime = Unix::Uptime->uptime(); #get system uptime in seconds
    my $uptime_m = int(($uptime/60)%60);
    my $uptime_h = int(($uptime/60/60)%24);
    my $uptime_d = int($uptime/60/60/24);

    #widget_set screenName widgetName x y \"text\"\n
    #print $remote "widget_set scr1 str1 1 1 \"$date\"\n"; #print date and time 
    #print $remote "widget_set scr1 str2 1 2 \"Penis\"\n"; #print text in second line

    print $remote "widget_set scr1 str1 1 1 \"$address\"\n";
    print $remote "widget_set scr1 str2 1 2 \"${uptime_d}d ${uptime_h}h:${uptime_m}m\"\n";
    sleep 10;
}
