#!/usr/bin/perl -w
###########################################
# Mike Schilli, 2006 (m@perlmeister.com)
###########################################
use strict;
use Audio::DSP;
use Log::Log4perl qw(:easy);
use SoundActivity;
use LWP::Simple;

Log::Log4perl->easy_init({
  file => "/tmp/phonewatch.log",
  level => $INFO,
});

my $IN_USE_POLL =  10;
my $IDLE_POLL   =  60;
my $STATUS_URL  = 
     'http://u:p@_foo.com/phonewatch.cgi';
my $SAMPLE_RATE = 1024;

INFO "Starting up";

while(1) {
  my $state = state();

  if(! defined $state) {
    DEBUG "Fetch failed";
    sleep $IDLE_POLL;
    next;
  }

  DEBUG "web site state: $state";

  if($state eq "idle") {
    DEBUG "Staying idle";
    sleep $IDLE_POLL;
    next;
  }

  INFO "Monitor requested";
  state("busy");
  poll_busy();
  state("idle");
}

###########################################
sub poll_busy{
###########################################

  my $dsp = new Audio::DSP(
    buffer   => 1024,
    channels => 1,
    format   => 8,
    rate     => $SAMPLE_RATE,
  );

  $dsp->init() or die $dsp->errstr();

  my $act = SoundActivity->new();

  while(1) {
    DEBUG "Reading DSP";
    $dsp->read() or die $dsp->errstr();

    $act->sample_add( $dsp->data() );
    $dsp->clear();

    if(! $act->is_active()) {
        INFO "Hangup detected";
        $dsp->close();
        return 1;
    }
    sleep $IN_USE_POLL;
  }
}

###########################################
sub state {
###########################################
  my($value) = @_;

  my $url = $STATUS_URL;
  $url .= "?state=$value" if $value;
  DEBUG "Fetching $url";
  my $content = get $url;
  if($content =~ m#<b>(.*?)</b>#) {
      return $1;
  }
}
