#!/usr/bin/env python
import serial
import os
import re
import fcntl
import time
import sys



if __name__ == '__main__':
    f = open ('/tmp/lock', 'w')
    try: fcntl.lockf (f, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except:
        sys.stderr.write ('[%s] Script already running.\n' % time.strftime ('%c') )
        sys.exit (-1)

valuekw = float(0.0)

ser = serial.Serial('/dev/ttyACM0',9600)
while True:
	read_serial=ser.readline()
	print read_serial
	p = re.compile("KW=<(.*?)>")
	m = p.search(read_serial)
	if m:
    		value = m.group(1)
		print value
		command_domoticz = 'curl \"http://10.0.1.10:8080/json.htm?type=command&param=udevice&idx=14&nvalue=0&svalue='+value+';69\"'
		os.system(command_domoticz)
		valuekw=valuekw+float(value)/1000/60
		print valuekw
                command_domoticz = 'curl \"http://10.0.1.10:8080/json.htm?type=command&param=udevice&idx=82&nvalue=0&svalue='+str(valuekw)+';'+value+'\"'
                os.system(command_domoticz)