Skip to content

Commit

Permalink
Use shorthand attribute in derivative sensor (home-assistant#128610)
Browse files Browse the repository at this point in the history
  • Loading branch information
gjohansson-ST authored Oct 18, 2024
1 parent 1abc953 commit 6ff2ce1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 15 deletions.
21 changes: 7 additions & 14 deletions homeassistant/components/derivative/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from datetime import datetime, timedelta
from decimal import Decimal, DecimalException
import logging
from typing import TYPE_CHECKING

import voluptuous as vol

Expand Down Expand Up @@ -162,7 +161,7 @@ def __init__(
self._attr_device_info = device_info
self._sensor_source_id = source_entity
self._round_digits = round_digits
self._state: float | int | Decimal = 0
self._attr_native_value = round(Decimal(0), round_digits)
# List of tuples with (timestamp_start, timestamp_end, derivative)
self._state_list: list[tuple[datetime, datetime, Decimal]] = []

Expand Down Expand Up @@ -190,7 +189,10 @@ async def async_added_to_hass(self) -> None:
restored_data.native_unit_of_measurement
)
try:
self._state = Decimal(restored_data.native_value) # type: ignore[arg-type]
self._attr_native_value = round(
Decimal(restored_data.native_value), # type: ignore[arg-type]
self._round_digits,
)
except SyntaxError as err:
_LOGGER.warning("Could not restore last state: %s", err)

Expand Down Expand Up @@ -270,24 +272,15 @@ def calculate_weight(
if elapsed_time > self._time_window:
derivative = new_derivative
else:
derivative = Decimal(0)
derivative = Decimal(0.00)
for start, end, value in self._state_list:
weight = calculate_weight(start, end, new_state.last_updated)
derivative = derivative + (value * Decimal(weight))

self._state = derivative
self._attr_native_value = round(derivative, self._round_digits)
self.async_write_ha_state()

self.async_on_remove(
async_track_state_change_event(
self.hass, self._sensor_source_id, calc_derivative
)
)

@property
def native_value(self) -> float | int | Decimal:
"""Return the state of the sensor."""
value = round(self._state, self._round_digits)
if TYPE_CHECKING:
assert isinstance(value, (float, int, Decimal))
return value
2 changes: 1 addition & 1 deletion tests/components/derivative/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async def test_setup_and_remove_config_entry(

# Check the platform is setup correctly
state = hass.states.get(derivative_entity_id)
assert state.state == "0"
assert state.state == "0.0"
assert "unit_of_measurement" not in state.attributes
assert state.attributes["source"] == "sensor.input"

Expand Down

0 comments on commit 6ff2ce1

Please sign in to comment.