#!/usr/bin/perl 


use Device::SerialPort;
use LWP::Simple;
# 
$serialDev='/dev/ttyUSB0';
$logFile='/tmp/logFile.csv';
$interval=5;
$urlPocasi="http://meteo.vsb.cz/pocasi/data.htm";
$debug=0;


## pokud je zadan nejaky parametr pouzije se jako nazev souboru pro zapis logu

if (!$ARGV[0]) {
	print "usage: $0 logFile.csv\n";
	exit;
}else{
	$logFile = $ARGV[0];
}



# hlavicka modem
$header="Date;Time;BSIC0;LAC0;CellId0;ARFCN0;Power0;BSIC1;LAC1;CellId1;ARFCN1;Power1;BSIC2;LAC2;CellId2;ARFCN2;Power2;BSIC3;LAC3;CellId3;ARFCN3;Power3;BSIC4;LAC4;CellId4;ARFCN4;Power4;BSIC5;LAC5;CellId5;ARFCN5;Power5;BSIC6;LAC6;CellId6;ARFCN6;Power6";
# hlavicka pocasi
$header.=";temperature;humidity;dewpoint;windDir;windSpeed;barometer;falling;windChill;thwIndex;heatIndex;rain;sunrise;sunset\n";

sub sread();
sub swrite($);
sub parseMoni($);
sub parsePocasi($);
sub getTime();
sub finish();
use sigtrap 'handler' => \&finish, 'INT', 'ABRT', 'QUIT', 'TERM';

## INICIALIZACE PORTU ###
 print "init: start\n" if($debug>0);
  $port = new Device::SerialPort ($serialDev, '0') || die "Can't start $serialDev $!\n"; 

  $port->user_msg(ON);
  $port->databits(8);
  $port->baudrate(115200);
  $port->parity("none");
  $port->stopbits(1);
  $port->handshake("none");

  $port->write_settings || print "ne-e\n" && undef $port;

  $port->read_char_time(0);     # don't wait for each character
  $port->read_const_time(1000); # 1 second per unfulfilled "read" call

#my $baud = $port->baudrate;
#my $parity = $port->parity;
#my $data = $port->databits;
#my $stop = $port->stopbits;
#my $hshake = $port->handshake;
#
#print "B = $baud, D = $data, S = $stop, P = $parity, 
#            H = $hshake\n";

############### MAIN loop ##################


 print "init: done\n" if($debug >0);

# logon to tmobile
 swrite('at+cops=1,1,"TMO",0');
 sread(); 
 swrite('at#moni=7');
 sread();


#### open log file #####
 open(LOG, ">>$logFile") || die "ERROR: nelze otevrit soubor $logFile $!\n";
 select(LOG); $|++;
 print LOG $header;


#### loop 	####
while(1){
	my $output = getTime();
	swrite('at#moni');
 	$output.=parseMoni(sread());
 	$output.=parsePocasi($urlPocasi);
	print LOG "$output\n";
	sleep $interval;
}

finish();


#######################################################
#####     functions				#######
#######################################################

sub finish(){

 close LOG;
 swrite('atz');
 sread();
 exit;

}

sub getTime(){
	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
	return( sprintf("%2d.%02d.%04d;%02d:%02d:%02d", $mday,$mon+1,$year+1900,$hour,$min,$sec) );
}

sub parseMoni($){
  my @lines = split("\n",$_[0]);
  my $line;
  my $outline='';
  foreach $line (@lines){
	
	$bsic='';
	$lac='';
	$cellId='';
	$arfcn='';
	$power='';

	# #MONI: Cell  BSIC  LAC  CellId  ARFCN    Power  C1  C2  TA  RxQual  PLMN
	# #MONI:  S    14  7032   76B3      32    -87dbm  18  18   2     0    T-Mobile CZ
	# #MONI: N1    74  7032   75F4      57    -92dbm  14  14
	# #MONI: N6    FF  FFFF   0000       0   -111dbm  -1  -1

	#Log (nejlepe CSV) by mel vypadat nasledovne:
	#datum;cas;BSIC1;LAC1;CellId1;ARFCN1;Power1;......;BSIC6;LAC6;CellId6;ARFCN6;Power6
	#								cell		bsic	  lac	      cellid    ardcn 	   power
	if( ($bsic, $lac, $cellId, $arfcn, $power) = $line =~ /#MONI:\s+[NS0-9]+\s+([a-f\d]+)\s+([a-f\d]+)\s+([a-f\d]+)\s+(\d+)\s+(-?[\d]+)dbm /i ){
		$outline.=";$bsic;$lac;$cellId;$arfcn;$power";
	}
  }
  return $outline;
}

