Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: latin-1 -*-
- from datetime import datetime
- import smbus
- import time
- import httplib, urllib, urllib2
- import json
- import os
- bus = smbus.SMBus(1) # Change 1 to 0 if Old revision of Rpi
- address = 0x04 # Arduino adress
- C = 2.5 # Watt per turn of the rotating disk
- idx_dummy_counter_elec = "259" # domoticz dummy counter idx
- idx_dummy_counter_water = "906" # domoticz water dummy counter idx
- idx_uservariable = ["18"] # domoticz uservariable idx of current kWh
- name_uservariable = ["EDF_Current_kWh"] # domoticz uservariable name
- type_uservariable = "1" # domoticz uservariable type (1=decimal)
- domoticz = "http://192.168.1.18:8080/" # domoticz local IP (no auth required)
- idx_sdbDHT = "653" #domoticz DHT virtual sensor
- idx_grenierDHT = "659" #domoticz DHT virtual sensor
- ScriptName=__file__.split("/") # split the file path, allows to get only the script name using ScriptName[-1]
- # This function returns the value of one of the above-defined uservariable
- def GetUservariableData(number):
- try:
- request_add = domoticz + "json.htm?type=command¶m=getuservariable&idx=" + idx_uservariable[number]
- rep = urllib2.urlopen(request_add)
- jsoncontent = str(rep.read())
- jsondata = json.loads(jsoncontent)
- return float(jsondata['result'][0]['Value']) # Return value of uservariable
- except urllib2.URLError:
- exit() # end script if URL couldn't be reached
- # This procedure update the value of the water counter
- def UpdateWaterCounter(idx, data):
- try:
- request_add = domoticz + "json.htm?type=command¶m=udevice&idx=" + idx + "&nvalue=0&svalue=" + str(data)
- req = urllib2.Request(request_add)
- result = urllib2.urlopen(req)
- except urllib2.URLError:
- exit() # end script if URL couldn't be reached
- # This procedure update the value of one of the above-defined uservariable
- def UpdateUservariable(number, data):
- try:
- request_add = domoticz + "json.htm?type=command¶m=updateuservariable&idx=" + idx_uservariable[number] + "&vname=" + name_uservariable[number] + "&vtype=" + type_uservariable + "&vvalue=" + str(data)
- req = urllib2.Request(request_add)
- result = urllib2.urlopen(req)
- except urllib2.URLError:
- exit() # end script if URL couldn't be reached
- # Update Energy Meter in domoticz
- def UpdateEnergyMeter(power, energy):
- try:
- request_add = domoticz + "json.htm?type=command¶m=udevice&idx=" + idx_dummy_counter_elec + "&nvalue=0&svalue=" + str(power) + ";" + str(energy)
- req = urllib2.Request(request_add)
- result = urllib2.urlopen(req)
- except urllib2.URLError:
- exit() # end script if URL couldn't be reached
- # Update DHT in domoticz
- def UpdateDHT(idx, temperature, humidity):
- try:
- request_add = domoticz + "json.htm?type=command¶m=udevice&idx=" + idx + "&nvalue=0&svalue=" + str(temperature) + ";" + str(humidity) + ";0"
- req = urllib2.Request(request_add)
- result = urllib2.urlopen(req)
- except urllib2.URLError:
- exit() # end script if URL couldn't be reached
- # Convert the DHT value (from signed to unsigned)
- def ConvertToSignedDHT(var):
- if (var > 327.68):
- #print "Negative Value follows !!"
- return var-655.36 # first bit set to 1 = huge value to represent a negative value
- else:
- #print "Positive Value follows !!"
- return var
- # Add an entry into domoticz log (and log the script name)
- def UpdateDomoticzLog(string):
- stringlog = ScriptName[-1] + " " + string
- stringencoded = urllib.quote_plus(stringlog)
- request_add = domoticz + "json.htm?type=command¶m=addlogmessage&message=" + stringencoded
- try:
- req = urllib2.Request(request_add.encode('latin-1'))
- result = urllib2.urlopen(req)
- except urllib2.URLError:
- print "Fail to update log with this request: " + request_add
- # Add an entry into domoticz log with the adequate format
- def LogToDomoticzWithFormat(message):
- UpdateDomoticzLog("<font color=\"Black\"><b>[I2C]</b> " + message + "</font>")
- # Retrieve the last update in seconds of a device
- def GetLastUpdateInSeconds(idx): # This function returns the value of the last update of the idx in seconds
- try:
- request_add = domoticz + "json.htm?type=devices&rid=" + str(idx)
- rep = urllib2.urlopen(request_add)
- except urllib2.URLError:
- exit() # end script if URL couldn't be reached
- jsoncontent = str(rep.read())
- jsondata = json.loads(jsoncontent)
- LastUpdate = jsondata['result'][0]['LastUpdate'] # Retrieve Json Last Update string
- LastUpdateDateTimeFormat = datetime.strptime(LastUpdate, '%Y-%m-%d %H:%M:%S') # Convert into datetime format
- LastUpdateUnixFormat = time.mktime(LastUpdateDateTimeFormat.timetuple()) # Convert Last update in unix format
- return int(time.time()-LastUpdateUnixFormat)
- ######################
- # SCRIPT STARTS HERE #
- ######################
- print "Sending processing request"
- try:
- bus.write_byte(address, 0)
- except IOError, err:
- print "Error while trying to write on bus: " + err
- print "End of script"
- LogToDomoticzWithFormat("Erreur lors de l'envoie de la requete [0], fin du script")
- exit()
- time.sleep(1) # sleep allows arduino to process "write" request and process data
- print "Receiving data table"
- data = [] # Init of data list to be received from Arduino
- i = 1
- while i < 15:
- try:
- bus.write_byte(address, i) # send instruction "i"
- time.sleep(0.1) # sleep allows arduino to process "write" request
- data.append(bus.read_byte(address))
- i += 1
- except:
- print 'Error while receiving data, exiting the script'
- LogToDomoticzWithFormat("Erreur lors de la reception de donnees [" + i + "], fin du script</font>")
- exit()
- time.sleep(0.1)
- bus.write_byte(address, i) # sends last instruction, allows to reset the counter inside the arduino
- W = data[1] * 256 + data[0]
- Turn = data[3] * 256 + data[2]
- delta_kWh = C * Turn
- temp_SdB = ConvertToSignedDHT((data[4] + data[5] * 256)/100.)
- humid_SdB = (data[6] + data[7] * 256)/100.
- temp_Grenier = ConvertToSignedDHT((data[8] + data[9] * 256)/100.)
- humid_Grenier = (data[10] + data[11] * 256)/100.
- WaterLiter = (data[12] + data[13] * 256)
- current_kWh = GetUservariableData(0) # Get value from uservariable 0 (current)
- print "Received data [elec]: ", W, " Watt ", Turn, " Turn ", delta_kWh, " delta kWh"
- print "Received data [SdB]: ", temp_SdB, "C ", humid_SdB, "%"
- print "Received data [Grenier]: ", temp_Grenier, "C ", humid_Grenier, "%"
- print "Received data [Water]: ", WaterLiter, "L "
- #### Plausibility checks
- ElecCounterLastUpdate = GetLastUpdateInSeconds(idx_dummy_counter_elec)
- if (delta_kWh*60/ElecCounterLastUpdate > 150) or (delta_kWh > 15000) or (ElecCounterLastUpdate < 15):
- LogToDomoticzWithFormat("La surveillance rapporte une erreur ! LastUpdate: " + str(ElecCounterLastUpdate) + "secondes, Energie: " + str(W) + " Watts, Consommation: +" + str(delta_kWh) + "Wh [" + str(current_kWh) + "]")
- exit()
- WaterCounterLastUpdate = GetLastUpdateInSeconds(idx_dummy_counter_water)
- if (WaterLiter*60/WaterCounterLastUpdate > 25) or (WaterLiter > 300) or (WaterCounterLastUpdate < 15):
- LogToDomoticzWithFormat("La surveillance rapporte une erreur ! LastUpdate: " + str(WaterCounterLastUpdate) + "secondes, " + str(WaterLiter) + " litre(s) non pris en compte")
- exit()
- #### Processing of power/energy in Domoticz
- print "Current: ", current_kWh, " delta: ", delta_kWh
- UpdateEnergyMeter(W, (current_kWh + delta_kWh))
- UpdateUservariable(0, (current_kWh + delta_kWh))
- if (delta_kWh > 0):
- LogToDomoticzWithFormat("Energie: " + str(W) + " Watts, Consommation: +" + str(delta_kWh) + "Wh [" + str(current_kWh) + "]")
- #### Processing of water in Domoticz
- UpdateWaterCounter(idx_dummy_counter_water, WaterLiter)
- if (WaterLiter > 0):
- LogToDomoticzWithFormat("Ajout de " + str(WaterLiter) + " litre(s) au compteur")
- #### Processing of temperature and humidity in Domoticz
- UpdateDHT(idx_sdbDHT, temp_SdB, humid_SdB)
- UpdateDHT(idx_grenierDHT, temp_Grenier, humid_Grenier)
- LogToDomoticzWithFormat("Salle de bain: " + str(temp_SdB) + "C / " + str(humid_SdB) + "% - Grenier: " + str(temp_Grenier) + "C / " + str(humid_Grenier) + "%")
- print "Counters Updated !"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement