44import asyncio
55from curses import has_key
66import json
7+ import time
78import logging
89from typing import Any
910
2324 ROOM ,
2425 ROOT_TOPIC ,
2526 RSSI ,
27+ TIMESTAMP ,
2628)
2729
2830PLATFORMS : list [Platform ] = [
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 ]
0 commit comments