#!/bin/bash 

#This script extracts data from /var/tmp/wxdatacopy.xml and sends it to a Weather Underground PWS account.
#wxdata.xml is created every 30 seconds by the WOSPI python program running in a screen environment.
#To prevent conflict, this script makes a copy of the XML file then deletes the original. The script then detects
#the existance of a new xml file before running again.
#The script needs to be run as root (sudo)

#The script is called by cron every minute
#Weather Underground is updated ever 5 minutes unless either of two factors occur:
#1. The rain rate is equal or greater than .5 inches.
#2. The wind speed is equal or greater than 10 mph.
#When either is true, WU is update every minute 
#When both fall below these values, the sending to WU will return a 5 minute interval
#after a send to show the new below-minimum values (2/23/2020)

#CURL has been replaced with the utility, HTTP, after CURL started returning errors from Weather Underground.
# New test for variables windspeednum and raininnum to prevent syntax error if empty. Depreciated as it doesn't work
#file variables
#5/7/2020 - remove assigning WU varibles prior to calling xml2wu function. This now occurs inside the function. 
#Changed cp and rm lines to mv
#Changed dateutc variable creation method

#Added logic to test for a log file and fill variables if it doesn't exist (only needed when script is new)


xml="/var/tmp/wxdata.xml"
xmlc="/var/tmp/wxdatacopy.xml"
wulog="/var/tmp/sendwu2.log"
pwlog="/var/tmp/sendpw.log"


#copy wxdata.xml then remove it
#The xml file will contain 101 lines unless console is reset. Barometric trend not valid line added in first three hours
#The file is 102 lines until then. 
if [ -s $xml ] &&  [ $(wc -l < $xml) -ge 100 ]
then


mv $xml $xmlc
##tgt="/mnt/readyshare/WOSPIimage/xml"
##cp $xmlc $tgt${xmlc:8:12}$(date +%m%d%y-%H%M%S)
## updated 2-15-22 to remove the <ver> field altogether. The next field <nver> will also be deleted. (Still working on this.)

sed  -i  '/<ver>/,/</d' $xmlc
##sed -i '/<ver>/d' $xmlc
else
exit
fi
#Added to ensure xmlcopy file contains the correct number of lines
## if ! [[ $(wc -l < $xmlc)  -ge 99 && $(wc -l <$xmlc) -le 101 ]]; then exit; fi

##2-15-22 This if statement shouldn't be needed now that all <ver> tag data is removed.
if [ "$(file -b $xmlc)" == "data" ]
then
	tgt="/mnt/readyshare/WOSPIimage/xml"
	cp $xmlc $tgt${xmlc:8:12}$(date +%m%d%y-%H%M%S)
	exit
fi

#get the time of the last transmission to WU
#2-21-20 get the current frequency to send
now=$(date +%s)
if [ -s $wulog ]
then
past=$(head -1 $wulog)
freq=$(tail -1 $wulog)
if ! [ "$freq" = "0" ] || [ "$freq" = "1" ]; then freq=1; fi

else
past=$(( $now - 60 ))
freq=0
fi

send=0
ID="KFLLUTZ41"
PASSWORD="odlihmcl"
# 1-1-22
PWSPW="ayjEZDGiP9"
#url to WU
urlhead="http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?action=updateraw&ID=$ID&PASSWORD=$PASSWORD"
pwshead="https://pwsupdate.pwsweather.com/api/v1/submitwx?&ID=$ID&PASSWORD=$PWSPW"
#WU fields/xml fields
 



#Assign xml file tags to variables   
#wind direction
winddirxml="<winddir>"
#wind speed
windspeedxml="<wind_mph>"
#wind speed 2 minute average
windspeedmph2mxml="<avgwind2_mph>"
#wind gust last ten minutes
windgust10mxml="<gust10_mph>"
#wind gust direction last ten minutes
windgustdirxml="<gust10dir>"
#wind gust now
windgustmxml="<gust10_mph>"
windgustdirxml="<gust10dir>"
# humidity and temp
humidityxml="<outhum_p>"
dewpointxml="<dewpoint_f>"
tempfxml="<outtemp_f>"
#rainin is the rain rate
raininxml="<rainrate_mmhr>"
#dailyrainin is the rain amount since local midnight
dailyraininxml="<dayrain_mm>"
barominxml="<barometer_inhg>"
softwarexml="<programversion>"



function xml2wu () {
# A third passed variable assumes mm to inch conversion
local ret=$1
local result=$(grep -F "$2" $xmlc|sed -e 's,.*>\([^<]*\)</.*,\1,g')
if [  -n "$3" ] 
then
		local result=$(echo "($result*.039370078)"|bc)
		local result=$(printf "%0.2f\n" $result)
fi
local result="$1=$result"
eval $ret="'$result'"
}

#put the utc date in now from network time

dateutc="dateutc="$(date -u +"%F+%T")
#fill the WU fields from XML
#function  $1=label (exit as variable) $2=var-containing-wxdataxml tag  $3=if-mm-to-inch-conversion
# Example windir <windir> (variable content)
# Example rainin <rainin> (variable content) y (any value) 

