Skip to content

Commit 56ab6b2

Browse files
authored
Prevent sensor updates caused by fluctuating “last seen” timestamps in Xbox integration (home-assistant#156419)
1 parent d1dea85 commit 56ab6b2

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

homeassistant/components/xbox/coordinator.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from __future__ import annotations
44

55
from dataclasses import dataclass, field
6-
from datetime import timedelta
6+
from datetime import datetime, timedelta
77
from http import HTTPStatus
88
import logging
99

@@ -251,7 +251,7 @@ async def _async_update_data(self) -> XboxData:
251251
translation_key="request_exception",
252252
) from e
253253
title_data[person.xuid] = title.titles[0]
254-
254+
person.last_seen_date_time_utc = self.last_seen_timestamp(person)
255255
if (
256256
self.current_friends - (new_friends := set(presence_data))
257257
or not self.current_friends
@@ -261,6 +261,22 @@ async def _async_update_data(self) -> XboxData:
261261

262262
return XboxData(new_console_data, presence_data, title_data)
263263

264+
def last_seen_timestamp(self, person: Person) -> datetime | None:
265+
"""Returns the most recent of two timestamps."""
266+
267+
# The Xbox API constantly fluctuates the "last seen" timestamp between two close values,
268+
# causing unnecessary updates. We only accept the most recent one as valild to prevent this.
269+
if not (prev_data := self.data.presence.get(person.xuid)):
270+
return person.last_seen_date_time_utc
271+
272+
prev_dt = prev_data.last_seen_date_time_utc
273+
cur_dt = person.last_seen_date_time_utc
274+
275+
if prev_dt and cur_dt:
276+
return max(prev_dt, cur_dt)
277+
278+
return cur_dt
279+
264280
def remove_stale_devices(self, xuids: set[str]) -> None:
265281
"""Remove stale devices from registry."""
266282

0 commit comments

Comments
 (0)