Skip to content

Commit

Permalink
Se comprueban posibles datos erróneos y se resetea el balance aunque …
Browse files Browse the repository at this point in the history
…no lleguen datos
  • Loading branch information
MiguelAngelLV committed Jun 17, 2023
1 parent 8dbb1cd commit c83d370
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions custom_components/balance_neto/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
native_unit_of_measurement="kWh",
device_class=DEVICE_CLASS_ENERGY,
state_class=STATE_CLASS_TOTAL_INCREASING,
suggested_display_precision=2
)

IMPORT_DESCRIPTION = SensorEntityDescription(
Expand All @@ -38,13 +39,15 @@
device_class=DEVICE_CLASS_ENERGY,
native_unit_of_measurement="kWh",
state_class=STATE_CLASS_TOTAL_INCREASING,
suggested_display_precision=2
)

BALANCE_DESCRIPTION = SensorEntityDescription(
key="balance_neto",
icon="mdi:scale-balance",
name="Balance Neto",
native_unit_of_measurement="kWh",
suggested_display_precision=2
)


Expand Down Expand Up @@ -96,7 +99,6 @@ async def async_added_to_hass(self):
if (last_sensor_data := await self.async_get_last_state()) is not None:
self._state = float(last_sensor_data.state)


@property
def extra_state_attributes(self):
return {
Expand Down Expand Up @@ -167,11 +169,11 @@ def extra_state_attributes(self):
}

def _update_value(self):
self._state = round((self._export - self._export_offset) - (self._import - self._import_offset), 2)
self._state = (self._export - self._export_offset) - (self._import - self._import_offset)
self.async_write_ha_state()

def update_import(self, state: State | None):
if state is None:
if not self._is_value_valid(state):
return

value = float(state.state)
Expand All @@ -188,7 +190,7 @@ def update_import(self, state: State | None):
self._update_value()

def update_export(self, state: State | None):
if state is None or state.state == 0:
if not self._is_value_valid(state):
return

value = float(state.state)
Expand All @@ -204,7 +206,6 @@ def update_export(self, state: State | None):
self._update_value()

def update_totals(self):

value = float(self._state)
self._last_reset = (datetime.utcnow() + timedelta(hours=1)).strftime("%Y-%m-%d %H:00:00")
self._import_offset = self._import
Expand All @@ -214,7 +215,16 @@ def update_totals(self):
else:
self._import_sensor.update_value(-value)

self._update_value()

def _reset(self):
self._import_offset = 0
self._export_offset = 0

@staticmethod
def _is_value_valid(state):
try:
value = float(state.state)
return value > 0
except ValueError:
return False

0 comments on commit c83d370

Please sign in to comment.