# Buggy code
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
    ):
        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 "",
            )
            if (devices is None or bluetooth is None) and not (
                hass.data[DATA_ALEXAMEDIA]["accounts"][email]["configurator"]
            ):
                raise AlexapyLoginError()
    except (AlexapyLoginError, JSONDecodeError):
        _LOGGER.debug(
            "%s: Alexa API disconnected; attempting to relogin : status %s",
            hide_email(email),
            login_obj.status,
        )
        if login_obj.status and not await test_login_status(
            hass, config_entry, login_obj, setup_alexa
        ):
            login_obj.status = {}
            await login_obj.login()
        return
    except BaseException as err:
        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


# Traceback (RuntimeError)
2020-04-27 13:53:41 ERROR (MainThread) [custom_components.alexa_media] Unexpected error fetching alexa_media data: Session is closed
Traceback (most recent call last):
File "/config/custom_components/alexa_media/__init__.py", line 277, in async_update_data
) = await asyncio.gather(*tasks)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 680, in get_devices
"get", login, "/api/devices-v2/device", query=None
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 167, in _static_request
ssl=login._ssl,
File "/usr/local/lib/python3.7/site-packages/aiohttp/client.py", line 357, in _request
raise RuntimeError('Session is closed')
RuntimeError: Session is closed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 136, in async_refresh
self.data = await self._async_update_data()
File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 124, in _async_update_data
return await self.update_method()
File "/config/custom_components/alexa_media/__init__.py", line 294, in async_update_data
await login_obj.login_with_cookie()
File "/usr/local/lib/python3.7/site-packages/alexapy/alexalogin.py", line 168, in login_with_cookie
await self.login(cookies=self._cookies)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexalogin.py", line 333, in login
if cookies and await self.test_loggedin(cookies):
File "/usr/local/lib/python3.7/site-packages/alexapy/alexalogin.py", line 238, in test_loggedin
self._prefix + self._url + "/api/bootstrap", cookies=cookies, ssl=self._ssl
File "/usr/local/lib/python3.7/site-packages/aiohttp/client.py", line 357, in _request
raise RuntimeError('Session is closed')
RuntimeError: Session is closed

# Fixed code
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 "",
            )
            if (devices is None or bluetooth is None) and not (
                hass.data[DATA_ALEXAMEDIA]["accounts"][email]["configurator"]
            ):
                raise AlexapyLoginError()
    except (AlexapyLoginError, JSONDecodeError):
        _LOGGER.debug(
            "%s: Alexa API disconnected; attempting to relogin : status %s",
            hide_email(email),
            login_obj.status,
        )
        if login_obj.status and not await test_login_status(
            hass, config_entry, login_obj, setup_alexa
        ):
            login_obj.status = {}
            await login_obj.login()
        return
    except BaseException as err:
        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