Ejemplo n.º 1
0
 async def async_update_data():
     try:
         return await api.async_info()
     except Exception as exception:
         raise UpdateFailed(f"Error communicating with API: {exception}"
                            ) from exception
Ejemplo n.º 2
0
    async def _async_update_data(self):
        """Fetch data from Google Wifi API."""

        try:
            system_data = await self.api.get_systems()

            for system_id, system in system_data.items():
                connected_count = 0
                guest_connected_count = 0
                main_network = system["groupSettings"]["lanSettings"].get(
                    "dhcpPoolBegin", " " * 10
                )
                main_network = ".".join(main_network.split(".", 3)[:3])

                for device_id, device in system["devices"].items():
                    device_network = device.get("ipAddress", " " * 10)
                    device_network = ".".join(device_network.split(".", 3)[:3])

                    if device_id not in self.devicelist:
                        to_add = {
                            "system_id": system_id,
                            "device_id": device_id,
                            "device": device,
                        }
                        async_dispatcher_send(self.hass, SIGNAL_ADD_DEVICE, to_add)
                        self.devicelist.append(device_id)

                    if device.get("connected") and main_network == device_network:
                        connected_count += 1
                        device["network"] = "main"
                    elif (
                        device.get("connected")
                        and device.get("unfilteredFriendlyType") != "Nest Wifi point"
                    ):
                        guest_connected_count += 1
                        device["network"] = "guest"
                    elif device.get("unfilteredFriendlyType") == "Nest Wifi point":
                        connected_count += 1
                        device["network"] = "main"

                for known_device in self.devicelist:
                    if known_device not in system["devices"]:
                        async_dispatcher_send(
                            self.hass, SIGNAL_DELETE_DEVICE, known_device
                        )
                        self.devicelist.remove(known_device)

            system_data[system_id]["connected_devices"] = connected_count
            system_data[system_id]["guest_devices"] = guest_connected_count
            system_data[system_id]["total_devices"] = (
                connected_count + guest_connected_count
            )

            if (
                time.time()
                > (self._last_speedtest + (60 * 60 * self.speedtest_interval))
                and self.auto_speedtest == True
                and self.hass.state == CoreState.running
            ):
                for system_id, system in system_data.items():
                    speedtest_result = await self.api.run_speed_test(
                        system_id=system_id
                    )
                    system_data[system_id]["speedtest"] = speedtest_result

                self._last_speedtest = time.time()
            elif self._force_speed_update:
                speedtest_result = await self.api.run_speed_test(system_id=system_id)
                system_data[system_id]["speedtest"] = speedtest_result
                self._force_speed_update = None

            return system_data
        except GoogleWifiException as error:
            session = aiohttp_client.async_create_clientsession(self.hass)
            self.api = GoogleWifi(refresh_token=self.refresh_token, session=session)
        except GoogleHomeIgnoreDevice as error:
            raise UpdateFailed(f"Error connecting to GoogleWifi: {error}") from error
        except ConnectionError as error:
            raise PlatformNotReady(
                f"Error connecting to GoogleWifi: {error}"
            ) from error
        except ValueError as error:
            raise ConfigEntryNotReady(
                f"Invalid data from GoogleWifi: {error}"
            ) from error
Ejemplo n.º 3
0
 async def _async_update_data(self):
     """Update data via library."""
     try:
         return await self.api.async_get_data()
     except Exception as exception:
         raise UpdateFailed() from exception
