#!/bin/sh

#echo "++BOF++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
# Declare Program Variables
sDBNAME='VellemanK8055'		# Enter the mysql database name
sDBUSER='root'				# Enter the mysql user name
sDBPASS='YOUR-SQL-PASSWORD-GOES-HERE'			# Enter the password of the user above

# BEGIN OF FUNCTIONS ===============================================

fnReturnValueFunction()
{
	#This function is used to get an return value 
	#from functions. BASH functions do not support return values
	ReturnValue=$1
}

fn8BitIntToBinary ()
{ 
	#This function is used to convert an 8 bit input (0-255)
	#and a binary string of length=8 (00010101). Also
	#it is used to set the input port variables
	#(although the velleman K8055 board does not have
	# 8 inputs, it only has 5. Variables are used to 
	# 'complete' the function)
	BitChar1=0  
        BitChar2=0
        BitChar3=0
        BitChar4=0
        BitChar5=0
        BitChar6=0
        BitChar7=0
        BitChar8=0
	InputPort8=0
        InputPort7=0
        InputPort6=0
        InputPort5=0
        InputPort4=0
        InputPort3=0
        InputPort2=0
        InputPort1=0
	

	IntegerToConvert=$1

	#What is an 8bit int ? it is an exact number ranging from 0 to 255
	#You can store this number in 8 bits (=1 byte)
	#bytes Bits are stores like 00101101  (=45)
	#to read a byte (8 bits), you read it from right to left, like bitnumbers -> 87654321
	#To create the binary string for each bit, the value it represents is substracted from
	#the input integer number to define wheter a bit is on or not.
	#like said. the bitstring is read from right to left.
	#so if we want to build the output string we creating left to right (notice diff.!!)
	#by going this way we have to subract the representational value of the bit of the input
	#to define wheter that bit is open or not. (and to see if the port is open or not!
	#so in this script the fun is only beginnen at part 3 where the check is made if the input
	#is greater or equal to 16 (port 5 open or not)


	if [ $IntegerToConvert -ge 128 ]; then
		BitChar1=1
		InputPort8=1
		IntegerToConvert=$((IntegerToConvert-128))
	fi

        if [ $IntegerToConvert -ge 64 ]; then
                BitChar2=1
		InputPort7=1
                IntegerToConvert=$((IntegerToConvert-64))
        fi

        if [ $IntegerToConvert -ge 32 ]; then
                BitChar3=1
		InputPort6=1
                IntegerToConvert=$((IntegerToConvert-32))
        fi

        if [ $IntegerToConvert -ge 16 ]; then
                BitChar4=1
		InputPort5=1
                IntegerToConvert=$((IntegerToConvert-16))
        fi

        if [ $IntegerToConvert -ge 8 ]; then
                BitChar5=1
		InputPort4=1
                IntegerToConvert=$((IntegerToConvert-8))
        fi

        if [ $IntegerToConvert -ge 4 ]; then
                BitChar6=1
		InputPort3=1
                IntegerToConvert=$((IntegerToConvert-4))
        fi

        if [ $IntegerToConvert -ge 2 ]; then
                BitChar7=1
		InputPort2=1
                IntegerToConvert=$((IntegerToConvert-2))
        fi

        if [ $IntegerToConvert -ge 1 ]; then
                BitChar8=1
		InputPort1=1
                IntegerToConvert=$((IntegerToConvert-1))
        fi

	IntegerToConvert=$BitChar1$BitChar2$BitChar3$BitChar4$BitChar5$BitChar6$BitChar7$BitChar8
	fnReturnValueFunction $IntegerToConvert
}

# END OF FUNCTIONS =================================================






