Skip to content

Commit

Permalink
Merge pull request #239 from saniho/AddTempo
Browse files Browse the repository at this point in the history
Add tempo + correction ecowatt
  • Loading branch information
saniho authored Sep 9, 2024
2 parents 3394425 + bee6a4a commit 577d4be
Show file tree
Hide file tree
Showing 13 changed files with 371 additions and 7 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/lint_python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ jobs:
- run: pytest . || true
#- run: pytest --doctest-modules . || true
#- run: shopt -s globstar && pyupgrade --py36-plus **/*.py || true
- run: safety check -i 43975
- run: safety check -i 43975 -i 70612
3 changes: 3 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions custom_components/apiEnedis/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ def __init__(self):
ENTITY_NAME: "ecowatt",
ENTITY_DELAI: 60,
},
"tempo": {
ENTITY_NAME: "tempo",
ENTITY_DELAI: 60,
},
}


Expand Down
2 changes: 1 addition & 1 deletion custom_components/apiEnedis/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"issue_tracker": "https://github.com/saniho/apiEnedis/issues",
"iot_class": "cloud_polling",
"config_flow": true,
"version": "2.3.1",
"version": "2.4.0",
"requirements": [
"packaging>=20.8"
],
Expand Down
26 changes: 25 additions & 1 deletion custom_components/apiEnedis/myCall.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def isAvailable() -> bool:
timestamp = datetime.datetime.now().timestamp()
_LOGGER.debug(
f"Ancien timeout? {timestamp}-{myCall._lastTimeout}"
f"={timestamp-myCall._lastTimeout}"
f"={timestamp - myCall._lastTimeout}"
f"> {MAX_PREVIOUS_TIMEOUT} ?"
)
if timestamp - myCall._lastTimeout > MAX_PREVIOUS_TIMEOUT:
Expand Down Expand Up @@ -163,6 +163,10 @@ def getUrl(self, serviceEnedis, data):
url = url + "/" + data["type"] + "/" + \
data["start"] + "/" + \
data["end"] + "/"
elif data["type"] == "rte/tempo":
url = url + "/" + data["type"] + "/" + \
data["start"] + "/" + \
data["end"] + "/"
return "get", url
# return "get", url + "cache"
elif self.isEnedisGateway(serviceEnedis):
Expand Down Expand Up @@ -368,6 +372,26 @@ def getDataEcoWatt(self, deb, fin):
self.setLastAnswer(dataAnswer)
return dataAnswer, callDone

def getDataTempo(self, deb, fin):
if fin is not None:
payload = {
"type": "rte/tempo",
"usage_point_id": self._PDL_ID,
"start": str(deb),
"end": str(fin),
}
headers = self.getDefaultHeader()
dataAnswer = self.post_and_get_json(
self.getServiceEnedis(), data=payload, headers=headers
)
callDone = True
else:
# pas de donnée
callDone = False
dataAnswer = ""
self.setLastAnswer(dataAnswer)
return dataAnswer, callDone

