Skip to content

Commit

Permalink
probleme enedis ne donne pas le detail de la veille( HC/HP )
Browse files Browse the repository at this point in the history
gestion "-1" pour la card si pas de données
  • Loading branch information
saniho committed Dec 12, 2020
1 parent dd58f28 commit 980eddb
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 51 deletions.
59 changes: 33 additions & 26 deletions custom_components/apiEnedis/apiEnedis.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
class apiEnedis:
def __init__(self, token, PDL_ID, delai = 3600, heuresCreuses = None, \
heuresCreusesCost=0, heuresPleinesCost=0, log = None):
self._serverName = "https://enedisgateway.tech/api"
self._token = token
self._PDL_ID = PDL_ID
self._lastMonth = None
Expand All @@ -31,8 +32,7 @@ def __init__(self, token, PDL_ID, delai = 3600, heuresCreuses = None, \
self._heuresCreusesCost = heuresCreusesCost
self._heuresPleinesCost = heuresPleinesCost
self._contract = None #{'subscribed_power':"", 'offpeak_hours':""}
self._HC = 0
self._HP = 0
self._HC, self._HP = 0, 0
self._interval_length = 1
self._updateRealise = False
self._niemeAppel = 0
Expand All @@ -49,7 +49,7 @@ def __init__(self, token, PDL_ID, delai = 3600, heuresCreuses = None, \
pass

def myLog(self, message):
#self._log.info(message)
self._log.info(message)
#self._log.warning(message)
pass

Expand All @@ -67,15 +67,8 @@ def post_and_get_json(self, url, params=None, data=None, headers=None):
import logging
import json

proxies = {
'http': 'http://localhost:8500',
'https': 'http://localhost:8500',
}
session = requests.Session()
##session.proxies.update(proxies)
response = session.post(url, params=params, data=json.dumps(data), headers=headers)
#response = session.post(url, params=params, data=json.dumps(data), headers=headers, proxies=proxies,
# verify='../../../hoverfly/cert.pem')
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as error:
Expand All @@ -98,7 +91,7 @@ def getDataPeriod(self, deb, fin ):
'Authorization': self._token,
'Content-Type': "application/json",
}
dataAnswer = self.post_and_get_json("https://enedisgateway.tech/api", data=payload, headers=headers)
dataAnswer = self.post_and_get_json(self._serverName, data=payload, headers=headers)
self.setLastAnswsr( dataAnswer )
return dataAnswer

Expand All @@ -114,7 +107,7 @@ def getDataProductionPeriod(self, deb, fin ):
'Authorization': self._token,
'Content-Type': "application/json",
}
dataAnswer = self.post_and_get_json("https://enedisgateway.tech/api", data=payload, headers=headers)
dataAnswer = self.post_and_get_json(self._serverName, data=payload, headers=headers)
self.setLastAnswsr( dataAnswer )
return dataAnswer

Expand All @@ -129,7 +122,7 @@ def getDataPeriodCLC(self, deb, fin ):
'Authorization': self._token,
'Content-Type': "application/json",
}
dataAnswer = self.post_and_get_json("https://enedisgateway.tech/api", data=payload, headers=headers)
dataAnswer = self.post_and_get_json(self._serverName, data=payload, headers=headers)
self.setLastAnswsr( dataAnswer )
return dataAnswer

Expand All @@ -142,7 +135,7 @@ def getDataContract(self, ):
'Authorization': self._token,
'Content-Type': "application/json",
}
dataAnswer = self.post_and_get_json("https://enedisgateway.tech/api", data=payload, headers=headers)
dataAnswer = self.post_and_get_json(self._serverName, data=payload, headers=headers)
self.setLastAnswsr( dataAnswer )
return dataAnswer

Expand Down Expand Up @@ -188,6 +181,16 @@ def CallgetLast7DaysDetails(self):
end_date = (datetime.date.today()).strftime("%Y-%m-%d")
return self.getDataPeriodCLC( start_date, end_date)

def CallgetCurrentMonthDetails(self):
import datetime
today = datetime.date.today()
debCurrentMonth = today.strftime("%Y-%m-01")
cejour = (datetime.date.today()).strftime("%Y-%m-%d")
if (debCurrentMonth != cejour):
return self.getDataPeriodCLC(debCurrentMonth, cejour)
else:
return 0

def CallgetLastWeek(self):
import datetime
today = datetime.date.today()
Expand Down Expand Up @@ -389,8 +392,8 @@ def _getHCHPfromHour(self, heure):
return heurePleine

