diff --git a/custom_components/format_ble_tracker/__init__.py b/custom_components/format_ble_tracker/__init__.py index 19d8208..1825b53 100644 --- a/custom_components/format_ble_tracker/__init__.py +++ b/custom_components/format_ble_tracker/__init__.py @@ -4,6 +4,7 @@ import asyncio from curses import has_key import json +import time import logging from typing import Any @@ -23,6 +24,7 @@ ROOM, ROOT_TOPIC, RSSI, + TIMESTAMP, ) PLATFORMS: list[Platform] = [ @@ -38,6 +40,7 @@ vol.Schema( { vol.Required(RSSI): vol.Coerce(int), + vol.Optional(TIMESTAMP): vol.Coerce(int) }, extra=vol.ALLOW_EXTRA, ), @@ -95,7 +98,6 @@ def __init__(self, hass: HomeAssistant, data) -> None: async def _async_update_data(self) -> dict[str, Any]: """Update data via library.""" - _LOGGER.error("Room data: %s", str(self.room_data)) if len(self.room_data) == 0: self.room = None else: @@ -123,6 +125,13 @@ async def message_received(self, msg): except vol.MultipleInvalid as error: _LOGGER.debug("Skipping update because of malformatted data: %s", error) return + msg_time = data.get(TIMESTAMP) + if (msg_time is not None): + current_time = int(time.time()) + if (current_time - msg_time >= self.get_expiration_time()): + _LOGGER.info("Received message with old timestamp, skipping") + return + room_topic = msg.topic.split("/")[2] await self.schedule_data_expiration(room_topic) @@ -135,11 +144,15 @@ async def schedule_data_expiration(self, room): self.room_expiration_timers[room].cancel() loop = asyncio.get_event_loop() timer = loop.call_later( - (self.expiration_time if self.expiration_time else self.default_expiration_time) * 60, + self.get_expiration_time(), lambda: asyncio.ensure_future(self.expire_data(room)), ) self.room_expiration_timers[room] = timer + def get_expiration_time(self): + """Calculate current expiration delay""" + return getattr(self, "expiration_time", self.default_expiration_time) * 60 + async def expire_data(self, room): """Set data for certain room expired""" del self.room_data[room] diff --git a/custom_components/format_ble_tracker/const.py b/custom_components/format_ble_tracker/const.py index 6974394..8719245 100644 --- a/custom_components/format_ble_tracker/const.py +++ b/custom_components/format_ble_tracker/const.py @@ -12,3 +12,4 @@ ROOT_TOPIC = "format_ble_tracker" ALIVE_NODES_TOPIC = ROOT_TOPIC + "/alive" RSSI = "rssi" +TIMESTAMP = "timestamp"