#!@PERLPATH@
# Meteorologica - Weather Underground update daemon for u2logger
# Copyright 2001 by David L Norris, KG9AE (dave@webaugur.com)
# $Id: rpt_wu.in,v 1.2 2001/12/14 08:55:43 kg9ae Exp $
#
# based on Weather beacon.
#          Copyright 1999 by Jonathan Bradshaw, N9OXE (n9oxe@arrl.net)
#
# Licensed under the GPL (see LICENSE file for details)
#
# Requirements:
#       Perl 5.004
#       u2logger (to create wx.dat file)
#

use POSIX;
use Socket;
use Sys::Syslog;
use strict;

use LWP::UserAgent;
use HTTP::Request;
use HTTP::Status;

require 5.004;

# Autoconf Values
my $LOGDIR="@prefix@/log";
my $STATEDIR="@prefix@/run";

# ------------------------------ Configurable Options ---------------------------------

# Mandatory Configuration
my $MYWUID = "KMYID4";			# Your Weather Underground ID, assigned by them
my $MYEMAIL = "you\@yourhost.com";	# escape the @ symbol with \@
my $MYWUPWD = "yourpass";		# Your Weather Underground Password

# Optional Configuration
my $wxdelay = 5;			# 5 minutes between each transmission
my $DATAFILE = $LOGDIR."/u2000.dat";

# Expert Configuration
my $myUserAgent = "Meteorologica";
my $wuServer = "http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php";   # Weather Underground's Update/Action URL

# ------------------------------ no user servicable parts below ---------------------------------

# Send (via HTTP) our weather information to Weather Underground
sub xmit {
	# Configure User Agent headers
	my $ua = new LWP::UserAgent;
	$ua->agent( $myUserAgent );
	$ua->from( $MYEMAIL );

	# Our weather data request string
	my ($data) = @_;

	# Form our HTTP request
	my $request = new HTTP::Request( "GET", $wuServer.$data );
	my $response = $ua->simple_request( $request );
	
	# Comment fork() below and uncomment this to test
	#print $wuServer.$data."\n\n";
	#print $response->code() . "\n";
	
	# Was it OK? If not print "<STATUS> FAILURE" to stdout
	# FIXME: This belongs in SysLog
	if( $response->code() != RC_OK ) {
		print $response->code() . " FAILURE\n";
	}
}

sub test_xmit {
	my ($data) = @_;
	print $wuServer.$data."\n\n";
}
sub cvttime {
  # Convert local date/time string into gmtime
  #
  my ($month, $day, $year, $hour, $minute) = @_;
  return mktime(0,$minute,$hour,$day,$month-1,$year-1900,0,0,0);
}

sub wxstring {
	# Read weather data file into hash table and return a Weather Underground HTTP URL
	my ($key, $data, $mydate, $tm, %wx);

	# Check the datafile even exists
	return unless ( -s $DATAFILE );

	# Read weather data into array
	open(WXDATFILE,"<$DATAFILE") || die "Unable to open weather data file!";
	while (<WXDATFILE>) {
		chop;
		($key, $data) = split(/: /);
		$wx{$key}=$data;
	}
	close(WXDATFILE);

	# Username and password
	$data = "?action=updateraw&ID=" . $MYWUID . "&PASSWORD=" . $MYWUPWD;
	
	# Date and time in MySQL (modified IS8601) format
	$data .= "&dateutc="
  		. strftime("%Y-%m-%d+%H:%M:%S", gmtime(cvttime(substr($wx{Date},0,2), substr($wx{Date},3,2), substr($wx{Date},6,4), substr($wx{Time},0,2), substr($wx{Time},3,2))) );

	# Wind Direction 0-360
	$data .= "&winddir=" . $wx{WindDirection};
	
	# Wind Speed MPH (1 min avg)
        $data .= "&windspeedmph=" . $wx{CalcWindAvg1Min};
	
	# Wind Gust MPH
        $data .= "&windgustmph=" . $wx{WindPeakSpeed5Min};
	
	# Humidity Relative %
	if ($wx{OutdoorHumidity} > 0) {
		$data .= "&humidity=" . $wx{OutdoorHumidity};
	} else {
		$data .= "&humidity=";
	}
	
	# Temperature F
        $data .= "&tempf=" . $wx{OutdoorTemp};
	
	# Last Hour's Rainfall
	if ($wx{CalcRainLastHour}) {
		$data .= "&rainin=" . $wx{CalcRainLastHour}; # last 60 mins
	} else {
		$data .= "&rainin=0.00";
	}
	# Barometer Inches/Hg
	$data .= "&baromin=" . $wx{Barometer};
	
	# Dewpoint F
	$data .= "&dewptf=" . $wx{DewPoint};
	
	# METAR Data
	$data .= "&weather=";
	
	# Cloud Cover
	$data .= "&clouds=";
	
	# Weather Software Version
	$data .= "&softwaretype=" . $myUserAgent;
  return $data;
}

#
# Main
#
fork && exit;
setsid();
Sys::Syslog::setlogsock('unix');
openlog('wunderground', 'pid', 'daemon');
syslog('notice', 'wunderground starting');

my ($wx, $lastwx);
while (1) {
  $wx = &wxstring();
  if ($wx) {
    syslog('debug', 'Sending: %s', $wx);
    &xmit($wx) unless ($wx eq $lastwx);
    $lastwx = $wx;
  }
  sleep($wxdelay * 60);
}
syslog('notice', 'wunderground exiting');
closelog();

# End of wunderground.pl