def createMultiDaysHCHP(self, data):
self._joursHC={}
self._joursHP={}
joursHC={}
joursHP={}
dateDuJour = (datetime.date.today()).strftime("%Y-%m-%d")
for x in data["meter_reading"]["interval_reading"]:
self._interval_length = x["interval_length"]
Expand All @@ -404,18 +407,19 @@ def createMultiDaysHCHP(self, data):
# pass
#else:
if(1):
if date not in self._joursHC:self._joursHC[date] = 0
if date not in self._joursHP:self._joursHP[date] = 0
if date not in joursHC:joursHC[date] = 0
if date not in joursHP:joursHP[date] = 0
heurePleine = self._getHCHPfromHour( heure )
if (heurePleine):
self._joursHP[date] += int(x["value"]) * self.getCoeffIntervalLength() # car c'est en heure
joursHP[date] += int(x["value"]) * self.getCoeffIntervalLength() # car c'est en heure
else:
self._joursHC[date] +=int(x["value"]) * self.getCoeffIntervalLength() # car c'est pas en heure
joursHC[date] +=int(x["value"]) * self.getCoeffIntervalLength() # car c'est pas en heure

# if ( date == "2020-12-06" ):
# print("ici", x["date"], heure, " ", heurePleine, ", ", x[ "value" ], \
# self._joursHP[date], self._joursHC[date], self._joursHP[date] + self._joursHC[date])

return joursHC, joursHP
#print(self._joursHC)
#print(self._joursHP)

Expand Down Expand Up @@ -533,7 +537,7 @@ def updateLast7DaysDetails(self, data=None):
self.myLog("updateLast7DaysDetails : data %s" %(data))
self.checkDataPeriod(data)
# construction d'un dico utile ;)
self.createMultiDaysHCHP(data)
self._joursHC, self._joursHP = self.createMultiDaysHCHP(data)

def getCurrentWeek(self):
return self._currentWeek
Expand All @@ -560,6 +564,7 @@ def updateCurrentMonth(self, data=None):
self._currentMonth = self.analyseValueAndAdd( data )
else:
self._currentMonth = data

def getLastYear(self):
return self._lastYear
def updateLastYear(self, data=None):
Expand Down Expand Up @@ -626,12 +631,12 @@ def update(self):
if (( self.getTimeLastCall() == None ) or
( self.getStatusLastCall() == False) or
( self.getDelaiIsGood() )):
self.updateErrorLastCall( "")
self.updateLastMethodCall("")
try:
self.setUpdateRealise( True )
self.myLogWarning( "myEnedis ...%s update lancé, status precedent : %s, lastCall :%s" \
% (self.get_PDL_ID(), self.getStatusLastCall(), self.getLastMethodCallError()))
self.updateErrorLastCall( "")
self.updateLastMethodCall("")
self.setUpdateRealise( True )
if ( self.isConsommation()):
self._niemeAppel += 1
if (self.getStatusLastCall() or self.getLastMethodCallError() == "updateYesterday"):
Expand Down Expand Up @@ -659,8 +664,8 @@ def update(self):
self.updateDataYesterdayHCHP()
except Exception as inst:
if ( inst.args[:3] == ('call', 'error', 'no_data_found')): # gestion que c'est pas une erreur de contrat trop recent ?
# si le service ne repond pas, l'erreur pas grave
self.updateErrorLastCall( "%s"%(self.getLastAnswer()))
# si le service ne repond pas, l'erreur pas grave, c'est que pas encore remonté
self.updateErrorLastCall( "%s"%("no yesterday data"))
pass
else:
raise Exception(inst)
Expand All @@ -687,6 +692,8 @@ def update(self):
elif ( self.isProduction()):
if (self.getStatusLastCall() or self.getLastMethodCallError() == "updateProductionYesterday"):
self.updateProductionYesterday()
self.updateTimeLastCall()
self.updateStatusLastCall(True)

except Exception as inst:
if ( inst.args == ("call", None)):
Expand Down
4 changes: 2 additions & 2 deletions custom_components/apiEnedis/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

ICON = "mdi:package-variant-closed"

__VERSION__ = "1.0.5.1"
__VERSION__ = "1.0.5.2"

