Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import time
- import datetime
- import urllib2
- import re
- import json
- import math
- import sys
- sys.stdout = open("/home/pi/energy.log", "w")
- global totalWattsSoFar, lastEnergyUpdate, lastEnergyUpdateDateTime, domoticz_url, ip, userVarIdx, deviceIdx
- ip = "192.168.0.99:8080"
- userVarIdx = "2"
- deviceIdx = "8"
- # to start off with, grab the running energy total, and the last update date from domoticz
- while True:
- try:
- # the virtual energy device has the running total stored as '1234 kWh'
- domoticz_url = "http://" + ip + "/json.htm?type=devices&rid=" + deviceIdx
- json_data = urllib2.urlopen(domoticz_url).read()
- json_dict = json.loads(json_data)
- totalWattsString = json_dict["result"][0]["Data"]
- print "Total Watts String: " + totalWattsString
- totalWattsSoFar = float(totalWattsString[0:len(totalWattsString) - 4]) * 1000
- # the last update date is stored in a user variable in the form of seconds since epoch
- domoticz_url = "http://" + ip + "/json.htm?type=command¶m=getuservariable&idx=" + userVarIdx
- json_data = urllib2.urlopen(domoticz_url).read()
- json_dict = json.loads(json_data)
- lastEnergyUpdateString = json_dict["result"][0]["Value"]
- lastEnergyUpdate = float(lastEnergyUpdateString)
- lastEnergyUpdateDateTime = datetime.datetime.utcfromtimestamp(lastEnergyUpdate)
- print "Total Watts: " + str(totalWattsSoFar) + ", Time since last update: " + str(lastEnergyUpdateDateTime)
- break
- except:
- time.sleep(10) # in case of domoticz downtime, just wait and try again
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.bind(('0.0.0.0', 9761))
- epoch = datetime.datetime.utcfromtimestamp(0)
- # infinite loop
- while True:
- # wait for an energy update
- data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
- #print "received message:", data
- if "todUse" in data:
- try:
- # calculate the time in seconds since the last update
- currentDateTime = datetime.datetime.now()
- elapsedTimeSinceEpoch = currentDateTime - epoch
- elapsedSecondsSinceEpoch = elapsedTimeSinceEpoch.total_seconds()
- elapsedTimeSinceLastUpdate = currentDateTime - lastEnergyUpdateDateTime
- elapsedSecondsSinceLastUpdate = elapsedTimeSinceLastUpdate.total_seconds()
- print "Seconds since last update: " + str(elapsedSecondsSinceLastUpdate)
- # extract the current usage
- json_dict = json.loads(data[2:])
- currentWatts = json_dict["cUse"]
- #currWatts = math.ceil(json_dict["cUse"] / 0.8) # test without adjustment to start off with
- #todayWatts = math.ceil(json_dict["todUse"] / 0.8) # this figure is unreliable and unsuitable for the domoticz counter anyway
- # calculate the additional watts used since last reading and add this to the total
- additionalWatts = (elapsedSecondsSinceLastUpdate / 3600 * currentWatts) if lastEnergyUpdate > 0 else 0
- totalWattsSoFar += additionalWatts
- # output the reading to the os log
- timeStamp = str(currentDateTime.hour).zfill(2) + ":" + str(currentDateTime.minute).zfill(2) + ":" + str(currentDateTime.second).zfill(2)
- print timeStamp + ", Curr Watts: " + str(currentWatts) + ", Add Watts: " + str(additionalWatts) + ", Tot Watts: " + str(totalWattsSoFar)
- # send the new readings
- domoticz_url = "http://" + ip + "/json.htm?type=command¶m=udevice&idx=" + deviceIdx + "&nvalue=0&svalue="+str(currentWatts)+";"+str(totalWattsSoFar)
- urllib2.urlopen(domoticz_url)
- # update the local vars ready for next reading
- lastEnergyUpdate = elapsedSecondsSinceEpoch
- lastEnergyUpdateDateTime = datetime.datetime.utcfromtimestamp(lastEnergyUpdate)
- # update the domoticz user variable with the last update date (only used on restart of script)
- domoticz_url = "http://" + ip + "/json.htm?type=command¶m=updateuservariable&idx=" + userVarIdx + "&vname=lastEnergyUpdate&vtype=1&vvalue="+str(lastEnergyUpdate)
- urllib2.urlopen(domoticz_url).read()
- time.sleep(10)
- except:
- time.sleep(10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement