Skip to content

Commit 0152fa0

Browse files
tr4nt0rfrenck
authored andcommitted
Prevent sensor updates caused by fluctuating “last seen” timestamps in Xbox integration (home-assistant#156419)
1 parent 37ebbe8 commit 0152fa0

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

@@ -237,7 +237,7 @@ async def _async_update_data(self) -> XboxData:
237237
translation_key="request_exception",
238238
) from e
239239
title_data[person.xuid] = title.titles[0]
240-
240+
person.last_seen_date_time_utc = self.last_seen_timestamp(person)
241241
if (
242242
self.current_friends - (new_friends := set(presence_data))
243243
or not self.current_friends
@@ -247,6 +247,22 @@ async def _async_update_data(self) -> XboxData:
247247

248248
return XboxData(new_console_data, presence_data, title_data)
249249

250+
def last_seen_timestamp(self, person: Person) -> datetime | None:
251+
"""Returns the most recent of two timestamps."""
252+
253+
# The Xbox API constantly fluctuates the "last seen" timestamp between two close values,
254+
# causing unnecessary updates. We only accept the most recent one as valild to prevent this.
255+
if not (prev_data := self.data.presence.get(person.xuid)):
256+
return person.last_seen_date_time_utc
257+
258+
prev_dt = prev_data.last_seen_date_time_utc
259+
cur_dt = person.last_seen_date_time_utc
260+
261+
if prev_dt and cur_dt:
262+
return max(prev_dt, cur_dt)
263+
264+
return cur_dt
265+
250266
def remove_stale_devices(self, xuids: set[str]) -> None:
251267
"""Remove stale devices from registry."""
252268

0 commit comments

Comments
 (0)