sub parsePocasi($){
	my ($url)=@_;
	my $html = get($url);
	print "ERROR: Couldn't get url: $url" unless defined $html;
#Current Conditions at VSB-TU Ostrava (49°50'N, 18°09'E, 300 m) as of 11.04.11 18:00:     Temperature 13.8°C
#Humidity 61%      Dewpoint 6.4°C
#Wind SW at 1.3 m/s
#Barometer 1016.6 hPa & Falling Rapidly     Wind Chill 13.8°C
#THW Index 13.1°C
#Heat Index 13.1°C
#Today's Rain 0.0 mm     Storm Total 0.0 mm
#Monthly Total 12.0 mm     Yearly Total 65.2 mm     Current Rain Rate 0.0 mm/hr          Sunrise:      6:04     Sunset:     19:34

# pozadovany vystup
	my ($date, $time, $temperature, $humidity, $dewpoint, $windDir, $windSpeed, $barometer, $falling, $windChill, $thwIndex, $heatIndex, $rain, $sunrise, $sunset) = '';

	if($html =~ m/as\s+of\s+([\d\.]+)\s+([\d\:]+):/i){
		$date=$1;
		$time=$1;
	}
	if($html =~ m/Temperature\s+([\d\.]+)/i){
		$temperature=$1;
	}
	if($html =~ m/humidity\s+([\d\.]+)%/i){
		$humidity=$1;
	}
	if($html =~ m/dewpoint\s+([\d\.]+)/i){
		$dewpoint=$1;
	}
	if($html =~ m/wind\s+(\w+)\s+at\s+([\d\.]+)/i){
		$windDir=$1;
		$windSpeed=$2;
	}
	if($html =~ m/Barometer\s+([\d\.]+)/i){
		$barometer=$1;
	}
	if($html =~ m/\&\s+(\w+\s\w*)\s+wind/i){
		$falling=$1;
	}
	if($html =~ m/wind chill\s+([\d\.]+)/i){
		$windChill=$1;
	}
	if($html =~ m/thw\sindex\s+([\d\.]+)/i){
		$thwIndex=$1;
	}
	if($html =~ m/heat\sIndex\s+([\d\.]+)/i){
		$heatIndex=$1;
	}
#Today's Rain 0.0 mm     Storm Total 0.0 mm
#Monthly Total 12.0 mm     Yearly Total 65.2 mm     Current Rain Rate 0.0 mm/hr          Sunrise:      6:04     Sunset:     19:34

	if($html =~ m/Current\sRain\sRate\s+([\d\.]+) mm\/hr/){
		$rain=$1;
	}
	if($html =~ m/sunrise:\s+([\d\:]+)/i){
		$sunrise=$1;
	}
	if($html =~ m/sunset:\s+([\d\:]+)/i){
		$sunset=$1;
	}
# vynechame date time z pocasi
#	return ";$date;$time;$temperature;$humidity;$dewpoint;$windDir;$windSpeed;$barometer;$falling;$windChill;$thwIndex;$heatIndex;$rain;$sunrise;$sunset"
	return ";$temperature;$humidity;$dewpoint;$windDir;$windSpeed;$barometer;$falling;$windChill;$thwIndex;$heatIndex;$rain;$sunrise;$sunset"


}

sub swrite($){
  my ($out)=@_;
  $out.="\r";
  my $count_out = $port->write($out);
  print "ERROR: write failed: $out\n"   unless ($count_out);
  print "ERROR: write incomplete: $out\n"     if ( $count_out != length($out) );
  print "$count_out bytes write\n" if ($debug > 1);
}


sub sread(){
 my $chars=0;
 my $timeout=5;
 my $buffer="";
 while ($timeout>0) {
        my ($count,$saw)=$port->read(255); # will read _up to_ 255 chars
        if ($count > 0) {
                $chars+=$count;
                $buffer.=$saw;
 
                # Check here to see if what we want is in the $buffer
                # say "last" if we find it
		if($buffer =~ /(OK|ERROR)\r$/){ 
			last;
		}
        }
        else {
                $timeout--;
        }
 }
 if ($timeout==0) {
	print "ERROR: read timeout\n";
        return 0;
 }
 if($buffer =~ m/ERROR/i){
	print "ERROR: modem vratil eroor:\n$buffer\n";
 }
 return $buffer;
}


######################
1;
