#========================================================================= 
#          Copyright © 2001-2004 QUALCOMM Incorporated.
#                     All Rights Reserved.
#========================================================================= 
#! /usr/local/bin/perl -w

use lib "$ENV{BREWTOOLSDIR}\\BREW Perl Interface";
use BREWPerlIF;

###############################################################
# This example illustrates how to use perl scripts to start   #
# logging to a file as well as a server too. This might be    #
# useful in cases where a person might decide to run a client #
# on some other machine and process the messages....          #
###############################################################


use Socket;
use Carp;
use IO::Handle;


my($remote, $port, $iaddr, $paddr, $proto, $line);

$port = 9999;
$proto = getprotobyname('tcp');
socket(Server, PF_INET, SOCK_STREAM, $proto) or die "socket $!";
setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)) or die "setsockopt: $!";

bind(Server, sockaddr_in($port, INADDR_ANY)) or die "bind: $!";
listen(Server, SOMAXCONN);
print "Server started on port $port\n";

##################
#Start the Client#
##################
$comPort = "COM1";


$dllName = "$ENV{BTILDIR}\\OEMLayer\\QCOMOEM.dll";

printf "Connecting to Device\n";
if(BREWPerlIF::ConnecttoDevice($comPort, $dllName) == 1) {
	printf "Device Connected\n";
	} else {
	die "Could not connect to device\n";
	}
printf "Setting Log Levels\n";
if(BREWPerlIF::SetMessageLevel(4)) { #Fatal Errors only
	printf "Message Level set successfully\n";
	} else {
	die "Could not set log level\n";
	}
if(BREWPerlIF::SetLogMask("0x000000000000000000000007FFF8")) {
	printf "LogMask Set successfully\n";
	} else {
	die "Could not set log mask successfully\n";
	}

$filename = "C:\\BREWLogger".$$;
if(BREWPerlIF::SetOptions($filename, "127.0.0.1", 9999)) {
#if(BREWPerlIF::SetOptions($filename, "1", 9999)) {
#if(BREWPerlIF::SetOptions_fileOnly($filename)) {
	printf "Options set successfully\n";
	} else {
	die "Could not set options \n";
	}

printf "Starting the logging........\n";
if(BREWPerlIF::StartLogger() ) {
	printf "Logging started\n";
	} else {
	die "Could not start logging\n";
	}


	


$SIG{CHLD} = \&REAPER;
for(; $paddr = accept(Client, Server); Close Client) {
 ($port, $iaddr) = sockaddr_in($paddr);
 my ($name) = gethostbyaddr($iaddr, AF_INET);
 print "Connection from $name\n";
 last;
}


while (1)
{
Client->autoflush(1);
$line='';
recv(Client, $line, 1500, 0) || die "Could not Rx $!\n";
print "$line\n"; ### The $line can be used to print to a file/send to a client

}

print "logging ended\n";
