From 02751a203a1d0dcfb6efd570cfb5246773f03e16 Mon Sep 17 00:00:00 2001 From: InTheDaylight14 <67400055+InTheDaylight14@users.noreply.github.com> Date: Mon, 26 Dec 2022 19:31:41 -0500 Subject: [PATCH] fix: account for time passing between updates (#419) --- custom_components/tesla_custom/sensor.py | 13 ++++++++++++- tests/test_sensor.py | 9 +++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/custom_components/tesla_custom/sensor.py b/custom_components/tesla_custom/sensor.py index 77fbca69..300d1936 100644 --- a/custom_components/tesla_custom/sensor.py +++ b/custom_components/tesla_custom/sensor.py @@ -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]: @@ -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"]: diff --git a/tests/test_sensor.py b/tests/test_sensor.py index 6a5f75d6..a86e8baa 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -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."""