import serial
import re
import MySQLdb

dbName = "electricity"
tblName = "consumption"
uName = "xxxx"
pswd = "xxxx"

ser = serial.Serial('/dev/ttyUSB0')
db=MySQLdb.connect(user=uName, passwd=pswd,db=dbName)
c = db.cursor()
prevWatts = 0
deltaT = 0

while 1:
	
        line=""
        try:
                ser = serial.Serial('/dev/ttyUSB0')
                line = ser.readline()   #read a '\n' terminated line
                ser.close()
        except:
                print "Error"

        m = re.search('.*<hr>(\d{2}).*<min>(\d{2}).*<sec>(\d{2}).*<ch1><watts>[0]*([1-9][0-9]*).*<tmpr>([0-9]*.[0-9])',line)
       
	if m is not None:
		hours = m.group(1)
 		mins = m.group(2)
		secs = m.group(3)
        	watts = m.group(4)
        	temp = m.group(5)
		
		totalTime = (int(hours)*3600) + (int(mins)*60) + int(secs)

		if deltaT == 0:   
			deltaT = 6
	
		else:
			deltaT = int(totalTime) - int(prevTime)

		prevTime = totalTime
		deltaW = int(watts) - int(prevWatts)
        	prevWatts = int(watts)
		joules = (prevWatts + int(watts))*0.5*deltaT	

		c.execute("INSERT INTO consumption (power, temp, joules, time) VALUES (%s, %s, %s, NOW())",(watts,temp,joules))

	#print watts+"W"
        #print temp+"C"
	#print deltaT
	#print deltaW

ser.close()