xml2wu winddir $winddirxml
xml2wu windspeedmph $windspeedxml
xml2wu humidity $humidityxml
xml2wu dewptf $dewpointxml
xml2wu windgustmph $windgustmxml
xml2wu windgustdir $windgustdirxml
xml2wu windgustmph_10m $windgustmxml
xml2wu windspdmph_avg2m $windspeedmph2mxml
xml2wu tempf $tempfxml
xml2wu windgustdir_10m $windgustdirxml 
xml2wu rainin $raininxml y
xml2wu dailyrainin $dailyraininxml y
xml2wu baromin $barominxml
xml2wu softwaretype $softwarexml

#softwaretype=$(echo "$softwaretype"| sed "s/"="/&"Wospi\ "/g")
softwaretype=$(echo "$softwaretype"| sed "s:"=":&"Wospi-":g")
#echo $winddir
#echo $windspeedmph
#echo $windgustmph
#echo $windgustdir
#echo $humidity
#echo $dewptf
#echo $windgustmph_10m
#echo $windspdmph_avg2m
#echo $tempf
#echo $windgustdir_10m
#echo $rainin
#echo $dailyrainin
#echo $baromin
#echo $softwaretype

#format two variables that will be mimimums for sending WU at one minute internals instead of 5 minute intervals.
windspeednum=$(echo $windspeedmph |cut -f 2 -d '=' )
raininnum=$(echo $rainin |cut -f 2 -d '=' )
#test these varibles for content. if either are empty than exit
# This doesn't seem to be a very good test of data integrity, it needs work
#if [ -z $windspeednum ] || [ -z $rainin ]
#then
#	ls -la /var/tmp/wxdata*.xml >> /var/tmp/trapit.log
#	baddate=$(date  +"%m%d%y-%H%M%S")
#	cp wxdatacopy.xml /var/tmp/baddata/baddata$baddate.xml
# exit 3
#fi



#echo $now
#echo $past 
#Send to WU if five or more minutes have elapsed since the last update or
# if the rainrate is greater than .1 inches or
# if the wind speed is equal or  greater than 5 mph changed from 10mph 2/24/2020

#BC returns 1 if comparison is equal or 0 if not



if [ $(echo "$raininnum >= .1"|bc) -eq 1 ] || [ $(echo "$windspeednum >= 5"|bc) -eq 1 ]
then
freq=1
send=1
#echo $freq $send >> /var/tmp/tempwind.log 

elif [ $freq = 1 ]
then
# script started with freq = 1 from last pass
#uncoment below to return to 5minute/1minute
#freq=0
send=1

elif [ $(echo "$now - $past"|bc) -ge 290 ]
then
send=1
else
#no sending conditions were met so exit script with $past intact from last send

#echo $send

#echo $?routine >>/var/tmp/baddata/routinecode.txt
exit 0
fi

#echo $(echo "$now - $past"|bc)
#echo $send
#echo $freq
#Set send to 1 to continually upday WU 5/19/22 - test to see why WU shows time delay
#send=1
if [ $send = 1 ]
then
  echo $now > $wulog
	echo $dateutc >> $wulog
	wxdatafield="&$dateutc&$winddir&$windspeedmph&$windspdmph_avg2m&$windgustmph_10m&$windgustdir_10m&$windgustmph&$windgustdir&$humidity&$dewptf&$tempf&$rainin&$dailyrainin&$baromin&$softwaretype"

	
WUout="$urlhead&$wxdatafield"
PWout="$pwshead&$wxdatafield&action=updateraw"

##  curl -s quit working  use http -b
## 8-4-21 update curl has been reinstated as it is much faster than http. The issue with curl is that WUNDERGROUND tigntened the HTTP
##  tolerances and send BAD REQUEST when the string contained spaces. Prior to May 2018 the utc date and softwaretype fields had 
## acceptable spaces. Strangely, both the utility, "HTTP" and any browser URL address line passed these strings with success.
## Both fields have been modified to allow use of curl.

        curl -s "$WUout" >> $wulog
	curl -s "$PWout" > $pwlog

## 2-21-20 try three times then exit. Changed WHILE loop to FOR loop

##	for (( cnt=1; cnt<=3; cnt++ ))

##	do
	#echo "sending" "$err"
##  curl -s quit working  use http -b
##        curl -s "$WUout" >> $wulog
##	http -b --timeout 5 "$WUout" >> $wulog
##		err=$?
##echo $err
##		if [ $err  -gt 0 ]
##			then
##			echo count $cnt $(date +%m%d%y-%H%M%S) >> /var/tmp/code.txt
##			 sleep 5
##		else
##				break
##		fi

##	done

#Store freq result


	echo $freq >> $wulog

	echo "$WUout" > /var/tmp/scriptout.txt
	echo "$PWout" > /var/tmp/pwscriptout.txt

#delete the semiphore file if it exists
#The semiphore file is created by wospifail.sh if more than five minutes have passed since update.
	if [ -a /var/tmp/semiphore.txt ];then rm /var/tmp/semiphore.txt; fi
fi




exit

