diff --git a/custom_components/polestar_api/polestar_api.py b/custom_components/polestar_api/polestar_api.py index cc3b120..6f795a8 100644 --- a/custom_components/polestar_api/polestar_api.py +++ b/custom_components/polestar_api/polestar_api.py @@ -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] @@ -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}', @@ -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: diff --git a/custom_components/polestar_api/sensor.py b/custom_components/polestar_api/sensor.py index a69e2e0..bc5395b 100644 --- a/custom_components/polestar_api/sensor.py +++ b/custom_components/polestar_api/sensor.py @@ -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