#!/usr/bin/perl

# edit these as appropriate.

my $SLEEP_TIME = 5;   # seconds
my $MOTHERSHIP='https://localhost/tracker.php';

# shouldn't have to edit these.

my %devices;
my $SENSOR_MAC="unknown";
my $VERBOSE=1;
my $OUT_FILE='scan.txt';

my $CURL='curl';
my $HCITOOL='hcitool';


# arguments:

$argc = $#ARGV + 1;

if ( $argc != 2 )
{
    print "usage: braces.pl <sleep> <location>\n";
    exit(0);
} 

$SLEEP_TIME = $ARGV[0];
$LOCATION = $ARGV[1];

while(1)
{
    # run hcitool to find discoverable devices.

    if ( $VERBOSE )
    {
        print ">>> scanning for local, discoverable devices...";
    }

    # get local device

    open( HCI_PIPE, "$HCITOOL dev | grep \"..:..:\"|" );

    while ( <HCI_PIPE> )
    {
        chomp;
        @scan = split( ' ', $_, 2 );
        $SENSOR_MAC = $scan[1];
    }

    close( HCI_PIPE );

    # scan for devices.

    open( HCI_PIPE, "$HCITOOL scan | grep \"..:..:\"|" );
    $count = 0;

    while ( <HCI_PIPE> )
    {
        chomp;
        @scan = split( ' ', $_, 2 );
        $mac = $scan[0];
        $name = $scan[1];

        $devices{$mac} = $name;

        if ( $VERBOSE )
        {
	    print "\n   * found device mac=$mac;name=$name";
        }

	$count++;
    }

    close( HCI_PIPE );

    if ( $VERBOSE )
    {
        print "\n\n>>> Inquiry found $count devices, sending to mothership..."; 
    }

    $|=1;
    send_inquiry();
    %devices=();

    if ( $VERBOSE )
    {
        print "(done)\n";
        print "sleeping for a minute...";
    }

    $|=1;
    sleep($SLEEP_TIME);

    if ( $VERBOSE )
    {
        print "(done)\n";    
    }
}

sub send_inquiry
{
    $content = "";

    while ( ( $key, $value ) = each(%devices) ) 
    {
        if ( length($content) > 0 )
        {
            $content = $content . "&"; 
        }

        $content = $content . $key . '='. $value;
    }

    # append our location and our MAC.

    $content = $content . '&location=' . $LOCATION;
    $content = $content . '&sensor=' . $SENSOR_MAC;

    open( OUTPUT, ">$OUT_FILE" ) || print "error opening file!: ($OUT_FILE)\n";
    print OUTPUT $content;
    close( OUTPUT );

    # write content to file, send with curl.

    `$CURL -k -s --data-ascii @./scan.txt $MOTHERSHIP -o response.txt`;

}