#Read Hardware counter settins (2counters on velleman, 2 counters on eMeter from database
dbasequery=`mysql -u$sDBUSER -p$sDBPASS -e'use '$sDBNAME'; SELECT counter1_Velleman, counter2_Velleman, EM_Tarif_1, EM_Tarif_2, (SELECT settingValue
FROM tblEnergyMeterSettings WHERE settingID =1) AS PulsesPerKW, (SELECT TarifEMeter_1 FROM tblEnergyTarifs ORDER BY ValidUntil LIMIT 0 , 1) AS TarifEMeter_1, (SELECT TarifEMeter_2 
FROM tblEnergyTarifs ORDER BY ValidUntil LIMIT 0 , 1) AS TarifEMeter_2, GasCounter, UpdateTimestamp FROM tblHardwareCounter;'`
iDBcounter1_Velleman=`echo $dbasequery | cut -d \  -f 10`
iDBcounter2_Velleman=`echo $dbasequery | cut -d \  -f 11`
iDBEM_Tarif_1=`echo $dbasequery | cut -d \  -f 12`
iDBEM_Tarif_2=`echo $dbasequery | cut -d \  -f 13`
iPulsesPerKW=`echo $dbasequery | cut -d \  -f 14`
iDBTarif_1=`echo $dbasequery | cut -d \  -f 15`
iDBTarif_2=`echo $dbasequery | cut -d \  -f 16`
iGasCounter=`echo $dbasequery | cut -d \  -f 17`
dUpdateTimestampDATE=`echo $dbasequery | cut -d \  -f 18`
dUpdateTimestampTIME=`echo $dbasequery | cut -d \  -f 19`

#echo "Start DB Variables"
#echo "     iPulsesPerKW:" $iPulsesPerKW
#echo "     iDBcounter1_Velleman:" $iDBcounter1_Velleman
#echo "     iDBcounter2_Velleman:" $iDBcounter2_Velleman
#echo "     iDBEM_Tarif_1:" $iDBEM_Tarif_1
#echo "     iDBEM_Tarif_2:" $iDBEM_Tarif_2
#echo "     iDBTarif_1:" $iDBTarif_1
#echo "     iDBTarif_2:" $iDBTarif_2
#echo "     iGasCounter:" $iGasCounter
#echo "     dUpdateTimestampDATE:" $dUpdateTimestampDATE
#echo "     dUpdateTimestampTIME:" $dUpdateTimestampTIME
#echo "     dCurrentDATE:" $CurrentDate
#echo "     dCurrentTIME:" $CurrentTime

#echo "End DBVariables"








# Read info from board and put into variable: sK8055_Output
UnixTime=$(perl -e 'print time, "\n" ')
CurrentDate=`date +%Y-%m-%d`
CurrentTime=`date +%H:%M:%S`
sK8055_Output=$(/opt/velleman/src/k8055 -p:0)
#echo "sK8055_Output:" $sK8055_Output

# Place output into seperate variables
iMSec=`echo $sK8055_Output | cut -d \; -f 1`
iDigitalInput=`echo $sK8055_Output | cut -d \; -f 2`
iAnalog1=`echo $sK8055_Output | cut -d \; -f 3`
iAnalog2=`echo $sK8055_Output | cut -d \; -f 4`
iCounter1=`echo $sK8055_Output | cut -d \; -f 5`
iCounter2=`echo $sK8055_Output | cut -d \; -f 6`
#echo "Start Hardware Variables"
#echo "     iMSec:" $iMSec
#echo "     iDigitalInput:" $iDigitalInput
#echo "     iAnalog1:" $iAnalog1
#echo "     iAnalog2:" $iAnalog2
#echo "     iCounter1:" $iCounter1
#echo "     iCounter2:" $iCounter2
#echo "End Hardware Variables"


#push input variable $iDigitalInput into function to determine which ports are selected.
fn8BitIntToBinary $iDigitalInput
BinaryInputs=$ReturnValue

#InputPort3 input for day or night tarif. if InputPort=1 then low tarif if = 0 then high tarif


PulseUsage=$((iCounter1-iDBcounter1_Velleman))
WattsPerPulse=`echo "scale=2 ; 1000 / $iPulsesPerKW" | bc`
WattsUsed=`echo "scale=2 ; $PulseUsage*$WattsPerPulse" | bc`
#echo $WattsUsed

if [ $iCounter1 -ge $iPulsesPerKW ]; then 
	iCounter1=0
	sK8055_Output=$(/opt/velleman/src/k8055 -p:0 -reset1)
fi



#CurrentDate
CY=`echo $CurrentDate | cut -d \- -f 1`
CM=`echo $CurrentDate | cut -d \- -f 2`
CD=`echo $CurrentDate | cut -d \- -f 3`
Ch=`echo $CurrentTime | cut -d \: -f 1`
Cm=`echo $CurrentTime | cut -d \: -f 2`
Cs=`echo $CurrentTime | cut -d \: -f 3`