Ejemplo n.º 4
0
    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:
                    matching_flows = [
                        flow for flow in
                        self._hass.config_entries.flow.async_progress()
                        if flow["context"].get("source") == SOURCE_REAUTH
                        and flow["context"].get(
                            "unique_id") == self.config_entry.unique_id
                    ]

                    if not matching_flows:
                        self._hass.async_create_task(
                            self._hass.config_entries.flow.async_init(
                                DOMAIN,
                                context={
                                    "source": SOURCE_REAUTH,
                                    "unique_id": self.config_entry.unique_id,
                                },
                                data=self.config_entry.data,
                            ))

                    raise UpdateFailed(
                        "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._hass, 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
Ejemplo n.º 5
0
 async def _async_update_data(self) -> IPPPrinter:
     """Fetch data from IPP."""
     try:
         return await self.ipp.printer()
     except IPPError as error:
         raise UpdateFailed(f"Invalid response from API: {error}") from error
Ejemplo n.º 6
0
 async def async_update_data():
     """Fetch data from API endpoint."""
     try:
         return await tankerkoenig.fetch_data()
     except LookupError:
         raise UpdateFailed("Failed to fetch data")
Ejemplo n.º 7
0
 async def init_data(self):
     """Initialize the UpdateCoordinator object"""
     try:
         await self._device.init_data()
     except Exception as err:
         raise UpdateFailed(f"Init failed: {err}") from err
Ejemplo n.º 8
0
    async def _async_update_data(self) -> SensiboData:
        """Fetch data from Sensibo."""

        devices = []
        try:
            data = await self.client.async_get_devices()
            for dev in data["result"]:
                devices.append(dev)
        except AuthenticationError as error:
            raise ConfigEntryAuthFailed from error
        except SensiboError as error:
            raise UpdateFailed from error

        if not devices:
            raise UpdateFailed("No devices found")

        device_data: dict[str, Any] = {}
        for dev in devices:
            unique_id = dev["id"]
            mac = dev["macAddress"]
            name = dev["room"]["name"]
            temperature = dev["measurements"].get("temperature")
            humidity = dev["measurements"].get("humidity")
            ac_states = dev["acState"]
            target_temperature = ac_states.get("targetTemperature")
            hvac_mode = ac_states.get("mode")
            running = ac_states.get("on")
            fan_mode = ac_states.get("fanLevel")
            swing_mode = ac_states.get("swing")
            horizontal_swing_mode = ac_states.get("horizontalSwing")
            light_mode = ac_states.get("light")
            available = dev["connectionStatus"].get("isAlive", True)
            capabilities = dev["remoteCapabilities"]
            hvac_modes = list(capabilities["modes"])
            if hvac_modes:
                hvac_modes.append("off")
            current_capabilities = capabilities["modes"][ac_states.get("mode")]
            fan_modes = current_capabilities.get("fanLevels")
            swing_modes = current_capabilities.get("swing")
            horizontal_swing_modes = current_capabilities.get("horizontalSwing")
            light_modes = current_capabilities.get("light")
            temperature_unit_key = dev.get("temperatureUnit") or ac_states.get(
                "temperatureUnit"
            )
            temperatures_list = (
                current_capabilities["temperatures"]
                .get(temperature_unit_key, {})
                .get("values", [0, 1])
            )
            if temperatures_list:
                diff = MAX_POSSIBLE_STEP
                for i in range(len(temperatures_list) - 1):
                    if temperatures_list[i + 1] - temperatures_list[i] < diff:
                        diff = temperatures_list[i + 1] - temperatures_list[i]
                temperature_step = diff

            active_features = list(ac_states)
            full_features = set()
            for mode in capabilities["modes"]:
                if "temperatures" in capabilities["modes"][mode]:
                    full_features.add("targetTemperature")
                if "swing" in capabilities["modes"][mode]:
                    full_features.add("swing")
                if "fanLevels" in capabilities["modes"][mode]:
                    full_features.add("fanLevel")
                if "horizontalSwing" in capabilities["modes"][mode]:
                    full_features.add("horizontalSwing")
                if "light" in capabilities["modes"][mode]:
                    full_features.add("light")

            state = hvac_mode if hvac_mode else "off"

            fw_ver = dev["firmwareVersion"]
            fw_type = dev["firmwareType"]
            model = dev["productModel"]

            calibration_temp = dev["sensorsCalibration"].get("temperature")
            calibration_hum = dev["sensorsCalibration"].get("humidity")

            # Sky plus supports functionality to use motion sensor as sensor for temp and humidity
            if main_sensor := dev["mainMeasurementsSensor"]:
                measurements = main_sensor["measurements"]
                temperature = measurements.get("temperature")
                humidity = measurements.get("humidity")

            motion_sensors: dict[str, Any] = {}
            if dev["motionSensors"]:
                for sensor in dev["motionSensors"]:
                    measurement = sensor["measurements"]
                    motion_sensors[sensor["id"]] = MotionSensor(
                        id=sensor["id"],
                        alive=sensor["connectionStatus"].get("isAlive"),
                        motion=measurement.get("motion"),
                        fw_ver=sensor.get("firmwareVersion"),
                        fw_type=sensor.get("firmwareType"),
                        is_main_sensor=sensor.get("isMainSensor"),
                        battery_voltage=measurement.get("batteryVoltage"),
                        humidity=measurement.get("humidity"),
                        temperature=measurement.get("temperature"),
                        model=sensor.get("productModel"),
                        rssi=measurement.get("rssi"),
                    )

            # Add information for pure devices
            pure_conf = dev["pureBoostConfig"]
            pure_sensitivity = pure_conf.get("sensitivity") if pure_conf else None
            pure_boost_enabled = pure_conf.get("enabled") if pure_conf else None
            pm25 = dev["measurements"].get("pm25")

            # Binary sensors for main device
            room_occupied = dev["roomIsOccupied"]
            update_available = bool(
                dev["firmwareVersion"] != dev["currentlyAvailableFirmwareVersion"]
            )

            device_data[unique_id] = {
                "id": unique_id,
                "mac": mac,
                "name": name,
                "ac_states": ac_states,
                "temp": temperature,
                "humidity": humidity,
                "target_temp": target_temperature,
                "hvac_mode": hvac_mode,
                "on": running,
                "fan_mode": fan_mode,
                "swing_mode": swing_mode,
                "horizontal_swing_mode": horizontal_swing_mode,
                "light_mode": light_mode,
                "available": available,
                "hvac_modes": hvac_modes,
                "fan_modes": fan_modes,
                "swing_modes": swing_modes,
                "horizontal_swing_modes": horizontal_swing_modes,
                "light_modes": light_modes,
                "temp_unit": temperature_unit_key,
                "temp_list": temperatures_list,
                "temp_step": temperature_step,
                "active_features": active_features,
                "full_features": full_features,
                "state": state,
                "fw_ver": fw_ver,
                "fw_type": fw_type,
                "model": model,
                "calibration_temp": calibration_temp,
                "calibration_hum": calibration_hum,
                "full_capabilities": capabilities,
                "motion_sensors": motion_sensors,
                "pure_sensitivity": pure_sensitivity,
                "pure_boost_enabled": pure_boost_enabled,
                "pm25": pm25,
                "room_occupied": room_occupied,
                "update_available": update_available,
            }
Ejemplo n.º 9
0
 async def _async_update_data():
     """Fetch data from Met Éireann."""
     try:
         return await weather_data.fetch_data()
     except Exception as err:
         raise UpdateFailed(f"Update failed: {err}") from err
Ejemplo n.º 10
0
 async def async_update_data() -> dict[str, Any] | None:
     try:
         return await client.async_get_cameras()
     except MotionEyeClientError as exc:
         raise UpdateFailed("Error communicating with API") from exc
Ejemplo n.º 11
0
 async def async_update_data():
     try:
         client = hass.data[DOMAIN_DATA][DATA_CLIENT]
         await hass.async_add_executor_job(client.update_data)
     except Exception as e:
         raise UpdateFailed(f"Error communicating with server: {e}")
Ejemplo n.º 12
0
 async def _async_update_data(self):
     try:
         await self.async_send_message(json.dumps(POLL_REFRESH_MESSAGE))
         return self.data
     except Exception as exception:
         raise UpdateFailed() from exception
Ejemplo n.º 13
0
 async def async_update_data():
     """Fetch data from API endpoint."""
     try:
         await api.get_state()
     except exceptions.ConnectError as err:
         raise UpdateFailed("Failed to communicate with device") from err
Ejemplo n.º 14
0
    async def _async_update_data(self) -> dict[str, Any]:
        """Update data via library."""
        try:
            await self.force_data_refresh()
        except HassioAPIError as err:
            raise UpdateFailed(f"Error on Supervisor API: {err}") from err

        new_data = {}
        supervisor_info = get_supervisor_info(self.hass)
        addons_info = get_addons_info(self.hass)
        addons_stats = get_addons_stats(self.hass)
        addons_changelogs = get_addons_changelogs(self.hass)
        store_data = get_store(self.hass)

        repositories = {
            repo[ATTR_SLUG]: repo[ATTR_NAME]
            for repo in store_data.get("repositories", [])
        }

        new_data[DATA_KEY_ADDONS] = {
            addon[ATTR_SLUG]: {
                **addon,
                **((addons_stats or {}).get(addon[ATTR_SLUG]) or {}),
                ATTR_AUTO_UPDATE: (addons_info.get(addon[ATTR_SLUG])
                                   or {}).get(ATTR_AUTO_UPDATE, False),
                ATTR_CHANGELOG: (addons_changelogs
                                 or {}).get(addon[ATTR_SLUG]),
                ATTR_REPOSITORY:
                repositories.get(addon.get(ATTR_REPOSITORY),
                                 addon.get(ATTR_REPOSITORY, "")),
            }
            for addon in supervisor_info.get("addons", [])
        }
        if self.is_hass_os:
            new_data[DATA_KEY_OS] = get_os_info(self.hass)

        new_data[DATA_KEY_CORE] = get_core_info(self.hass)
        new_data[DATA_KEY_SUPERVISOR] = supervisor_info

        # If this is the initial refresh, register all addons and return the dict
        if not self.data:
            async_register_addons_in_dev_reg(
                self.entry_id, self.dev_reg,
                new_data[DATA_KEY_ADDONS].values())
            async_register_core_in_dev_reg(self.entry_id, self.dev_reg,
                                           new_data[DATA_KEY_CORE])
            async_register_supervisor_in_dev_reg(self.entry_id, self.dev_reg,
                                                 new_data[DATA_KEY_SUPERVISOR])
            if self.is_hass_os:
                async_register_os_in_dev_reg(self.entry_id, self.dev_reg,
                                             new_data[DATA_KEY_OS])

        # Remove add-ons that are no longer installed from device registry
        supervisor_addon_devices = {
            list(device.identifiers)[0][1]
            for device in self.dev_reg.devices.values()
            if self.entry_id in device.config_entries
            and device.model == SupervisorEntityModel.ADDON
        }
        if stale_addons := supervisor_addon_devices - set(
                new_data[DATA_KEY_ADDONS]):
            async_remove_addons_from_dev_reg(self.dev_reg, stale_addons)
Ejemplo n.º 15
0
 async def async_update_data_dimmer():
     """Fetch data from Control4 director for dimmer lights."""
     try:
         return await director_update_data(hass, entry, CONTROL4_DIMMER_VAR)
     except C4Exception as err:
         raise UpdateFailed(f"Error communicating with API: {err}") from err
Ejemplo n.º 16
0
Archivo: sensor.py Proyecto: 2Fake/core
 async def async_update_data():
     await hass.async_add_executor_job(sensor.update)
     if not sensor.sample_ok:
         raise UpdateFailed(f"Bad update of sensor {name}")
     return sensor
Ejemplo n.º 17
0
 async def _async_update():
     """Update the device state."""
     try:
         await led_ble.update()
     except BLEAK_EXCEPTIONS as ex:
         raise UpdateFailed(str(ex)) from ex
Ejemplo n.º 18
0
async def update_sensors(vue, scales):
    try:
        # Note: asyncio.TimeoutError and aiohttp.ClientError are already
        # handled by the data update coordinator.
        data = {}
        loop = asyncio.get_event_loop()
        for scale in scales:
            now = datetime.utcnow() - timedelta(seconds=1)
            channels = await loop.run_in_executor(
                None, vue.get_devices_usage, device_gids, now, scale
            )
            if not channels:
                _LOGGER.warn(
                    f"No channels found during update for scale {scale}. Retrying..."
                )
                channels = await loop.run_in_executor(
                    None, vue.get_devices_usage, device_gids, now, scale
                )
            if channels:
                for channel in channels:
                    id = "{0}-{1}-{2}".format(
                        channel.device_gid, channel.channel_num, scale
                    )
                    usage = round(channel.usage, 3)
                    if scale == Scale.MINUTE.value:
                        usage = round(
                            60 * 1000 * channel.usage
                        )  # convert from kwh to w rate
                    elif scale == Scale.SECOND.value:
                        usage = round(3600 * 1000 * channel.usage)  # convert to rate
                    elif scale == Scale.MINUTES_15.value:
                        usage = round(
                            4 * 1000 * channel.usage
                        )  # this might never be used but for safety, convert to rate
                    info = None

                    if channel.device_gid in device_information:
                        info = device_information[channel.device_gid]
                        if channel.channel_num in ["MainsFromGrid", "MainsToGrid"]:
                            found = False
                            channel_123 = None
                            for channel2 in info.channels:
                                if channel2.channel_num == channel.channel_num:
                                    found = True
                                    break
                                elif channel2.channel_num == "1,2,3":
                                    channel_123 = channel2
                            if not found:
                                _LOGGER.info(
                                    f"Adding channel for channel {channel.device_gid}-{channel.channel_num}"
                                )
                                info.channels.append(
                                    VueDeviceChannel(
                                        gid=channel.device_gid,
                                        name=None,
                                        channelNum=channel.channel_num,
                                        channelMultiplier=channel_123.channel_multiplier,
                                        channelTypeGid=channel_123.channel_type_gid,
                                    )
                                )

                    data[id] = {
                        "device_gid": channel.device_gid,
                        "channel_num": channel.channel_num,
                        "usage": usage,
                        "scale": scale,
                        "info": info,
                    }
            else:
                raise UpdateFailed(f"No channels found during update for scale {scale}")

        return data
    except Exception as err:
        _LOGGER.error(f"Error communicating with Emporia API: {err}")
        raise UpdateFailed(f"Error communicating with Emporia API: {err}")
Ejemplo n.º 19
0
 async def async_update_data(self):
     """Fetch data"""
     try:
         return await self._device.fetch_data()
     except Exception as err:
         raise UpdateFailed(f"Update failed: {err}") from err
Ejemplo n.º 20
0
 async def _update_method():
     """Get the latest data from Airthings."""
     try:
         return await airthings.update_devices()
     except AirthingsError as err:
         raise UpdateFailed(f"Unable to fetch data: {err}") from err
Ejemplo n.º 21
0
 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}")
