async def async_update_data(): """Fetch data from API endpoint. This is the place to pre-process the data to lookup tables so entities can quickly look up their data. """ try: # Fetch srp_energy data start_date = datetime.now() + timedelta(days=-1) end_date = datetime.now() with async_timeout.timeout(10): hourly_usage = await opp.async_add_executor_job( api.usage, start_date, end_date, is_time_of_use, ) previous_daily_usage = 0.0 for _, _, _, kwh, _ in hourly_usage: previous_daily_usage += float(kwh) return previous_daily_usage except (TimeoutError) as timeout_err: raise UpdateFailed("Timeout communicating with API") from timeout_err except (ConnectError, HTTPError, Timeout, ValueError, TypeError) as err: raise UpdateFailed(f"Error communicating with API: {err}") from err
async def async_update(): """Get the latest data from the Notion API.""" data = {"bridges": {}, "sensors": {}, "tasks": {}} tasks = { "bridges": client.bridge.async_all(), "sensors": client.sensor.async_all(), "tasks": client.task.async_all(), } results = await asyncio.gather(*tasks.values(), return_exceptions=True) for attr, result in zip(tasks, results): if isinstance(result, NotionError): raise UpdateFailed( f"There was a Notion error while updating {attr}: {result}" ) if isinstance(result, Exception): raise UpdateFailed( f"There was an unknown error while updating {attr}: {result}" ) for item in result: if attr == "bridges" and item["id"] not in data["bridges"]: # If a new bridge is discovered, register it: opp.async_create_task( async_register_new_bridge(opp, item, entry)) data[attr][item["id"]] = item return data
async def async_update_data(): try: async with async_timeout.timeout(10): await hub.async_update_relays() except aiohttp.client_exceptions.ClientResponseError as err: raise UpdateFailed(f"Wrong credentials: {err}") from err except aiohttp.client_exceptions.ClientConnectorError as err: raise UpdateFailed(f"Error communicating with API: {err}") from err
async def async_safe_fetch(bridge, fetch_method): """Safely fetch data.""" try: with async_timeout.timeout(4): return await bridge.async_request_call(fetch_method) except aiohue.Unauthorized as err: await bridge.handle_unauthorized_error() raise UpdateFailed("Unauthorized") from err except aiohue.AiohueException as err: raise UpdateFailed(f"Hue error: {err}") from err
async def _async_update_data(self): """Update data via library.""" data = {} try: obs = await self.airnow.observations.latLong( self.latitude, self.longitude, distance=self.distance, ) except (AirNowError, ClientConnectorError) as error: raise UpdateFailed(error) from error if not obs: raise UpdateFailed("No data was returned from AirNow") max_aqi = 0 max_aqi_level = 0 max_aqi_desc = "" max_aqi_poll = "" for obv in obs: # Convert AQIs to Concentration pollutant = obv[ATTR_API_AQI_PARAM] concentration = aqi_to_concentration(obv[ATTR_API_AQI], pollutant) data[obv[ATTR_API_AQI_PARAM]] = concentration # Overall AQI is the max of all pollutant AQIs if obv[ATTR_API_AQI] > max_aqi: max_aqi = obv[ATTR_API_AQI] max_aqi_level = obv[ATTR_API_CATEGORY][ATTR_API_CAT_LEVEL] max_aqi_desc = obv[ATTR_API_CATEGORY][ATTR_API_CAT_DESCRIPTION] max_aqi_poll = pollutant # Copy other data from PM2.5 Value if obv[ATTR_API_AQI_PARAM] == ATTR_API_PM25: # Copy Report Details data[ATTR_API_REPORT_DATE] = obv[ATTR_API_REPORT_DATE] data[ATTR_API_REPORT_HOUR] = obv[ATTR_API_REPORT_HOUR] # Copy Station Details data[ATTR_API_STATE] = obv[ATTR_API_STATE] data[ATTR_API_STATION] = obv[ATTR_API_STATION] data[ATTR_API_STATION_LATITUDE] = obv[ ATTR_API_STATION_LATITUDE] data[ATTR_API_STATION_LONGITUDE] = obv[ ATTR_API_STATION_LONGITUDE] # Store Overall AQI data[ATTR_API_AQI] = max_aqi data[ATTR_API_AQI_LEVEL] = max_aqi_level data[ATTR_API_AQI_DESCRIPTION] = max_aqi_desc data[ATTR_API_POLLUTANT] = max_aqi_poll return data
async def async_update_data(self): """Update sensor data.""" try: with async_timeout.timeout(4): return await self.bridge.async_request_call( self.bridge.api.sensors.update) except Unauthorized as err: await self.bridge.handle_unauthorized_error() raise UpdateFailed("Unauthorized") from err except AiohueException as err: raise UpdateFailed(f"Hue error: {err}") from err
async def async_update_data(): """Fetch data from Nuki bridge.""" try: # Note: asyncio.TimeoutError and aiohttp.ClientError are already # handled by the data update coordinator. async with async_timeout.timeout(10): await opp.async_add_executor_job(_update_devices, locks + openers) except InvalidCredentialsException as err: raise UpdateFailed( f"Invalid credentials for Bridge: {err}") from err except RequestException as err: raise UpdateFailed( f"Error communicating with Bridge: {err}") from err
async def async_update(self): """Get updated data from SimpliSafe.""" async def async_update_system(system): """Update a system.""" await system.update(cached=system.version != 3) self._async_process_new_notifications(system) tasks = [ async_update_system(system) for system in self.systems.values() ] results = await asyncio.gather(*tasks, return_exceptions=True) for result in results: if isinstance(result, InvalidCredentialsError): if self._emergency_refresh_token_used: raise ConfigEntryAuthFailed( "Update failed with stored refresh token") LOGGER.warning( "SimpliSafe cloud error; trying stored refresh token") self._emergency_refresh_token_used = True try: await self._api.refresh_access_token( self.config_entry.data[CONF_TOKEN]) return except SimplipyError as err: raise UpdateFailed( # pylint: disable=raise-missing-from f"Error while using stored refresh token: {err}") if isinstance(result, EndpointUnavailable): # In case the user attempts an action not allowed in their current plan, # we merely log that message at INFO level (so the user is aware, # but not spammed with ERROR messages that they cannot change): LOGGER.info(result) if isinstance(result, SimplipyError): raise UpdateFailed( f"SimpliSafe error while updating: {result}") if self._api.refresh_token != self.config_entry.data[CONF_TOKEN]: _async_save_refresh_token(self._opp, self.config_entry, self._api.refresh_token) # If we've reached this point using an emergency refresh token, we're in the # clear and we can discard it: if self._emergency_refresh_token_used: self._emergency_refresh_token_used = False
async def async_update(self): """Fetch data from the device and update availability.""" try: data = await self.async_fetch_data() except (BroadlinkException, OSError) as err: if self.available and ( dt.utcnow() - self.last_update > self.SCAN_INTERVAL * 3 or isinstance(err, (AuthorizationError, OSError)) ): self.available = False _LOGGER.warning( "Disconnected from %s (%s at %s)", self.device.name, self.device.api.model, self.device.api.host[0], ) raise UpdateFailed(err) from err else: if self.available is False: _LOGGER.warning( "Connected to %s (%s at %s)", self.device.name, self.device.api.model, self.device.api.host[0], ) self.available = True self.last_update = dt.utcnow() return data
async def async_update_data_non_dimmer(): """Fetch data from Control4 director for non-dimmer lights.""" try: return await director_update_data(opp, entry, CONTROL4_NON_DIMMER_VAR) except C4Exception as err: raise UpdateFailed(f"Error communicating with API: {err}") from err
async def _async_update_data(self) -> DictToObj: """Update data via library.""" try: data = await self.brother.async_update() except (ConnectionError, SnmpError, UnsupportedModel) as error: raise UpdateFailed(error) from error return data
def update(self) -> None: """Update the data from the SolarEdge Monitoring API.""" try: data = self.api.get_details(self.site_id) details = data["details"] except KeyError as ex: raise UpdateFailed("Missing details data, skipping update") from ex self.data = None self.attributes = {} for key, value in details.items(): key = snakecase(key) if key in ["primary_module"]: for module_key, module_value in value.items(): self.attributes[snakecase(module_key)] = module_value elif key in [ "peak_power", "type", "name", "last_update_time", "installation_date", ]: self.attributes[key] = value elif key == "status": self.data = value LOGGER.debug("Updated SolarEdge details: %s, %s", self.data, self.attributes)
async def _async_update_data(self): try: with timeout(10): await self.data.update() except ClientConnectionError as err: raise UpdateFailed(err) from err return self.data
async def _async_update_data(self) -> Status: """Fetch data from Toon.""" try: return await self.toon.update() except ToonError as error: raise UpdateFailed( f"Invalid response from API: {error}") from error
async def _async_update_data(self): """Fetch the data from the NOAA Aurora Forecast.""" try: return await self.api.get_forecast_data(self.longitude, self.latitude) except ClientError as error: raise UpdateFailed(f"Error updating from NOAA: {error}") from error
async def async_update_data(): """Fetch data from shade endpoint.""" async with async_timeout.timeout(10): shade_entries = await shades.get_resources() if not shade_entries: raise UpdateFailed("Failed to fetch new shade data.") return _async_map_data_by_id(shade_entries[SHADE_DATA])
async def _async_update_data(self): """Fetch data from OmniLogic.""" try: data = await self.api.get_telemetry_data() except OmniLogicException as error: raise UpdateFailed( f"Error updating from OmniLogic: {error}") from error parsed_data = {} def get_item_data(item, item_kind, current_id, data): """Get data per kind of Omnilogic API item.""" if isinstance(item, list): for single_item in item: data = get_item_data(single_item, item_kind, current_id, data) if "systemId" in item: system_id = item["systemId"] current_id = current_id + (item_kind, system_id) data[current_id] = item for kind in ALL_ITEM_KINDS: if kind in item: data = get_item_data(item[kind], kind, current_id, data) return data parsed_data = get_item_data(data, "Backyard", (), parsed_data) return parsed_data
async def async_update_huisbaasje(huisbaasje): """Update the data by performing a request to Huisbaasje.""" try: # Note: asyncio.TimeoutError and aiohttp.ClientError are already # handled by the data update coordinator. async with async_timeout.timeout(FETCH_TIMEOUT): if not huisbaasje.is_authenticated(): _LOGGER.warning( "Huisbaasje is unauthenticated. Reauthenticating") await huisbaasje.authenticate() current_measurements = await huisbaasje.current_measurements() return { source_type: { SENSOR_TYPE_RATE: _get_measurement_rate(current_measurements, source_type), SENSOR_TYPE_THIS_DAY: _get_cumulative_value(current_measurements, source_type, SENSOR_TYPE_THIS_DAY), SENSOR_TYPE_THIS_WEEK: _get_cumulative_value(current_measurements, source_type, SENSOR_TYPE_THIS_WEEK), SENSOR_TYPE_THIS_MONTH: _get_cumulative_value(current_measurements, source_type, SENSOR_TYPE_THIS_MONTH), SENSOR_TYPE_THIS_YEAR: _get_cumulative_value(current_measurements, source_type, SENSOR_TYPE_THIS_YEAR), } for source_type in SOURCE_TYPES } except HuisbaasjeException as exception: raise UpdateFailed( f"Error communicating with API: {exception}") from exception
async def async_update_data(): try: return await myq.update_device_info() except InvalidCredentialsError as err: raise ConfigEntryAuthFailed from err except MyQError as err: raise UpdateFailed(str(err)) from err
async def async_coordinator_update_data_central() -> None: """Fetch all device and sensor data from api.""" try: await api.async_update() except Exception as err: raise UpdateFailed(f"Error communicating with API: {err}") from err return None
async def _async_update_data(self) -> bool: """Update data device by device.""" try: all_vacuums = await self.ayla_api.async_list_devices() self._online_dsns = { v["dsn"] for v in all_vacuums if v["connection_status"] == "Online" and v["dsn"] in self.shark_vacs } _LOGGER.debug("Updating sharkiq data") online_vacs = (self.shark_vacs[dsn] for dsn in self.online_dsns) await asyncio.gather(*[self._async_update_vacuum(v) for v in online_vacs]) except ( SharkIqAuthError, SharkIqNotAuthedError, SharkIqAuthExpiringError, ) as err: _LOGGER.debug("Bad auth state. Attempting re-auth", exc_info=err) raise ConfigEntryAuthFailed from err except Exception as err: _LOGGER.exception("Unexpected error updating SharkIQ") raise UpdateFailed(err) from err return True
async def async_update_data(): """Fetch data from API endpoint.""" try: await api.get_state() except exceptions.ConnectError as err: raise UpdateFailed( f"Failed to communicating with device {err}") from err
async def async_update_data(): """Update all stored entities for Wolf SmartSet.""" try: values = await wolf_client.fetch_value(gateway_id, device_id, parameters) return {v.value_id: v.value for v in values} except ConnectError as exception: raise UpdateFailed( f"Error communicating with API: {exception}") from exception except FetchFailed as exception: raise UpdateFailed( f"Could not fetch values from server due to: {exception}" ) from exception except InvalidAuth as exception: raise UpdateFailed( "Invalid authentication during update.") from exception
async def _async_update_data(self) -> dict: """Execute a "locked" API request against the valve controller.""" async with self._api_lock, self._client: try: resp = await self._api_coro() except GuardianError as err: raise UpdateFailed(err) from err return resp["data"]
async def _async_update_data(): """Update data via library.""" with async_timeout.timeout(20): try: await atag.update() except AtagException as err: raise UpdateFailed(err) from err return atag
async def async_update_data(): """Update data via API endpoint.""" try: async with async_timeout.timeout(DEFAULT_TIMEOUT): await api.full_update_device() return True except XMLDataMissingError as err: raise UpdateFailed("Smile update failed") from err
async def _async_update_data(self): """Update data via library.""" try: async with timeout(10): await asyncio.gather( *[self._update_device(), self._update_consumption_data()] ) except (RequestError) as error: raise UpdateFailed(error) from error
async def async_update_data(): """Get new data from the API.""" try: async with NodeSamba(config_entry.data[CONF_IP_ADDRESS], config_entry.data[CONF_PASSWORD]) as node: return await node.async_get_latest_measurements() except NodeProError as err: raise UpdateFailed( f"Error while retrieving data: {err}") from err
async def _async_update_data(self): data = {} with async_timeout.timeout(20): try: weather_response = await self._get_owm_weather() data = self._convert_weather_response(weather_response) except (APIRequestError, UnauthorizedError) as error: raise UpdateFailed(error) from error return data
async def _async_update_data(self): """Update the state of the device.""" try: await self.device.update_state() except DeviceNotBoundError as error: raise UpdateFailed(f"Device {self.name} is unavailable") from error except DeviceTimeoutError as error: self._error_count += 1 # Under normal conditions GREE units timeout every once in a while if self.last_update_success and self._error_count >= MAX_ERRORS: _LOGGER.warning( "Device is unavailable: %s (%s)", self.name, self.device.device_info, ) raise UpdateFailed( f"Device {self.name} is unavailable") from error