Skip to content

Commit

Permalink
cache as fast as possible to prevent overflow
Browse files Browse the repository at this point in the history
  • Loading branch information
Tuen Lee committed Nov 18, 2023
1 parent 6a02624 commit e8d23af
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
15 changes: 12 additions & 3 deletions custom_components/polestar_api/polestar_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,10 @@ def get_cache_data(self, path, reponse_path=None):
path = path.replace('{vin}', self.vin)

if self.cache_data and self.cache_data[path]:
if self.cache_data[path]['timestamp'] > datetime.now() - timedelta(seconds=30):
if self.cache_data[path]['timestamp'] > datetime.now() - timedelta(seconds=15):
data = self.cache_data[path]['data']
if data is None:
return False
if reponse_path:
for key in reponse_path.split('.'):
data = data[key]
Expand All @@ -90,9 +92,18 @@ async def get_data(self, path, reponse_path=None):
path = path.replace('{vin}', self.vin)

cache_data = self.get_cache_data(path, reponse_path)
# if false, then we are fetching data just return
if cache_data is False:
return
if cache_data:
_LOGGER.debug("Using cached data")
return cache_data

# put as fast possible something in the cache otherwise we get a lot of requests
if not self.cache_data:
self.cache_data = {}
self.cache_data[path] = {'data': None, 'timestamp': datetime.now()}

url = 'https://api.volvocars.com/energy/v1/vehicles/' + path
headers = {
HEADER_AUTHORIZATION: f'{self.token_type} {self.access_token}',
Expand All @@ -116,8 +127,6 @@ async def get_data(self, path, reponse_path=None):
data = resp['data']

# add cache_data[path]
if not self.cache_data:
self.cache_data = {}
self.cache_data[path] = {'data': data, 'timestamp': datetime.now()}

if reponse_path:
Expand Down
5 changes: 3 additions & 2 deletions custom_components/polestar_api/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,5 +233,6 @@ def unit_of_measurement(self) -> str:
async def async_update(self):
"""Get the latest data and updates the states."""
data = await self._device.get_data(self.entity_description.path, self.entity_description.response_path)
self._attr_native_value = data
self.value = data
if data is not None:
self._attr_native_value = data
self.value = data

0 comments on commit e8d23af

Please sign in to comment.