Ejemplo n.º 22
0
    async def _async_update_data(self) -> Dict[str, Device]:
        """Fetch TaHoma data via event listener."""
        try:
            events = await self.client.fetch_events()
        except BadCredentialsException as exception:
            raise UpdateFailed("Invalid authentication.") from exception
        except TooManyRequestsException as exception:
            raise UpdateFailed(
                "Too many requests, try again later.") from exception
        except MaintenanceException as exception:
            raise UpdateFailed(
                "Server is down for maintenance.") from exception
        except TimeoutError as exception:
            raise UpdateFailed("Failed to connect.") from exception
        except (ServerDisconnectedError, NotAuthenticatedException):
            self.executions = {}
            await self.client.login()
            self.devices = await self._get_devices()
            return self.devices
        except Exception as exception:
            _LOGGER.debug(exception)
            raise UpdateFailed(exception) from exception

        for event in events:
            _LOGGER.debug(
                "%s/%s (device: %s, state: %s -> %s)",
                event.name,
                event.exec_id,
                event.deviceurl,
                event.old_state,
                event.new_state,
            )

            if event.name == EventName.DEVICE_AVAILABLE:
                self.devices[event.deviceurl].available = True

            elif event.name in [
                    EventName.DEVICE_UNAVAILABLE,
                    EventName.DEVICE_DISABLED,
            ]:
                self.devices[event.deviceurl].available = False

            elif event.name in [
                    EventName.DEVICE_CREATED,
                    EventName.DEVICE_UPDATED,
            ]:
                self.devices = await self._get_devices()

            elif event.name == EventName.DEVICE_REMOVED:
                registry = await device_registry.async_get_registry(self.hass)
                registry.async_remove_device(event.deviceurl)
                del self.devices[event.deviceurl]

            elif event.name == EventName.DEVICE_STATE_CHANGED:
                for state in event.device_states:
                    device = self.devices[event.deviceurl]
                    if state.name not in device.states:
                        device.states[state.name] = state
                    device.states[state.name].value = self._get_state(state)

            elif event.name == EventName.EXECUTION_REGISTERED:
                if event.exec_id not in self.executions:
                    self.executions[event.exec_id] = {}

                self.update_interval = timedelta(seconds=1)

            elif (event.name == EventName.EXECUTION_STATE_CHANGED
                  and event.exec_id in self.executions and event.new_state
                  in [ExecutionState.COMPLETED, ExecutionState.FAILED]):
                del self.executions[event.exec_id]

        if not self.executions:
            self.update_interval = self.original_update_interval

        return self.devices