SCAN_INTERVAL = timedelta(seconds=1800)# interrogation enedis ?
DEFAUT_DELAI_INTERVAL = 7200 # interrogation faite toutes 2 les heures
Expand Down Expand Up @@ -211,7 +211,7 @@ async def async_added_to_hass(self) -> None:
#_LOGGER.warning("*** kyes : %s " %(state.attributes.keys()))
# si seulement pas eut de mise à jour !!
# si la clef yesterday est disponible dans l'element courant, alors c'est que l'on a eut une mise à jour
if 'yesterday' not in self._attributes.keys(): # pas plutot la key à checker ??
if 'yesterday' not in self._attributes.keys() and 'yesterday_production' not in self._attributes.keys(): # pas plutot la key à checker ??
self._state = state.state
_LOGGER.warning("*** / / / \ \ \ *** mise a jour state precedent %s " % (self._state))
self._attributes = state.attributes
Expand Down
83 changes: 60 additions & 23 deletions custom_components/apiEnedis/sensorEnedis.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ def manageSensorState( _myDataEnedis,_LOGGER = None, version = None ):
# si pas de mises à jour alors juste return !!
return
if (_myDataEnedis.getStatusLastCall()): # update avec statut ok
#if( 1 ): #
try:
if( 1 ): #
#try:
status_counts["typeCompteur"] = _myDataEnedis.getTypePDL()
if ( _myDataEnedis.isConsommation()):
status_counts["lastSynchro"] = datetime.datetime.now()
Expand All @@ -28,67 +28,101 @@ def manageSensorState( _myDataEnedis,_LOGGER = None, version = None ):
last7daysHP = _myDataEnedis.get7DaysHP()
listeClef = list(last7daysHP.keys())
listeClef.reverse()

print(listeClef)
today = datetime.date.today()
listeClef = []
for i in range( 7 ):
maDate = today - datetime.timedelta( i + 1)
listeClef.append(maDate.strftime("%Y-%m-%d"))
print(listeClef)
niemejour = 0
for clef in listeClef:
niemejour += 1
status_counts['day_%s_HP' % (niemejour)] = last7daysHP[clef]
valeur= -1
if ( clef in last7daysHP.keys()):
valeur = last7daysHP[clef]
status_counts['day_%s_HP' % (niemejour)] = valeur
last7daysHC = _myDataEnedis.get7DaysHC()
listeClef = list(last7daysHP.keys())
listeClef.reverse()
#listeClef = list(last7daysHP.keys())
#listeClef.reverse()
niemejour = 0
for clef in listeClef:
# print(clef, " ", last7daysHC[clef])
niemejour += 1
status_counts['day_%s_HC' % (niemejour)] = last7daysHC[clef]
valeur= -1
if ( clef in last7daysHC.keys()):
valeur = last7daysHC[clef]
status_counts['day_%s_HC' % (niemejour)] = valeur
# gestion du cout par jour ....

niemejour = 0
cout = []
for clef in listeClef:
niemejour += 1
cout.append(0.001 * _myDataEnedis.getHCCost(last7daysHC[clef]) +
0.001 * _myDataEnedis.getHPCost(last7daysHP[clef]))
status_counts['dailyweek_cost'] = [("{:.2f}".format(day_cost)) for day_cost in cout]
valeur = -1
if ( clef in last7daysHC.keys() and clef in last7daysHP.keys()):
valeur = 0.001 * _myDataEnedis.getHCCost(last7daysHC[clef]) + \
0.001 * _myDataEnedis.getHPCost(last7daysHP[clef])
valeur = "{:.2f}".format(valeur)
cout.append(valeur)
status_counts['dailyweek_cost'] = cout
niemejour = 0
coutHC = []
for clef in listeClef:
niemejour += 1
coutHC.append(
0.001 * _myDataEnedis.getHCCost(last7daysHC[clef]))
status_counts['dailyweek_costHC'] = [("{:.2f}".format(day_cost)) for day_cost in coutHC]
valeur = -1
if ( clef in last7daysHC.keys()):
valeur = 0.001 * _myDataEnedis.getHCCost(last7daysHC[clef])
valeur = "{:.2f}".format(valeur)
coutHC.append(valeur)
status_counts['dailyweek_costHC'] = coutHC

niemejour = 0
dailyHC = []
for clef in listeClef:
niemejour += 1
dailyHC.append(last7daysHC[clef])
status_counts['dailyweek_HC'] = [("{:.3f}".format(0.001 * day_HC)) for day_HC in dailyHC]
valeur = -1
if ( clef in last7daysHC.keys()):
valeur = "{:.3f}".format(0.001 * last7daysHC[clef])
dailyHC.append(valeur)
status_counts['dailyweek_HC'] = dailyHC

