#!/usr/bin/perl

use IO::Socket;

# program to receve data from iphon and turn on/off the sprinkler
# have working with a simple json file adding more interaction with count


# to disable i2c for test mode
$test = 0;

printf "starting\n";

$in_p0 = 0x00; # read for port0
$in_p1 = 0x01; # read for port1

$out_p0 = 0.02; # write output port0
$out_p1 = 0x03; # write output port1

$i2c_address_1 = 0x20;

$config_p0 = 0x06;
$config_p1 = 0x07;

$output = 0x00;

$count = 0;


# --------------------------------------------------
# start setting up the device


$comand = "i2cdetect -y 1";
&sendc();

# set up port 1 for output config
$comand = "i2cset -y 1 ".$i2c_address_1 ." ".$config_p1." ".$output."\n";
&sendc();

# clear outputs turn them all off
$comand = "i2cset -y 1 ".$i2c_address_1." ".$out_p1." 0x00\n";
&sendc();
# read outputs
$comand = "i2cget -y 1 ".$i2c_address_1." ".$out_p1." \n";
&sendc();

# --------------------------------------------------
# listen to for commands
printf "listening\n";

# Flush after every write
$| = 1;


my $server = IO::Socket::INET->new(LocalPort=>55056,Proto=>"udp")
or die "Can't create UDP server: $@";
my ($datagram,$flags);

while ($server->recv($datagram,80,$flags)){
  my $ipaddr = $server->peerhost;
  my $port = $server->peerport;

  printf "extracted $datagram ";
  &parse_data($datagram);;

#--------------------------------------------------------
# attend to the sprinkler
if($count == 0)
{
# clear outputs
$comand = "i2cset -y 1 ".$i2c_address_1." ".$out_p1." 0x00\n";
&sendc();
}# end if

if($count == 1)
{
# set outputs
$comand = "i2cset -y 1 ".$i2c_address_1." ".$out_p1." 0x18\n";
&sendc();
}# end if

}# end while

$server-> close();


# --------------------------------------------------
# subroutines

# writing the registers

sub sendc
{
print $comand;
if ($test != 1)
{
my $temp = `$comand 2>&1`;
printf "$temp\n";
}else
{
printf "TEST MODE no command\n";
}
}# end sub

sub parse_data
{
 my($data) = $_[0];
 #check if this is a read or write command
 if($data =~ /read/)
  {
   &send_data($data,$server);
 }else
 {
   &read_data($data);
 }
} # end sub


sub send_data
 {
  $trans_data = "lamp_on = $count";
  #$trans_data = "lamp_on = %d",$count;
  #$trans_data = "lamp_on = 1";
  printf "sending data $trans_data\n";
  $server->send($trans_data);
 }# end sub send_data

sub read_data
  {
  my $data = $_[0];
 

  if($count == 0){$count = 1}else{$count = 0}

  printf "::reading data $data: count is $count\n";
  }

