Advertisement
Guest User

Domoticz_LWRF_EnergyMon

a guest
Nov 7th, 2014
421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.92 KB | None | 0 0
  1. import socket
  2. import time
  3. import datetime
  4. import urllib2
  5. import re
  6. import json
  7. import math
  8. import sys
  9.  
  10. sys.stdout = open("/home/pi/energy.log", "w")
  11.  
  12. global totalWattsSoFar, lastEnergyUpdate, lastEnergyUpdateDateTime, domoticz_url, ip, userVarIdx, deviceIdx
  13.  
  14. ip = "192.168.0.99:8080"
  15. userVarIdx = "2"
  16. deviceIdx = "8"
  17.  
  18. # to start off with, grab the running energy total, and the last update date from domoticz
  19. while True:
  20.     try:
  21.         # the virtual energy device has the running total stored as '1234 kWh'
  22.         domoticz_url = "http://" + ip + "/json.htm?type=devices&rid=" + deviceIdx
  23.         json_data = urllib2.urlopen(domoticz_url).read()
  24.         json_dict = json.loads(json_data)
  25.         totalWattsString = json_dict["result"][0]["Data"]
  26.         print "Total Watts String: " + totalWattsString
  27.         totalWattsSoFar = float(totalWattsString[0:len(totalWattsString) - 4]) * 1000
  28.  
  29.         # the last update date is stored in a user variable in the form of seconds since epoch
  30.         domoticz_url = "http://" + ip + "/json.htm?type=command&param=getuservariable&idx=" + userVarIdx
  31.         json_data = urllib2.urlopen(domoticz_url).read()
  32.         json_dict = json.loads(json_data)
  33.         lastEnergyUpdateString = json_dict["result"][0]["Value"]
  34.         lastEnergyUpdate = float(lastEnergyUpdateString)
  35.         lastEnergyUpdateDateTime = datetime.datetime.utcfromtimestamp(lastEnergyUpdate)
  36.         print "Total Watts: " + str(totalWattsSoFar) + ", Time since last update: " + str(lastEnergyUpdateDateTime)
  37.         break
  38.     except:
  39.         time.sleep(10) # in case of domoticz downtime, just wait and try again
  40.  
  41. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  42. sock.bind(('0.0.0.0', 9761))
  43. epoch = datetime.datetime.utcfromtimestamp(0)
  44.  
  45. # infinite loop
  46. while True:
  47.     # wait for an energy update
  48.     data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
  49.     #print "received message:", data
  50.     if "todUse" in data:
  51.         try:
  52.             # calculate the time in seconds since the last update
  53.             currentDateTime = datetime.datetime.now()
  54.             elapsedTimeSinceEpoch = currentDateTime - epoch
  55.             elapsedSecondsSinceEpoch = elapsedTimeSinceEpoch.total_seconds()
  56.             elapsedTimeSinceLastUpdate = currentDateTime - lastEnergyUpdateDateTime
  57.             elapsedSecondsSinceLastUpdate = elapsedTimeSinceLastUpdate.total_seconds()
  58.             print "Seconds since last update: " + str(elapsedSecondsSinceLastUpdate)
  59.            
  60.             # extract the current usage
  61.             json_dict = json.loads(data[2:])
  62.             currentWatts = json_dict["cUse"]
  63.             #currWatts = math.ceil(json_dict["cUse"] / 0.8) # test without adjustment to start off with
  64.             #todayWatts = math.ceil(json_dict["todUse"] / 0.8) # this figure is unreliable and unsuitable for the domoticz counter anyway
  65.                
  66.             # calculate the additional watts used since last reading and add this to the total
  67.             additionalWatts = (elapsedSecondsSinceLastUpdate / 3600 * currentWatts) if lastEnergyUpdate > 0 else 0
  68.             totalWattsSoFar += additionalWatts
  69.            
  70.             # output the reading to the os log
  71.             timeStamp = str(currentDateTime.hour).zfill(2) + ":" + str(currentDateTime.minute).zfill(2) + ":" + str(currentDateTime.second).zfill(2)
  72.             print timeStamp + ", Curr Watts: " + str(currentWatts) + ", Add Watts: " + str(additionalWatts) + ", Tot Watts: " + str(totalWattsSoFar)
  73.            
  74.             # send the new readings
  75.             domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + deviceIdx + "&nvalue=0&svalue="+str(currentWatts)+";"+str(totalWattsSoFar)
  76.             urllib2.urlopen(domoticz_url)
  77.            
  78.             # update the local vars ready for next reading
  79.             lastEnergyUpdate = elapsedSecondsSinceEpoch
  80.             lastEnergyUpdateDateTime = datetime.datetime.utcfromtimestamp(lastEnergyUpdate)
  81.            
  82.             # update the domoticz user variable with the last update date (only used on restart of script)
  83.             domoticz_url = "http://" + ip + "/json.htm?type=command&param=updateuservariable&idx=" + userVarIdx + "&vname=lastEnergyUpdate&vtype=1&vvalue="+str(lastEnergyUpdate)
  84.             urllib2.urlopen(domoticz_url).read()
  85.                
  86.             time.sleep(10)
  87.         except:
  88.             time.sleep(10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement