Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Charge time remaining, account for time passing between updates #419

Merged
merged 3 commits into from
Dec 27, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Little out of my element here, I want to draw attention to this to make sure this works for testing. Trying to change the time 2 minutes in the future and make sure that the state has stayed the same.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not certain what the issue is. Is the test failing? I haven't mocked timestamps before so I'd just be reading the documentation like you are and reviewing the HA examples.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No the test is passing just fine. Maybe @carleeno can review the mock_timetravel. I based it off of their recent PR to shore up time tests. I just want to make sure that the state is actually being evaluated two minutes later by using that monkeypatch.setattr...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@InTheDaylight14 the mock looks correct, however you're not asserting anything afterwards so it's not actually testing anything.

Add an assert state.state == charge_complete_str at the end and see what happens, this will reveal if your logic is good.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for an explanation of what the monkeypatch is doing is it's replacing the homeassistant.util.dt.utcnow that HA uses with our mocked time. So when dt.utcnow is called from sensor.py it will actually get your mocked value.

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