#!/usr/bin/perl

# Control a Sony TV from MythTV by Paul R. Kucher
# This script is free software and is licensed under the GNU GPL.
#
# This script was modified from rca_control.pl:  Remote control of a
# DirecTV unit via the serial port by Josh Wilmes (http://www.hitchhiker.org/dss)

$|=1;
use POSIX qw(:termios_h);
use FileHandle;

# Verbose output
$verbose=1;

# Serial port settings.
$baudrate = "9600";
$serport = "/dev/ttyS5";

my $serial=init_serial($serport,$baudrate);

if($ARGV[0] eq "power")
{
	send_command("0x15");
}
elsif($ARGV[0] eq "vol_up")
{
	send_command("0x12");
}
elsif($ARGV[0] eq "vol_dn")
{
	send_command("0x13");
}
elsif($ARGV[0] eq "tvvideo")
{
	send_command("0x25");
}
elsif($ARGV[0] eq "mute")
{
	send_command("0x14");
}

sub send_command {
    (@send)=@_;
    foreach (@send) { s/^0x//g; $_=hex($_); }
    print "SEND: " if ($verbose);
    foreach $num (@send) {
	$str=pack('C',$num);
	printf("0x%X [%s] ", $num, $str) if ($verbose);
      syswrite($serial,$str,length($str));
    }
    print "\n" if ($verbose);
}


sub get_reply {
    my $starttime=time();
    my ($last,$ok,@ret);

    print "RECV: " if ($verbose);

    $ret=sysread($serial,$buf,1);
    $str=sprintf("0x%2.2X", ord($buf));

    # busy wait bad!
    die ("Error ($str)\n") if (time() - $starttime > 8);

   print "\n\n" if ($verbose);

   return $str
}


sub init_serial {
    my($port,$baud)=@_;
    my($termios,$cflag,$lflag,$iflag,$oflag);
    my($voice);

    my $serial=new FileHandle("+>$port") || die "Could not open $port: $!\n";

    $termios = POSIX::Termios->new();
    $termios->getattr($serial->fileno()) || die "getattr: $!\n";
    $cflag= 0 | CS8 | HUPCL | CREAD | CLOCAL;
    $lflag= 0;
    $iflag= 0 | IGNBRK | IGNPAR | IXON | IXOFF;
    $oflag= 0;

    $termios->setcflag($cflag);
    $termios->setlflag($lflag);
    $termios->setiflag($iflag);
    $termios->setoflag($oflag);
    $termios->setattr($serial->fileno(),TCSANOW) || die "setattr: $!\n";
    eval qq[
      \$termios->setospeed(POSIX::B$baud) || die "setospeed: \$!\n";
      \$termios->setispeed(POSIX::B$baud) || die "setispeed: \$!\n";
    ];

    die $@ if $@;

    $termios->setattr($serial->fileno(),TCSANOW) || die "setattr: $!\n";

    # This gets rid of all the special characters..
    $termios->getattr($serial->fileno()) || die "getattr: $!\n";	
    for (0..NCCS) {	
	if ($_ == NCCS) { last; }

	# Dont mess up XON/XOFF..
	if ($_ == VSTART || $_ == VSTOP) { next; }

	$termios->setcc($_,0);	
    }
    $termios->setattr($serial->fileno(),TCSANOW) || die "setattr: $!\n";

    return $serial;
}