Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit d179e4d

Browse files
committed
Added MQTT message timestamp support
1 parent c0883db commit d179e4d

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

custom_components/format_ble_tracker/__init__.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import asyncio
55
from curses import has_key
66
import json
7+
import time
78
import logging
89
from typing import Any
910

@@ -23,6 +24,7 @@
2324
ROOM,
2425
ROOT_TOPIC,
2526
RSSI,
27+
TIMESTAMP,
2628
)
2729

2830
PLATFORMS: list[Platform] = [
@@ -38,6 +40,7 @@
3840
vol.Schema(
3941
{
4042
vol.Required(RSSI): vol.Coerce(int),
43+
vol.Optional(TIMESTAMP): vol.Coerce(int)
4144
},
4245
extra=vol.ALLOW_EXTRA,
4346
),
@@ -95,7 +98,6 @@ def __init__(self, hass: HomeAssistant, data) -> None:
9598

9699
async def _async_update_data(self) -> dict[str, Any]:
97100
"""Update data via library."""
98-
_LOGGER.error("Room data: %s", str(self.room_data))
99101
if len(self.room_data) == 0:
100102
self.room = None
101103
else:
@@ -123,6 +125,13 @@ async def message_received(self, msg):
123125
except vol.MultipleInvalid as error:
124126
_LOGGER.debug("Skipping update because of malformatted data: %s", error)
125127
return
128+
msg_time = data.get(TIMESTAMP)
129+
if (msg_time is not None):
130+
current_time = int(time.time())
131+
if (current_time - msg_time >= self.get_expiration_time()):
132+
_LOGGER.info("Received message with old timestamp, skipping")
133+
return
134+
126135
room_topic = msg.topic.split("/")[2]
127136

128137
await self.schedule_data_expiration(room_topic)
@@ -135,11 +144,15 @@ async def schedule_data_expiration(self, room):
135144
self.room_expiration_timers[room].cancel()
136145
loop = asyncio.get_event_loop()
137146
timer = loop.call_later(
138-
(self.expiration_time if self.expiration_time else self.default_expiration_time) * 60,
147+
self.get_expiration_time(),
139148
lambda: asyncio.ensure_future(self.expire_data(room)),
140149
)
141150
self.room_expiration_timers[room] = timer
142151

152+
def get_expiration_time(self):
153+
"""Calculate current expiration delay"""
154+
return getattr(self, "expiration_time", self.default_expiration_time) * 60
155+
143156
async def expire_data(self, room):
144157
"""Set data for certain room expired"""
145158
del self.room_data[room]

custom_components/format_ble_tracker/const.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@
1212
ROOT_TOPIC = "format_ble_tracker"
1313
ALIVE_NODES_TOPIC = ROOT_TOPIC + "/alive"
1414
RSSI = "rssi"
15+
TIMESTAMP = "timestamp"

0 commit comments

Comments
 (0)