#Stored Date from database from previous reading
DY=`echo $dUpdateTimestampDATE | cut -d \- -f 1`
DM=`echo $dUpdateTimestampDATE | cut -d \- -f 2`
DD=`echo $dUpdateTimestampDATE | cut -d \- -f 3`
Dh=`echo $dUpdateTimestampTIME | cut -d \: -f 1`
Dm=`echo $dUpdateTimestampTIME | cut -d \: -f 2`
Ds=`echo $dUpdateTimestampTIME | cut -d \: -f 3`





#Calculate the seconds starting in 1970 for 2 variables: Current Time and last update timestamp Date Time
#How this works. It starts at 1970, calculating the seconds until the point of the date/time in the variable.
Csecs=$((CY-1970))									#Difference in years from currentyear-1970
Csecs=`echo "scale=2 ; $Csecs * 365.25" | bc`		#calculate days from years
Csecs=`echo "scale=2 ; $Csecs + ($CM*30.5)" | bc`	#add the part off the current month
Csecs=`echo "scale=2 ; $Csecs + $CD" | bc`			#add the days of the current month
Csecs=`echo "scale=2 ; $Csecs*24*60*60" | bc`		#now that we have number of days, starting in 1970, calculate number of seconds x24hours x60minutes x60secons
Csecs=`echo "scale=2 ; $Csecs + ($Ch*60*60)" | bc`	#add the hours in seconds of the current day
Csecs=`echo "scale=2 ; $Csecs + ($Cm*60)" | bc`		#add the minutes in seconds of the current day
Csecs=`echo "scale=2 ; $Csecs + $Cs" | bc`			#add the seconds of the current day.

#And do again but now with the date from the database... the date/time of the last reading.
Dsecs=$((DY-1970))
Dsecs=`echo "scale=2 ; $Dsecs * 365.25" | bc`
Dsecs=`echo "scale=2 ; $Dsecs + ($DM*30.5)" | bc`
Dsecs=`echo "scale=2 ; $Dsecs + $DD" | bc`
Dsecs=`echo "scale=2 ; $Dsecs*24*60*60" | bc`
Dsecs=`echo "scale=2 ; $Dsecs + ($Dh*60*60)" | bc`
Dsecs=`echo "scale=2 ; $Dsecs + ($Dm*60)" | bc`
Dsecs=`echo "scale=2 ; $Dsecs + $Ds" | bc`


# difference in seconds from previous reading
DiffSecs=`echo "scale=2 ; $Csecs - $Dsecs" | bc`
#echo $DiffSecs

WattsPerMinute=`echo "scale=2 ; ($WattsUsed/$DiffSecs)*60" | bc`
KwPerHour=`echo "scale=4 ; (($WattsUsed/$DiffSecs)*60*60)/1000" | bc`
#echo $WattsPerMinute
#echo $KwPerHour



if [ $InputPort3 = 1 ]; then # if = 1 then input 3 is high which means high tarif (1) else, tarif low (2)
	iDBEM_Tarif_1=`echo "scale=5 ; $iDBEM_Tarif_1 + ($WattsUsed/1000)" | bc`
	CostPerHour=`echo "scale=5 ; $KwPerHour * $iDBTarif_1" | bc`
else
	iDBEM_Tarif_2=`echo "scale=5 ; $iDBEM_Tarif_2 + ($WattsUsed/1000)" | bc`
	CostPerHour=`echo "scale=5 ; $KwPerHour * $iDBTarif_2" | bc`
fi

#echo '---'
#echo $CostPerHour

DBUpdateDate=$CurrentDate'_'$CurrentTime

dbasequery=`mysql -u$sDBUSER -p$sDBPASS -e'use '$sDBNAME'; UPDATE tblHardwareCounter SET counter1_Velleman = '$iCounter1' , counter2_Velleman ='$iCounter2', EM_Tarif_1 = '$iDBEM_Tarif_1', 
EM_Tarif_2 = '$iDBEM_Tarif_2', UpdateTimestamp = "'$DBUpdateDate'";'`
#echo $dbasequery

dbasequery=`mysql -u$sDBUSER -p$sDBPASS -e'use '$sDBNAME'; INSERT INTO tblEnergyMeter (datetime, MeterValue_1, MeterValue_2, CurrentMeter, WattsPerMinute, KiloWattsPerHour, CostperHour, MeasurementTimeInSeconds) VALUES ("'$DBUpdateDate'", '$iDBEM_Tarif_1', '$iDBEM_Tarif_2', '$InputPort3', '$WattsPerMinute', '$KwPerHour', '$CostPerHour', '$DiffSecs');'`
#echo $dbasequery





#echo "++EOF++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"