status_counts['dailyweek'] = [(day) for day in listeClef]
niemejour = 0
coutHP = []
for clef in listeClef:
niemejour += 1
coutHP.append(
0.001 * _myDataEnedis.getHPCost(last7daysHP[clef]))
status_counts['dailyweek_costHP'] = [("{:.2f}".format(day_cost)) for day_cost in coutHP]
valeur = -1
if ( clef in last7daysHP.keys()):
valeur = 0.001 * _myDataEnedis.getHPCost(last7daysHP[clef])
valeur = "{:.2f}".format(valeur)
coutHP.append(valeur)
status_counts['dailyweek_costHP'] = coutHP
#gestion du format : "{:.2f}".format(a)

niemejour = 0
dailyHP = []
for clef in listeClef:
niemejour += 1
dailyHP.append(last7daysHP[clef])
status_counts['dailyweek_HP'] = [("{:.3f}".format(0.001 * day_HP)) for day_HP in dailyHP]
valeur = -1
if ( clef in last7daysHP.keys()):
valeur = last7daysHP[clef]
valeur = "{:.3f}".format(0.001 * valeur)
dailyHP.append(valeur)
status_counts['dailyweek_HP'] = dailyHP

niemejour = 0
daily = []
for clef in listeClef:
niemejour += 1
somme = last7daysHP[clef] + last7daysHC[clef]
somme = -1
if ( clef in last7daysHP.keys() and clef in last7daysHC.keys() ):
somme = last7daysHP[clef] + last7daysHC[clef]
somme = "{:.2f}".format(0.001 * somme)
status_counts['day_%s' %(niemejour)] = somme
daily.append(somme)
status_counts['daily'] = [("{:.2f}".format(0.001 * day)) for day in daily]
status_counts['daily'] = daily

status_counts["halfhourly"] = []
status_counts["offpeak_hours"] = _myDataEnedis.getYesterdayHC() * 0.001
Expand Down Expand Up @@ -128,12 +162,15 @@ def manageSensorState( _myDataEnedis,_LOGGER = None, version = None ):
elif( _myDataEnedis.isProduction()):
status_counts["yesterday_production"] = _myDataEnedis.getProductionYesterday()
status_counts['errorLastCall'] = _myDataEnedis.getErrorLastCall()
status_counts["lastSynchro"] = datetime.datetime.now()
status_counts["lastUpdate"] = _myDataEnedis.getLastUpdate()
status_counts["timeLastCall"] = _myDataEnedis.getTimeLastCall()


except:
"""except:
status_counts['errorLastCall'] = _myDataEnedis.getErrorLastCall()
_LOGGER.warning( "errorLastCall : %s " %( _myDataEnedis.getErrorLastCall() ))

"""
return status_counts

def logSensorState( status_counts ):
Expand Down
4 changes: 4 additions & 0 deletions custom_components/apiEnedis/testEnedis.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,22 @@ def testMulti():
mon_conteneur.read("../../../myCredential/security.txt")
#for qui in ["ENEDIS","ENEDIS2","ENEDIS3","ENEDIS4"]:
#for qui in ["ENEDIS","ENEDIS7"]:
#for qui in ["ENEDIS9"]:
for qui in ["ENEDIS"]:
token = mon_conteneur[qui]['TOKEN']
PDL_ID = mon_conteneur[qui]['CODE']
print(token, PDL_ID)
heureCreusesCh = "[['00:00','05:00'], ['22:00', '24:00']]"
myDataEnedis = apiEnedis.apiEnedis( token=token, PDL_ID=PDL_ID, delai=10, \
heuresCreuses=eval(heureCreusesCh), heuresCreusesCost=0.0797, heuresPleinesCost=0.1175 )
#myDataEnedis._serverName = "http://localhost:5500" # pour mockserver
#myDataEnedis._serverName = "http://localhost:5501" # pour record
myDataEnedis.updateContract()
myDataEnedis.updateHCHP()
#print(myDataEnedis.getContract())
#print(myDataEnedis.getTypePDL())
testComplet( myDataEnedis )
print( myDataEnedis.getLastMethodCallError())

def testMono():
import configparser
Expand Down

0 comments on commit 980eddb

Please sign in to comment.