Advertisement
Damien-V

Arduino Elec/water/DHT sketch

Aug 19th, 2017
1,179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.20 KB | None | 0 0
  1. # -*- coding: latin-1 -*-
  2.  
  3. from datetime import datetime
  4. import smbus
  5. import time
  6. import httplib, urllib, urllib2
  7. import json
  8. import os
  9.  
  10. bus = smbus.SMBus(1)                # Change 1 to 0 if Old revision of Rpi
  11. address = 0x04                      # Arduino adress
  12. C = 2.5                             # Watt per turn of the rotating disk
  13.  
  14. idx_dummy_counter_elec = "259"                          # domoticz dummy counter idx
  15. idx_dummy_counter_water = "906"                         # domoticz water dummy counter idx
  16. idx_uservariable = ["18"]                               # domoticz uservariable idx of current kWh
  17. name_uservariable = ["EDF_Current_kWh"]                 # domoticz uservariable name
  18. type_uservariable = "1"                                 # domoticz uservariable type (1=decimal)
  19. domoticz = "http://192.168.1.18:8080/"                  # domoticz local IP (no auth required)
  20.  
  21. idx_sdbDHT = "653"                                      #domoticz DHT virtual sensor
  22. idx_grenierDHT = "659"                                  #domoticz DHT virtual sensor
  23.  
  24. ScriptName=__file__.split("/")                          # split the file path, allows to get only the script name using ScriptName[-1]
  25.  
  26. # This function returns the value of one of the above-defined uservariable
  27. def GetUservariableData(number):                       
  28.     try:
  29.         request_add = domoticz + "json.htm?type=command&param=getuservariable&idx=" + idx_uservariable[number]
  30.         rep = urllib2.urlopen(request_add)
  31.         jsoncontent = str(rep.read())
  32.         jsondata = json.loads(jsoncontent)
  33.         return float(jsondata['result'][0]['Value'])    # Return value of uservariable
  34.     except urllib2.URLError:
  35.         exit()                                          # end script if URL couldn't be reached
  36.  
  37. # This procedure update the value of the water counter     
  38. def UpdateWaterCounter(idx, data):                     
  39.     try:
  40.         request_add = domoticz + "json.htm?type=command&param=udevice&idx=" + idx + "&nvalue=0&svalue=" + str(data)
  41.         req = urllib2.Request(request_add)
  42.         result = urllib2.urlopen(req)
  43.     except urllib2.URLError:
  44.         exit()                                          # end script if URL couldn't be reached    
  45.  
  46. # This procedure update the value of one of the above-defined uservariable     
  47. def UpdateUservariable(number, data):                  
  48.     try:
  49.         request_add = domoticz + "json.htm?type=command&param=updateuservariable&idx=" + idx_uservariable[number] + "&vname=" + name_uservariable[number] + "&vtype=" + type_uservariable + "&vvalue=" + str(data)
  50.         req = urllib2.Request(request_add)
  51.         result = urllib2.urlopen(req)
  52.     except urllib2.URLError:
  53.         exit()                                          # end script if URL couldn't be reached
  54.  
  55. # Update Energy Meter in domoticz      
  56. def UpdateEnergyMeter(power, energy):                  
  57.     try:
  58.         request_add = domoticz + "json.htm?type=command&param=udevice&idx=" + idx_dummy_counter_elec + "&nvalue=0&svalue=" + str(power) + ";" + str(energy)
  59.         req = urllib2.Request(request_add)
  60.         result = urllib2.urlopen(req)
  61.     except urllib2.URLError:
  62.         exit()                                          # end script if URL couldn't be reached
  63.  
  64. # Update DHT in domoticz       
  65. def UpdateDHT(idx, temperature, humidity):             
  66.     try:
  67.         request_add = domoticz + "json.htm?type=command&param=udevice&idx=" + idx + "&nvalue=0&svalue=" + str(temperature) + ";" + str(humidity) + ";0"
  68.         req = urllib2.Request(request_add)
  69.         result = urllib2.urlopen(req)
  70.     except urllib2.URLError:
  71.         exit()                                          # end script if URL couldn't be reached
  72.  
  73. # Convert the DHT value (from signed to unsigned)      
  74. def ConvertToSignedDHT(var):
  75.     if (var > 327.68):
  76.         #print "Negative Value follows !!"     
  77.         return var-655.36                               # first bit set to 1 = huge value to represent a negative value
  78.     else:
  79.         #print "Positive Value follows !!"     
  80.         return var
  81.  
  82. # Add an entry into domoticz log (and log the script name)
  83. def UpdateDomoticzLog(string):
  84.     stringlog = ScriptName[-1] + " " + string  
  85.     stringencoded = urllib.quote_plus(stringlog)       
  86.     request_add = domoticz + "json.htm?type=command&param=addlogmessage&message=" + stringencoded  
  87.     try:
  88.         req = urllib2.Request(request_add.encode('latin-1'))
  89.         result = urllib2.urlopen(req)
  90.     except urllib2.URLError:
  91.         print "Fail to update log with this request: " + request_add       
  92.  
  93. # Add an entry into domoticz log with the adequate format  
  94. def LogToDomoticzWithFormat(message):
  95.     UpdateDomoticzLog("<font color=\"Black\"><b>[I2C]</b> " + message + "</font>")     
  96.  
  97. # Retrieve the last update in seconds of a device  
  98. def GetLastUpdateInSeconds(idx):                # This function returns the value of the last update of the idx in seconds
  99.     try:
  100.         request_add = domoticz + "json.htm?type=devices&rid=" + str(idx)
  101.         rep = urllib2.urlopen(request_add)
  102.     except urllib2.URLError:
  103.         exit()                                  # end script if URL couldn't be reached
  104.     jsoncontent = str(rep.read())
  105.     jsondata = json.loads(jsoncontent)
  106.     LastUpdate = jsondata['result'][0]['LastUpdate']                                # Retrieve Json Last Update string
  107.     LastUpdateDateTimeFormat = datetime.strptime(LastUpdate, '%Y-%m-%d %H:%M:%S')   # Convert into datetime format
  108.     LastUpdateUnixFormat = time.mktime(LastUpdateDateTimeFormat.timetuple())        # Convert Last update in unix format
  109.     return int(time.time()-LastUpdateUnixFormat)
  110.    
  111. ######################
  112. # SCRIPT STARTS HERE #
  113. ######################
  114.  
  115. print "Sending processing request"
  116. try:
  117.     bus.write_byte(address, 0)
  118. except IOError, err:
  119.     print "Error while trying to write on bus: " + err
  120.     print "End of script"
  121.     LogToDomoticzWithFormat("Erreur lors de l'envoie de la requete [0], fin du script")
  122.     exit()
  123.    
  124. time.sleep(1)                           # sleep allows arduino to process "write" request and process data
  125.  
  126. print "Receiving data table"
  127. data = []                               # Init of data list to be received from Arduino
  128. i = 1
  129. while i < 15:
  130.     try:
  131.         bus.write_byte(address, i)      # send instruction "i"
  132.         time.sleep(0.1)                 # sleep allows arduino to process "write" request
  133.         data.append(bus.read_byte(address))
  134.         i += 1
  135.     except:
  136.         print 'Error while receiving data, exiting the script'
  137.         LogToDomoticzWithFormat("Erreur lors de la reception de donnees [" + i + "], fin du script</font>")
  138.         exit()
  139.  
  140. time.sleep(0.1)
  141. bus.write_byte(address, i)              # sends last instruction, allows to reset the counter inside the arduino
  142.        
  143. W = data[1] * 256 + data[0]
  144. Turn = data[3] * 256 + data[2]
  145. delta_kWh = C * Turn
  146. temp_SdB = ConvertToSignedDHT((data[4] + data[5] * 256)/100.)
  147. humid_SdB = (data[6] + data[7] * 256)/100.
  148. temp_Grenier = ConvertToSignedDHT((data[8] + data[9] * 256)/100.)
  149. humid_Grenier = (data[10] + data[11] * 256)/100.
  150. WaterLiter = (data[12] + data[13] * 256)
  151.  
  152. current_kWh = GetUservariableData(0) # Get value from uservariable 0 (current)     
  153.  
  154. print "Received data [elec]: ", W, " Watt ", Turn, " Turn ", delta_kWh, " delta kWh"
  155. print "Received data [SdB]: ", temp_SdB, "C ", humid_SdB, "%"
  156. print "Received data [Grenier]: ", temp_Grenier, "C ", humid_Grenier, "%"
  157. print "Received data [Water]: ", WaterLiter, "L "
  158.  
  159. #### Plausibility checks
  160. ElecCounterLastUpdate = GetLastUpdateInSeconds(idx_dummy_counter_elec)
  161. if (delta_kWh*60/ElecCounterLastUpdate > 150) or (delta_kWh > 15000) or (ElecCounterLastUpdate < 15):
  162.     LogToDomoticzWithFormat("La surveillance rapporte une erreur ! LastUpdate: " + str(ElecCounterLastUpdate) + "secondes, Energie: " + str(W) + " Watts, Consommation: +" + str(delta_kWh) + "Wh [" + str(current_kWh) + "]")
  163.     exit()
  164.  
  165. WaterCounterLastUpdate = GetLastUpdateInSeconds(idx_dummy_counter_water)
  166. if (WaterLiter*60/WaterCounterLastUpdate > 25) or (WaterLiter > 300) or (WaterCounterLastUpdate < 15):
  167.     LogToDomoticzWithFormat("La surveillance rapporte une erreur ! LastUpdate: " + str(WaterCounterLastUpdate) + "secondes, " + str(WaterLiter) + " litre(s) non pris en compte")
  168.     exit()
  169.    
  170. #### Processing of power/energy in Domoticz
  171. print "Current: ", current_kWh, " delta: ", delta_kWh
  172. UpdateEnergyMeter(W, (current_kWh + delta_kWh))
  173. UpdateUservariable(0, (current_kWh + delta_kWh))
  174.  
  175. if (delta_kWh > 0):
  176.     LogToDomoticzWithFormat("Energie: " + str(W) + " Watts, Consommation: +" + str(delta_kWh) + "Wh [" + str(current_kWh) + "]")
  177.  
  178. #### Processing of water in Domoticz
  179. UpdateWaterCounter(idx_dummy_counter_water, WaterLiter)
  180. if (WaterLiter > 0):
  181.     LogToDomoticzWithFormat("Ajout de " + str(WaterLiter) + " litre(s) au compteur")
  182.  
  183. #### Processing of temperature and humidity in Domoticz
  184. UpdateDHT(idx_sdbDHT, temp_SdB, humid_SdB)
  185. UpdateDHT(idx_grenierDHT, temp_Grenier, humid_Grenier)
  186. LogToDomoticzWithFormat("Salle de bain: " + str(temp_SdB) + "C / " + str(humid_SdB) + "% - Grenier: " + str(temp_Grenier) + "C / " + str(humid_Grenier) + "%")
  187.  
  188. print "Counters Updated !"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement