#!/usr/bin/perl

# UDP.PL
#
# Enable/Disable IO ports on the siteplayer through UDP packets.
# Note, the site player must be configured to allow UDP packets. (hint: ff20 -> 1)
#
# Use the Socket module, which allows us to create UDP packets
use Socket;
use Getopt::Std;

# Set the siteplayer address and UDP port
$HOSTNAME = "192.168.10.150";
$PORT = 26482;

# Command line options are as follows:
# 	-h hostname    	sets hostname (default is hard coded.)
# 	-d             	turn on debug statements
# 	-i #		set I/O port number (#) on site player
#	-s 0|1		set state, either 0 or 1
getopts("ds:i:h:");

if ($opt_h) { $HOSTNAME = $opt_h; } 
if ($opt_i =~ /[0-7]/) { $IO = $opt_i; } 
	else { 
		print"IO (-i) = $opt_i. Must be between 0 and 7.\n";
		help(); }
if ($opt_s =~ /[01]/) { $STATE = $opt_s; } 
	else { 	
		print "-s = $opt_s. Must be 0 or 1.\n";
		help(); }
# Debug on
if($opt_d) { 
	print "Hostname: $HOSTNAME\n"; 
	print "I/O: $IO\n";
	print "State: $STATE\n";
	}

# Calculate port address and state (0 or 1)
#
# UDP packet format:
#   # of data bytes
#   1's complement of # of data bytes
#   LSB of IO port address
#   MSB of IO port address
#   Data
#   00
#   00
#   Ex: 01 FE 14 FF 01 00 00 -> sets IO3 to 01 (off)
#
#   Port Addresses Range: FF11 through FF18 -> IO 0-7
#
$o = 0x00 + $STATE;
$a = 0x11 + $IO;

# Convert to a binary string
$MSG = pack("C7",0x01,0xFE,$a,0xFF,$o,0x00,0x00);

# Send message to SitePlayer
socket(SOCKET, PF_INET, SOCK_DGRAM, getprotobyname("udp"))
   or die "Socket: $!";
$ipaddr = inet_aton($HOSTNAME);
$portaddr = sockaddr_in($PORT, $ipaddr);
send (SOCKET, $MSG, 0, $portaddr) == length($MSG)
   or die "Can't send to $HOSTNAME($PORT): $!";

# That's it - one UDP packet to the site player

# Print the help lines
sub help {
	print "\nudp.pl sends a UDP string to the Site Player.\n\n";
	print "  -h hostname or IP address (default is hard coded.)\n";
	print "  -i [0-7] -> IO port number\n";
	print "  -s [0-1] -> turn IO on or off\n";
	print "  -d -> enable debug\n\n";
	print "e.g. ./udp.pl -d -s 1 -h 192.168.10.150 -i 7\n";
	die "Try again.\n";
}