Ejemplo n.º 23
0
    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.

        This will ping Alexa API to identify all devices, bluetooth, and the last
        called device.

        This will add new devices and services when discovered. By default this
        runs every SCAN_INTERVAL seconds unless another method calls it. if
        websockets is connected, it will increase the delay 10-fold between updates.
        While throttled at MIN_TIME_BETWEEN_SCANS, care should be taken to
        reduce the number of runs to avoid flooding. Slow changing states
        should be checked here instead of in spawned components like
        media_player since this object is one per account.
        Each AlexaAPI call generally results in two webpage requests.
        """
        from alexapy import AlexaAPI

        email: Text = login_obj.email
        if (email not in hass.data[DATA_ALEXAMEDIA]["accounts"]
                or "login_successful" not in login_obj.status
                or login_obj.session.closed):
            return
        existing_serials = _existing_serials(hass, login_obj)
        existing_entities = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
            "entities"]["media_player"].values()
        auth_info = hass.data[DATA_ALEXAMEDIA]["accounts"][email].get(
            "auth_info")
        new_devices = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
            "new_devices"]
        devices = {}
        bluetooth = {}
        preferences = {}
        dnd = {}
        raw_notifications = {}
        tasks = [
            AlexaAPI.get_devices(login_obj),
            AlexaAPI.get_bluetooth(login_obj),
            AlexaAPI.get_device_preferences(login_obj),
            AlexaAPI.get_dnd_state(login_obj),
            AlexaAPI.get_notifications(login_obj),
        ]
        if new_devices:
            tasks.append(AlexaAPI.get_authentication(login_obj))

        try:
            # Note: asyncio.TimeoutError and aiohttp.ClientError are already
            # handled by the data update coordinator.
            async with async_timeout.timeout(10):
                if new_devices:
                    (
                        devices,
                        bluetooth,
                        preferences,
                        dnd,
                        raw_notifications,
                        auth_info,
                    ) = await asyncio.gather(*tasks)
                else:
                    (
                        devices,
                        bluetooth,
                        preferences,
                        dnd,
                        raw_notifications,
                    ) = await asyncio.gather(*tasks)
                _LOGGER.debug(
                    "%s: Found %s devices, %s bluetooth",
                    hide_email(email),
                    len(devices) if devices is not None else "",
                    len(bluetooth.get("bluetoothStates", []))
                    if bluetooth is not None else "",
                )
        except (AlexapyLoginError, JSONDecodeError):
            _LOGGER.debug(
                "%s: Alexa API disconnected; attempting to relogin : status %s",
                hide_email(email),
                login_obj.status,
            )
            if login_obj.status:
                await login_obj.reset()
                await login_obj.login()
                await test_login_status(hass, config_entry, login_obj,
                                        setup_alexa)
            return
        except BaseException as err:
            raise
            raise UpdateFailed(f"Error communicating with API: {err}")

        await process_notifications(login_obj, raw_notifications)
        # Process last_called data to fire events
        await update_last_called(login_obj)

        new_alexa_clients = []  # list of newly discovered device names
        exclude_filter = []
        include_filter = []

        for device in devices:
            serial = device["serialNumber"]
            dev_name = device["accountName"]
            if include and dev_name not in include:
                include_filter.append(dev_name)
                if "appDeviceList" in device:
                    for app in device["appDeviceList"]:
                        (hass.data[DATA_ALEXAMEDIA]["accounts"][email]
                         ["excluded"][app["serialNumber"]]) = device
                hass.data[DATA_ALEXAMEDIA]["accounts"][email]["excluded"][
                    serial] = device
                continue
            elif exclude and dev_name in exclude:
                exclude_filter.append(dev_name)
                if "appDeviceList" in device:
                    for app in device["appDeviceList"]:
                        (hass.data[DATA_ALEXAMEDIA]["accounts"][email]
                         ["excluded"][app["serialNumber"]]) = device
                hass.data[DATA_ALEXAMEDIA]["accounts"][email]["excluded"][
                    serial] = device
                continue

            if "bluetoothStates" in bluetooth:
                for b_state in bluetooth["bluetoothStates"]:
                    if serial == b_state["deviceSerialNumber"]:
                        device["bluetooth_state"] = b_state
                        break

            if "devicePreferences" in preferences:
                for dev in preferences["devicePreferences"]:
                    if dev["deviceSerialNumber"] == serial:
                        device["locale"] = dev["locale"]
                        device["timeZoneId"] = dev["timeZoneId"]
                        _LOGGER.debug(
                            "%s: Locale %s timezone %s",
                            dev_name,
                            device["locale"],
                            device["timeZoneId"],
                        )
                        break

            if "doNotDisturbDeviceStatusList" in dnd:
                for dev in dnd["doNotDisturbDeviceStatusList"]:
                    if dev["deviceSerialNumber"] == serial:
                        device["dnd"] = dev["enabled"]
                        _LOGGER.debug("%s: DND %s", dev_name, device["dnd"])
                        hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                            "devices"]["switch"].setdefault(
                                serial, {"dnd": True})

                        break
            hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                "auth_info"] = device["auth_info"] = auth_info
            hass.data[DATA_ALEXAMEDIA]["accounts"][email]["devices"][
                "media_player"][serial] = device

            if serial not in existing_serials:
                new_alexa_clients.append(dev_name)
            elif serial in existing_entities:
                await hass.data[DATA_ALEXAMEDIA]["accounts"][email][
                    "entities"]["media_player"].get(serial).refresh(
                        device, no_api=True)
        _LOGGER.debug(
            "%s: Existing: %s New: %s;"
            " Filtered out by not being in include: %s "
            "or in exclude: %s",
            hide_email(email),
            list(existing_entities),
            new_alexa_clients,
            include_filter,
            exclude_filter,
        )

        if new_alexa_clients:
            cleaned_config = config.copy()
            cleaned_config.pop(CONF_PASSWORD, None)
            # CONF_PASSWORD contains sensitive info which is no longer needed
            for component in ALEXA_COMPONENTS:
                _LOGGER.debug("Loading %s", component)
                hass.async_add_job(
                    hass.config_entries.async_forward_entry_setup(
                        config_entry, component))

        hass.data[DATA_ALEXAMEDIA]["accounts"][email]["new_devices"] = False
Ejemplo n.º 24
0
 async def _async_update_data(self) -> dict:
     """Fetch Ruckus Unleashed data."""
     try:
         return {API_CLIENTS: await self._fetch_clients()}
     except (AuthenticationError, ConnectionError) as error:
         raise UpdateFailed(error) from error
Ejemplo n.º 25
0
 async def async_update_data():
     """Fetch data from NUT."""
     async with async_timeout.timeout(10):
         await hass.async_add_executor_job(data.update)
         if not data.status:
             raise UpdateFailed("Error fetching UPS state")
Ejemplo n.º 26
0
 async def async_update_data():
     """Fetch data from API endpoint."""
     try:
         return await refresh_subaru_data(entry, vehicle_info, controller)
     except SubaruException as err:
         raise UpdateFailed(err.message) from err
Ejemplo n.º 27
0
 async def async_get():
     try:
         return await api.async_get()
     except ApiError as err:
         raise UpdateFailed(err) from err
Ejemplo n.º 28
0
 async def _async_update_data(self) -> None:
     """Fetch all device and sensor data from api."""
     try:
         await self.device.async_update()
     except FLUX_LED_EXCEPTIONS as ex:
         raise UpdateFailed(ex) from ex
Ejemplo n.º 29
0
 async def _async_update_data(self) -> MetWeatherData:
     """Fetch data from Met."""
     try:
         return await self.weather.fetch_data()
     except Exception as err:
         raise UpdateFailed(f"Update failed: {err}") from err
Ejemplo n.º 30
0
 async def async_update_data():
     """Get new data from the API."""
     try:
         return await client.tiles.all()
     except TileError as err:
         raise UpdateFailed(f"Error while retrieving data: {err}")