def getDataPeriodCLC(self, deb, fin):
if fin is not None:
payload = {
Expand Down
35 changes: 35 additions & 0 deletions custom_components/apiEnedis/myCheckData.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,25 @@ def analyseValueEcoWatt(self, data):
else:
from datetime import datetime
for date in data.keys():
# si pas de données
if "detail" in data.keys():
return listeEcoWattDate
for detailDate in data[date]["detail"]:
detailDatekey = datetime.strptime(detailDate, "%Y-%m-%d %H:%M:%S")
listeEcoWattDate[detailDatekey] = data[date]["detail"][detailDate]
return listeEcoWattDate

def analyseValueTempo(self, data):
listeEcoWattDate = {}
if data is None: # pas de valeur
return None
else:
from datetime import datetime
for date in data.keys():
detailDatekey = datetime.strptime(date, "%Y-%m-%d")
listeEcoWattDate[detailDatekey] = data[date]
return listeEcoWattDate

def checkData(self, dataAnswer):
# new version de la réponse
# si erreur 500
Expand Down Expand Up @@ -141,3 +155,24 @@ def checkDataEcoWatt(self, dataAnswer):
else:
raise Exception("call", "error", dataAnswer[API.ERROR_CODE])
return True

def checkDataTempo(self, dataAnswer):
if dataAnswer.get(API.ERROR_CODE, 200) == 500:
return False
if API.ERROR_CODE in dataAnswer.keys():
if (
(dataAnswer[API.ERROR_CODE] == "ADAM-ERR0123")
or (dataAnswer[API.ERROR_CODE] == "no_data_found")
or (dataAnswer[API.ERROR_CODE] == "ADAM-ERR0069")
or (dataAnswer[API.ERROR_CODE] == "UNKERROR_002")
):
return False
# collecte horaire non activée
if dataAnswer[API.ERROR_CODE] == "ADAM-ERR0075":
return False
if dataAnswer[API.ERROR_CODE] == "Internal Server error":
# erreur interne enedis
raise Exception("call", "error", "UNKERROR_001")
else:
raise Exception("call", "error", dataAnswer[API.ERROR_CODE])
return True
40 changes: 40 additions & 0 deletions custom_components/apiEnedis/myClientEnedis.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from .myDataEnedisMaxPower import myDataEnedisMaxPower
from .myDataEnedisProduction import myDataEnedisProduction
from .myDataEnedisEcoWatt import myDataEnedisEcoWatt
from .myDataEnedisTempo import myDataEnedisTempo

log = logging.getLogger(__nameMyEnedis__)

Expand Down Expand Up @@ -137,6 +138,10 @@ def __init__(
self._myCalli, self._token, self._version, self.contract
)

self._tempo = myDataEnedisTempo(
self._myCalli, self._token, self._version, self.contract
)

log.info("run myEnedis")
self._gitVersion: str | None = None
self._dataJsonDefault: dict[str, Any] = {}
Expand Down Expand Up @@ -779,6 +784,29 @@ def updateEcoWatt(self, data=None, withControl=True):
self.setDataRequestJson(clefFunction, self._ecoWatt)
self.setNbCall(self._ecoWatt.getNbCall())

def updateTempo(self, data=None, withControl=True):
clefFunction = "updateTempo"
self.lastMethodCall = clefFunction
requestJson = self.getDataRequestJson(clefFunction)
if data is None:
data = self.getDataJsonValue(clefFunction)
hier = (datetime.date.today() - datetime.timedelta(1)).strftime(_formatDateYmd)
demain = (datetime.date.today() + datetime.timedelta(1)).strftime(_formatDateYmd)
deb = self.contract.minCompareDateContract(hier)
fin = self.contract.maxCompareDateContract(demain)
data = self._tempo.updateData(
clefFunction,
self.getHorairePossible(),
data,
deb,
fin,
withControl=withControl,
dataControl=requestJson,
)
self.setDataJsonValue(clefFunction, data)
self.setDataRequestJson(clefFunction, self._tempo)
self.setNbCall(self._tempo.getNbCall())

def updateYesterdayConsumptionMaxPower(self, data=None, withControl=True):
clefFunction = "updateYesterdayConsumptionMaxPower"
self.lastMethodCall = clefFunction
Expand Down Expand Up @@ -866,6 +894,9 @@ def getCurrentYear(self):
def getEcoWatt(self):
return self._ecoWatt

def getTempo(self):
return self._tempo

def getLastUpdate(self):
return self._lastUpdate

Expand Down Expand Up @@ -1162,6 +1193,14 @@ def callEcoWatt(self):
self.updateStatusLastCall(True)
log.info("mise à jour effectuee EcoWatt")

def callTempo(self):
if ((self.getStatusLastCall() or self.lastMethodCallError == "updateTempo")
and (self.getServiceEnedis() == _ENEDIS_MyElectricData)):
self.updateTempo()
self.updateTimeLastCall()
self.updateStatusLastCall(True)
log.info("mise à jour effectuee Tempo")

def update(self): # noqa C901
log.info(f"myEnedis ...new update ?? {self._PDL_ID}")
if self.contract.isLoaded:
Expand Down Expand Up @@ -1191,6 +1230,7 @@ def update(self): # noqa C901
self.callConsommation()
self.callProduction()
self.callEcoWatt()
self.callTempo()
if self._forceCallJson:
self._forceCallJson = False
self.setDataJsonDefault({})
Expand Down
102 changes: 102 additions & 0 deletions custom_components/apiEnedis/myDataEnedisTempo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
try:
from .const import ( # isort:skip
__nameMyEnedis__,
)

except ImportError:
from const import ( # type: ignore[no-redef]
__nameMyEnedis__,
)

import logging

from .myCheckData import myCheckData
from .myDataControl import getInformationDataControl, okDataControl

log = logging.getLogger(__nameMyEnedis__)


class myDataEnedisTempo:
def __init__(self, myCalli, token, version, contrat):
self.myCalli = myCalli
self._value = {}
self._date = None
self._contrat = contrat
self._token, self._version = token, version
self._dateDeb = None
self._dateFin = None
self._callOk = None
self._nbCall = 0
self._data = None

def CallgetData(self, dateDeb, dateFin):
val1, val2 = self.myCalli.getDataTempo(dateDeb, dateFin)
return val1, val2

def getValue(self):
return self._value

def getDateFin(self):
return self._dateFin

def getDateDeb(self):
return self._dateDeb

def getCallOk(self):
return self._callOk

def getNbCall(self):
return self._nbCall

def updateData(
self,
clefFunction,
horairePossible=True,
data=None,
dateDeb=None,
dateFin=None,
withControl=False,
dataControl=None,
):
self._nbCall = 0
onLance = True
if withControl:
if okDataControl(clefFunction, dataControl, dateDeb, dateFin):
onLance = True
self._callOk = True
else:
if not horairePossible:
onLance = True
dateDeb, dateFin, self._callOk = getInformationDataControl(
dataControl
)
if self._callOk is None:
data = (
None # si on doit mettre à jour .... sauf si on est pas la
)
else:
self._callOk = None
data = None # si on doit mettre à jour .... sauf si on est pas la
if onLance:
self._dateDeb = dateDeb
self._dateFin = dateFin
log.info(f"--updateData {clefFunction} ( du {dateDeb} au {dateFin} )--")
self._data = data
if self._data is None:
self._data, callDone = self.CallgetData(dateDeb, dateFin)
self._nbCall = 1
else:
callDone = True
log.info("updateData : data %s", self._data)
if (callDone) and (myCheckData().checkDataTempo(self._data)):
self._value = myCheckData().analyseValueTempo(self._data)
self._callOk = True
else:
self._value = 0
self._callOk = callDone
log.info(f"with update !! {clefFunction} ( du {dateDeb} au {dateFin} )--")
log.info("updateData : data %s", (self._data))
else:
log.info(f"noupdate !! {clefFunction} ( du {dateDeb} au {dateFin} )--")
log.info("no updateData : data %s", (self._data))
return self._data
Loading

0 comments on commit 577d4be

Please sign in to comment.