Skip to content

Commit

Permalink
premier test energy
Browse files Browse the repository at this point in the history
  • Loading branch information
saniho committed Dec 2, 2021
1 parent 8d6cba5 commit 1976072
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 4 deletions.
6 changes: 5 additions & 1 deletion custom_components/apiEnedis/const.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
""" Constants """
# attention updater aussi manifest.json
__VERSION__ = "1.3.1.14"
__VERSION__ = "1.3.2.0"
__name__ = "myEnedis"

try:
Expand Down Expand Up @@ -79,4 +79,8 @@ def __init__(self):
ENTITY_NAME: "yesterdayCost",
ENTITY_DELAI: 60,
},
"energy": {
ENTITY_NAME: "energy",
ENTITY_DELAI: 60,
},
}
2 changes: 1 addition & 1 deletion custom_components/apiEnedis/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"name": "myEnedis sensor",
"documentation": "https://github.com/saniho/apiEnedis/",
"config_flow": true,
"version": "1.3.1.14",
"version": "1.3.2.0",
"requirements": [
"packaging>=20.8"
],
Expand Down
2 changes: 1 addition & 1 deletion custom_components/apiEnedis/myContrat.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,6 @@ def _getHCHPfromHour(self, heure):
heurePleine = False
except:
pass
if (heureCreuse[0] < heure) and (heure <= heureCreuse[1]):
if (heureCreuse[0] <= heure) and (heure < heureCreuse[1]):
heurePleine = False
return heurePleine
141 changes: 141 additions & 0 deletions custom_components/apiEnedis/myEnedisSensorCoordinatorEnergy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""Sensor for my first"""
import datetime
import logging
from datetime import timedelta

try:
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from homeassistant.core import HomeAssistant
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import callback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import Throttle
from homeassistant.const import (
ATTR_ATTRIBUTION,
)

except ImportError:
# si py test
pass


from .const import (
DOMAIN,
__VERSION__,
__name__,
_consommation,
_production,
SENSOR_TYPES,
COORDINATOR_ENEDIS,
ENTITY_DELAI,
)
_LOGGER = logging.getLogger(__name__)
from .sensorEnedis import manageSensorState

ICON = "mdi:package-variant-closed"

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

def __init__(self, sensor_type, coordinator: DataUpdateCoordinator, typeSensor = _consommation):
"""Initialize the sensor."""
super().__init__(coordinator)
self._myDataSensorEnedis = manageSensorState()
self._myDataSensorEnedis.init(coordinator.clientEnedis, _LOGGER, __VERSION__ )
interval = sensor_type[ENTITY_DELAI]
self.update = Throttle(timedelta(seconds=interval))(self._update)
self._attributes = {}
self._state = None
self._unit = "kWh"
self._lastState = None
self._lastAttributes = None
self._typeSensor = typeSensor

@property
def unique_id(self):
"Return a unique_id for this entity."
if self._typeSensor == _production:
name = "myEnedis.energy.%s.production" %(self._myDataSensorEnedis.get_PDL_ID())
else:
name = "myEnedis.energy.%s" %(self._myDataSensorEnedis.get_PDL_ID())
return name

@property
def name(self):
"""Return the name of the sensor."""
if ( self._typeSensor == _production):
name = "myEnedis.energy.%s.production" %(self._myDataSensorEnedis.get_PDL_ID())
else:
name = "myEnedis.energy.%s" %(self._myDataSensorEnedis.get_PDL_ID())
return name

@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

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()
if state:
self._state = state.state

#TEST info
try:
if 'typeCompteur' in state.attributes:
self.attrs = state.attributes
_LOGGER.info("Redemarrage avec element present ??")
except:
_LOGGER.info("Redemarrage mais rien de present")
pass

@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: "",
"device_class": "energy",
"state_class": "total",
"unit_of_measurement": self._unit,
"last_reset": "2021-01-01T00:00:00", #à corriger plus tard !!
}
status_counts, state = self._myDataSensorEnedis.getStatusEnergy( self._typeSensor )
self._state = state

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."""
4 changes: 3 additions & 1 deletion custom_components/apiEnedis/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
from .myEnedisSensorCoordinator import myEnedisSensorCoordinator
from .myEnedisSensorCoordinatorHistory import myEnedisSensorCoordinatorHistory
from .myEnedisSensorYesterdayCostCoordinator import myEnedisSensorYesterdayCostCoordinator
from .myEnedisSensorCoordinatorEnergy import myEnedisSensorCoordinatorEnergy

async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
Expand All @@ -84,9 +85,10 @@ async def async_setup_entry(
entities.append(myEnedisSensorCoordinatorHistory(mysensor, coordinator_enedis, detail="HP"))
elif sensor_type == "yesterdayCost":
entities.append(myEnedisSensorYesterdayCostCoordinator(mysensor, coordinator_enedis))
elif sensor_type == "energy":
entities.append(myEnedisSensorCoordinatorEnergy(mysensor, coordinator_enedis))
else:
pass
#entities.append(MeteoFranceSensor(sensor_type, coordinator_enedis))

async_add_entities(
entities,
Expand Down
8 changes: 8 additions & 0 deletions custom_components/apiEnedis/sensorEnedis.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ def getExistsRecentVersion(self, versionCurrent, versionGit):
else:
return False

def getStatusEnergy(self, typeSensor = _consommation):
state = "unavailable"
status_counts = defaultdict(int)
if self._myDataEnedis.getTimeLastCall() != None:
state = "{:.3f}".format(self._myDataEnedis.getCurrentYear().getValue() * 0.001)

return status_counts, state

def getStatus(self, typeSensor = _consommation):
state = "unavailable"
status_counts = defaultdict(int)
Expand Down

0 comments on commit 1976072

Please sign in to comment.