Skip to content

Commit

Permalink
adds sensor yesterdaycost
Browse files Browse the repository at this point in the history
modification readme
  • Loading branch information
saniho committed Jan 1, 2021
1 parent 04dea7e commit 2493044
Show file tree
Hide file tree
Showing 6 changed files with 145 additions and 205 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ Ensuite vous aurez le sensor de disponible :
https://github.com/saniho/content-card-linky**


**************

N'hésitez pas à aller faire un tour sur ce forum ou vous trouverez pleins d'informations

https://forum.hacf.fr/t/hacs-ajoutez-des-modules-et-des-cartes-personnalisees/359

*************

_**VERSION**_

**1.1.0.0**
Expand Down
2 changes: 1 addition & 1 deletion custom_components/apiEnedis/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@
DEFAULT_SENSOR_INTERVAL = 60 # 60 secondes verifications du coordinator


__VERSION__ = "1.1.0.1"
__VERSION__ = "1.1.1.0alpha1"
26 changes: 17 additions & 9 deletions custom_components/apiEnedis/myEnedis.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,10 @@ def updateDataYesterdayHCHP(self, data=None):
self.myLog("--updateDataYesterdayHCHP --")
if (data == None): data = self.CallgetDataYesterdayHCHP()
self.myLog("updateDataYesterdayHCHP : data %s" % (data))
self.checkData(data)
self.createHCHP(data)
if ( self.checkData( data )):
self.checkData(data)
else:
return

def checkDataPeriod(self, dataAnswer ):
if ("enedis_return" in dataAnswer.keys()):
Expand All @@ -487,12 +489,14 @@ def checkDataPeriod(self, dataAnswer ):
return True

def checkData(self, dataAnswer ):
if ("error" in dataAnswer.keys()):
if ("enedis_return" in dataAnswer.keys()):
#if ( isinstance(dataAnswer['enedis_return'], str)):
# dataAnswer['enedis_return'] = json.loads(dataAnswer['enedis_return'])
if ( dataAnswer['enedis_return']["error"] == "ADAM-DC-0008" ):
#No consent can be found for this customer and this usage point
return False
elif ( dataAnswer['enedis_return']["error"] == "UNKERROR_002" ) :
return False
else:
raise Exception( 'call' , "error", dataAnswer["error"] )
return True
Expand Down Expand Up @@ -543,9 +547,11 @@ def updateLast7Days(self, data=None):
self.myLog("--updateLast7Days --")
if ( data == None ): data = self.CallgetLast7Days()
self.myLog("updateLast7Days : data %s" %(data))
self.checkDataPeriod(data)
# construction d'un dico utile ;)
self._last7Days = self.analyseValueAndMadeDico( data )
if ( self.checkDataPeriod(data) ):
# construction d'un dico utile ;)
self._last7Days = self.analyseValueAndMadeDico( data )
else:
return

def getLast7DaysDetails(self):
return self._last7DaysDetails
Expand All @@ -554,9 +560,11 @@ def updateLast7DaysDetails(self, data=None):
self.myLog("--updateLast7DaysDetails --")
if ( data == None ): data = self.CallgetLast7DaysDetails()
self.myLog("updateLast7DaysDetails : data %s" %(data))
self.checkDataPeriod(data)
# construction d'un dico utile ;)
self._joursHC, self._joursHP = self.createMultiDaysHCHP(data)
if ( self.checkDataPeriod(data) ):
# construction d'un dico utile ;)
self._joursHC, self._joursHP = self.createMultiDaysHCHP(data)
else:
return

def getCurrentWeek(self):
return self._currentWeek
Expand Down
103 changes: 96 additions & 7 deletions custom_components/apiEnedis/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ async def async_setup_entry(
entities = []
myEnedis_Cordinator = hass.data[DOMAIN]
entities.append(myEnedisSensorCoordinator(myEnedis_Cordinator))
entities.append(myEnedisSensorYesterdayCostCoordinator(myEnedis_Cordinator))
async_add_entities(entities)

class myEnedisSensorCoordinator(CoordinatorEntity, RestoreEntity):
Expand Down Expand Up @@ -191,19 +192,12 @@ def update():

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
#_LOGGER.warning("*** / / / \ \ \ *** mise a jour attributes precedent %s " %( self._attributes ))
#on sauvegarde les elements pour les reprendre si errot
self.setLastAttributes()
self.setLastState()

def _update_state(self):
"""Update sensors state."""
# si pas encore à jour, alors return tout court ....

#if self.coordinator.data:
# self._state = self.coordinator.data["ping"]
self._attributes = {ATTR_ATTRIBUTION: "" }
status_counts, state = self._myDataEnedis.myEnedis.getStatus()
self._attributes.update(status_counts)
Expand All @@ -223,6 +217,101 @@ def device_state_attributes(self):
def icon(self):
"""Icon to use in the frontend."""

class myEnedisSensorYesterdayCostCoordinator(CoordinatorEntity, RestoreEntity):
"""."""

def __init__(self, coordinator):
"""Initialize the sensor."""
super().__init__(coordinator)
self._myDataEnedis = coordinator
self._attributes = {}
self._state = None
self._unit = "€"
interval = timedelta(seconds=120)
self.update = Throttle(interval)(self._update)
self._lastState = None

"""
@property
def unique_id(self):
"Return a unique_id for this entity."
if self.forecast_day is not None:
return f"{self.coordinator.location_key}-{self.kind}-{self.forecast_day}".lower()
return f"{self.coordinator.location_key}-{self.kind}".lower()
"""

def setLastState(self):
self._lastState = self._state

@property
def name(self):
"""Return the name of the sensor."""
return "myEnedis.cost.yesterday.%s" %(self._myDataEnedis.myEnedis._myDataEnedis.get_PDL_ID())

@property
def state(self):
"""Return the state of the sensor."""
return self._state

@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit

@property
def device_state_attributes(self):
"""Return the state attributes."""
#if not self.coordinator.data:
# return None
self._attributes = {
ATTR_ATTRIBUTION: "",
}
return self._attributes

async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()

@callback
def update():
"""Update state."""
self._update_state()
self.async_write_ha_state()

self.async_on_remove(self.coordinator.async_add_listener(update))
self._update_state()
if not state:
return

def _update_state(self):
"""Update sensors state."""
self._attributes = {ATTR_ATTRIBUTION: "" }
status_counts, state = self._myDataEnedis.myEnedis.getStatusYesterdayCost()
if ( state != "unavailable"):
if ( state != self._state ):
self._attributes.update(status_counts)
self._state = state
else:
# donnée identique au jour precedent ....# vior faire autrement avec la date ?
return
else:
# donnée non disponible
return

def _update(self):
"""Update device state."""
self._attributes = {ATTR_ATTRIBUTION: ""}
self._state = "unavailable"

@property
def device_state_attributes(self):
"""Return the state attributes."""
return self._attributes

@property
def icon(self):
"""Icon to use in the frontend."""


class myEnedisSensor(RestoreEntity):
Expand Down
Loading

0 comments on commit 2493044

Please sign in to comment.