Advertisement
Guest User

Domoticz_LWRF_EnergyMon - Revised

a guest
Nov 2nd, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.76 KB | None | 0 0
  1. #!/usr/bin/python
  2. import socket
  3. import time
  4. import datetime
  5. import urllib2
  6. import re
  7. import json
  8. import math
  9. import sys
  10.  
  11. sys.stdout = open("/home/pi/energy.log", "w")
  12.  
  13. global totalWattsSoFar, lastEnergyUpdate, lastEnergyUpdateDateTime, domoticz_url, ip, userVarIdx, deviceIdx
  14.  
  15. ip = "192.168.1.XXX:8080"   #IP adddress & port number of Domoticz server
  16. userVarIdx = "XX"       #User Variable "lastEnergyUpdate" Idx reference number
  17. deviceIdx = "XX"        #Energy Meter Idx reference number
  18. temp1FEIdx = "XX"       #TRV1 Temperature Idx reference number
  19. temp2REIdx = "XX"       #TRV2 Temperature Idx reference number
  20. temp3KIIdx = "XX"       #TRV3 Temperature Idx reference number
  21. battery1FEIdx = "XX"        #TRV1 Battery level Idx reference number
  22. battery2REIdx = "XX"        #TRV2 Battery level Idx reference number
  23. battery3KIIdx = "XX"        #TRV3 Battery level Idx reference number
  24. lwrfbaseIdx = "XX"      #LWRF Link Firmware Idx reference number
  25. lwrftrvIdx = "XX"       #TRV Firmware Idx reference number
  26. trv1 = "314XX"          #TRV1 Serial Number
  27. trv2 = "D16XX"          #TRV2 Serial Number
  28. trv3 = "534XX"          #TRV3 Serial Number
  29.  
  30. trvfwold ="not set"
  31. basefwold ="not set"
  32. # to start off with, grab the running energy total, and the last update date from domoticz
  33. while True:
  34.     try:
  35.         # the virtual energy device has the running total stored as '1234 kWh'
  36.         domoticz_url = "http://" + ip + "/json.htm?type=devices&rid=" + deviceIdx
  37.         json_data = urllib2.urlopen(domoticz_url).read()
  38.         json_dict = json.loads(json_data)
  39.         totalWattsString = json_dict["result"][0]["Data"]
  40.         print "Total Watts String: " + totalWattsString
  41.         totalWattsSoFar = float(totalWattsString[0:len(totalWattsString) - 4]) * 1000
  42.  
  43.         # the last update date is stored in a user variable in the form of seconds since epoch
  44.         domoticz_url = "http://" + ip + "/json.htm?type=command&param=getuservariable&idx=" + userVarIdx
  45.         json_data = urllib2.urlopen(domoticz_url).read()
  46.         json_dict = json.loads(json_data)
  47.         lastEnergyUpdateString = json_dict["result"][0]["Value"]
  48.         lastEnergyUpdate = float(lastEnergyUpdateString)
  49.         lastEnergyUpdateDateTime = datetime.datetime.utcfromtimestamp(lastEnergyUpdate)
  50.         print "Total Watts: " + str(totalWattsSoFar) + ", Time since last update: " + str(lastEnergyUpdateDateTime)
  51.         break
  52.     except:
  53.         time.sleep(10) # in case of domoticz downtime, just wait and try again
  54.  
  55. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  56. sock.bind(('0.0.0.0', 9761))
  57. epoch = datetime.datetime.utcfromtimestamp(0)
  58.  
  59. # infinite loop
  60. while True:
  61.     # wait for an energy update
  62.     # if "todUse" in data:
  63.     data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
  64.     #print "received message:", data
  65.     if "todUse" in data:
  66.         try:
  67.             # energy monitor data from device
  68.             # calculate the time in seconds since the last update
  69.             currentDateTime = datetime.datetime.now()
  70.             elapsedTimeSinceEpoch = currentDateTime - epoch
  71.             elapsedSecondsSinceEpoch = elapsedTimeSinceEpoch.total_seconds()
  72.             elapsedTimeSinceLastUpdate = currentDateTime - lastEnergyUpdateDateTime
  73.             elapsedSecondsSinceLastUpdate = elapsedTimeSinceLastUpdate.total_seconds()
  74.             print "Seconds since last update: " + str(elapsedSecondsSinceLastUpdate)
  75.            
  76.             # extract the current usage
  77.             json_dict = json.loads(data[2:])
  78.             currentWatts = json_dict["cUse"]
  79.             #
  80.             #currWatts = math.ceil(json_dict["cUse"] / 0.8) # test without adjustment to start off with
  81.             #todayWatts = math.ceil(json_dict["todUse"] / 0.8) # this figure is unreliable and unsuitable for the domoticz counter anyway
  82.                
  83.             # calculate the additional watts used since last reading and add this to the total
  84.             additionalWatts = (elapsedSecondsSinceLastUpdate / 3600 * currentWatts) if lastEnergyUpdate > 0 else 0
  85.             totalWattsSoFar += additionalWatts
  86.            
  87.             # output the reading to the os log
  88.             timeStamp = str(currentDateTime.hour).zfill(2) + ":" + str(currentDateTime.minute).zfill(2) + ":" + str(currentDateTime.second).zfill(2)
  89.             print timeStamp + ", Curr Watts: " + str(currentWatts) + ", Add Watts: " + str(additionalWatts) + ", Tot Watts: " + str(totalWattsSoFar)
  90.            
  91.             # send the new readings
  92.             domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + deviceIdx + "&nvalue=0&svalue="+str(currentWatts)+";"+str(totalWattsSoFar)
  93.             urllib2.urlopen(domoticz_url)
  94.            
  95.             # update the local vars ready for next reading
  96.             lastEnergyUpdate = elapsedSecondsSinceEpoch
  97.             lastEnergyUpdateDateTime = datetime.datetime.utcfromtimestamp(lastEnergyUpdate)
  98.            
  99.             # update the domoticz user variable with the last update date (only used on restart of script)
  100.             domoticz_url = "http://" + ip + "/json.htm?type=command&param=updateuservariable&idx=" + userVarIdx + "&vname=lastEnergyUpdate&vtype=1&vvalue="+str(lastEnergyUpdate)
  101.             urllib2.urlopen(domoticz_url).read()
  102.                
  103.             #time.sleep(10)
  104.         except:
  105.             time.sleep(10)
  106.  
  107. ##  elif trv1 in data: # Reads data from TRV1####################################################
  108. ##      try:
  109. ##          #print "Room 1 TRV"
  110. ##          # extract current temperature & battery level & TRV firmware verion from TRV1
  111. ##          json_dict = json.loads(data[2:])
  112. ##          currentTemp = json_dict["cTemp"]
  113. ##          battery = json_dict["batt"]
  114. ##          trvfw = json_dict["ver"]
  115. ##          #print currentTemp
  116. ##          #print battery
  117. ##          #print trvfw
  118. ##
  119. ##          # send the new readings
  120. ##          domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + temp1FEIdx + "&nvalue=0&svalue="+str(currentTemp)
  121. ##          urllib2.urlopen(domoticz_url)
  122. ##          domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + battery1FEIdx + "&nvalue=0&svalue="+str(battery)
  123. ##          urllib2.urlopen(domoticz_url)
  124. ##         
  125. ##          if trvfw != trvfwold: #Only update Domoticz on first reading or if firmware updates
  126. ##              domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + lwrftrvIdx + "&nvalue=0&svalue="+str(trvfw)
  127. ##              urllib2.urlopen(domoticz_url)
  128. ##              trvfwold = trvfw
  129. ##
  130. ##          #time.sleep(10)
  131. ##      except:
  132. ##          time.sleep(10)
  133. ##
  134. ##  elif trv2 in data: # Reads data from TRV1####################################################
  135. ##      try:
  136. ##          #print "Room 2 TRV"
  137. ##          # extract current temperature & battery level & TRV firmware verion from TRV2
  138. ##          json_dict = json.loads(data[2:])
  139. ##          currentTemp = json_dict["cTemp"]
  140. ##          battery = json_dict["batt"]
  141. ##          trvfw = json_dict["ver"]
  142. ##          #print currentTemp
  143. ##          #print battery
  144. ##          #print trvfw
  145. ##
  146. ##          # send the new readings
  147. ##          domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + temp2REIdx + "&nvalue=0&svalue="+str(currentTemp)
  148. ##          urllib2.urlopen(domoticz_url)
  149. ##          domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + battery2REIdx + "&nvalue=0&svalue="+str(battery)
  150. ##          urllib2.urlopen(domoticz_url)
  151. ##
  152. ##
  153. ##          if trvfw != trvfwold: #Only update Domoticz on first reading or if firmware updates
  154. ##              domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + lwrftrvIdx + "&nvalue=0&svalue="+str(trvfw)
  155. ##              urllib2.urlopen(domoticz_url)
  156. ##              trvfwold = trvfw
  157. ##
  158. ##          #time.sleep(10)
  159. ##      except:
  160. ##          time.sleep(10)
  161. ##
  162. ##  elif trv3 in data: # Reads data from TRV1####################################################
  163. ##      try:
  164. ##          #print "Room 3 TRV"
  165. ##          # extract current temperature & battery level & TRV firmware verion from TRV3
  166. ##          json_dict = json.loads(data[2:])
  167. ##          currentTemp = json_dict["cTemp"]
  168. ##          battery = json_dict["batt"]
  169. ##          trvfw = json_dict["ver"]
  170. ##          #print currentTemp
  171. ##          #print battery
  172. ##          #print trvfw
  173. ##
  174. ##          # send the new readings
  175. ##          domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + temp3KIIdx + "&nvalue=0&svalue="+str(currentTemp)
  176. ##          urllib2.urlopen(domoticz_url)
  177. ##          domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + battery3KIIdx + "&nvalue=0&svalue="+str(battery)
  178. ##          urllib2.urlopen(domoticz_url)
  179. ##
  180. ##          if trvfw != trvfwold: #Only update Domoticz on first reading or if firmware updates
  181. ##              domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + lwrftrvIdx + "&nvalue=0&svalue="+str(trvfw)
  182. ##              urllib2.urlopen(domoticz_url)
  183. ##              trvfwold = trvfw
  184. ##
  185. ##          #time.sleep(10)
  186. ##      except:
  187. ##          time.sleep(10)
  188. ##
  189. ##  elif "system" in data: # Reads LRV Link firmware ##################################################
  190. ##      try:
  191. ##          # extract LWRF Link firmware level
  192. ##          json_dict = json.loads(data[2:])           
  193. ##          basefw = json_dict["fw"]
  194. ##          #print basefw
  195. ##
  196. ##          # send the new readings
  197. ##          if basefw != basefwold: #Only update Domoticz on first reading or if firmware updates
  198. ##              domoticz_url = "http://" + ip + "/json.htm?type=command&param=udevice&idx=" + lwrfbaseIdx + "&nvalue=0&svalue="+str(basefw)
  199. ##              urllib2.urlopen(domoticz_url)
  200. ##              basefwold = basefw
  201. ##
  202. ##          #time.sleep(10)
  203. ##      except:
  204. ##          time.sleep(10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement