Skip to content

Commit

Permalink
fix: account for time passing between updates (#419)
Browse files Browse the repository at this point in the history
  • Loading branch information
InTheDaylight14 authored Dec 27, 2022
1 parent b979846 commit 02751a2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
13 changes: 12 additions & 1 deletion custom_components/tesla_custom/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,8 @@ def __init__(
self._attr_device_class = SensorDeviceClass.TIMESTAMP
self._attr_icon = "mdi:timer-plus"
self._value: Optional[datetime] = None
self._last_known_value: Optional[int] = None
self._last_update_time: Optional[datetime] = None

@property
def native_value(self) -> Optional[datetime]:
Expand All @@ -529,8 +531,17 @@ def native_value(self) -> Optional[datetime]:
charge_hours = 0
else:
charge_hours = float(self._car.time_to_full_charge)

if self._last_known_value != charge_hours:
self._last_known_value = charge_hours
self._last_update_time = dt.utcnow()

if self._car.charging_state == "Charging" and charge_hours > 0:
new_value = dt.utcnow() + timedelta(hours=charge_hours)
new_value = (
dt.utcnow()
+ timedelta(hours=charge_hours)
- (dt.utcnow() - self._last_update_time)
)
if self._value is None or (new_value - self._value).total_seconds() >= 60:
self._value = new_value
if self._car.charging_state in ["Charging", "Complete"]:
Expand Down
9 changes: 9 additions & 0 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,15 @@ async def test_time_charge_complete_charging(
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.TIMESTAMP
assert state.attributes.get(ATTR_STATE_CLASS) is None

mock_timetravel = mock_now + timedelta(minutes=2)
monkeypatch.setattr(dt, "utcnow", lambda: mock_timetravel)

state = hass.states.get("sensor.my_model_s_time_charge_complete")
charge_complete = mock_now + timedelta(
hours=float(car_mock_data.VEHICLE_DATA["charge_state"]["time_to_full_charge"])
)
charge_complete_str = datetime.strftime(charge_complete, "%Y-%m-%dT%H:%M:%S+00:00")


async def test_time_charge_completed(hass: HomeAssistant) -> None:
"""Tests time charge complete is the correct value."""
Expand Down

0 comments on commit 02751a2

Please sign in to comment.