Skip to content

Commit

Permalink
Added MQTT message timestamp support
Browse files Browse the repository at this point in the history
  • Loading branch information
formatBCE committed Jul 25, 2022
1 parent c0883db commit d179e4d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
17 changes: 15 additions & 2 deletions custom_components/format_ble_tracker/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import asyncio
from curses import has_key
import json
import time
import logging
from typing import Any

Expand All @@ -23,6 +24,7 @@
ROOM,
ROOT_TOPIC,
RSSI,
TIMESTAMP,
)

PLATFORMS: list[Platform] = [
Expand All @@ -38,6 +40,7 @@
vol.Schema(
{
vol.Required(RSSI): vol.Coerce(int),
vol.Optional(TIMESTAMP): vol.Coerce(int)
},
extra=vol.ALLOW_EXTRA,
),
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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]
Expand Down
1 change: 1 addition & 0 deletions custom_components/format_ble_tracker/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@
ROOT_TOPIC = "format_ble_tracker"
ALIVE_NODES_TOPIC = ROOT_TOPIC + "/alive"
RSSI = "rssi"
TIMESTAMP = "timestamp"

0 comments on commit d179e4d

Please sign in to comment.