# Buggy code
async def ws_handler(message_obj):
    """Handle websocket messages.

    This allows push notifications from Alexa to update last_called
    and media state.
    """

    command = (
        message_obj.json_payload["command"]
        if isinstance(message_obj.json_payload, dict)
        and "command" in message_obj.json_payload
        else None
    )
    json_payload = (
        message_obj.json_payload["payload"]
        if isinstance(message_obj.json_payload, dict)
        and "payload" in message_obj.json_payload
        else None
    )
    existing_serials = _existing_serials()
    seen_commands = hass.data[DATA_ALEXAMEDIA]["accounts"][email]["websocket_commands"]
    if command and json_payload:
        _LOGGER.debug(
            "%s: Received websocket command: %s : %s",
            hide_email(email),
            command,
            hide_serial(json_payload),
        )
        serial = None
        if command not in seen_commands:
            seen_commands[command] = time.time()
            _LOGGER.debug("Adding %s to seen_commands: %s", command, seen_commands)
        if (
            "dopplerId" in json_payload
            and "deviceSerialNumber" in json_payload["dopplerId"]
        ):
            serial = json_payload["dopplerId"]["deviceSerialNumber"]
        elif (
            "key" in json_payload
            and "entryId" in json_payload["key"]
            and json_payload["key"]["entryId"].find("#") != -1
        ):
            serial = (json_payload["key"]["entryId"]).split("#")[2]
            json_payload["key"]["serialNumber"] = serial
        else:
            serial = None
        if command == "PUSH_ACTIVITY":
            #  Last_Alexa Updated
            last_called = {
                "serialNumber": serial,
                "timestamp": json_payload["timestamp"],
            }
            if serial and serial in existing_serials:
                await update_last_called(login_obj, last_called)
            hass.bus.async_fire(
                f"{DOMAIN}_{hide_email(email)}"[0:32],
                {"push_activity": json_payload},
            )
        elif command in (
            "PUSH_AUDIO_PLAYER_STATE",
            "PUSH_MEDIA_CHANGE",
            "PUSH_MEDIA_PROGRESS_CHANGE",
        ):
            # Player update/ Push_media from tune_in
            if serial and serial in existing_serials:
                _LOGGER.debug("Updating media_player: %s", hide_serial(json_payload))
                hass.bus.async_fire(
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"player_state": json_payload},
                )
        elif command == "PUSH_VOLUME_CHANGE":
            # Player volume update
            if serial and serial in existing_serials:
                _LOGGER.debug(
                    "Updating media_player volume: %s", hide_serial(json_payload)
                )
                hass.bus.async_fire(
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"player_state": json_payload},
                )
        elif command in (
            "PUSH_DOPPLER_CONNECTION_CHANGE",
            "PUSH_EQUALIZER_STATE_CHANGE",
        ):
            # Player availability update
            if serial and serial in existing_serials:
                _LOGGER.debug(
                    "Updating media_player availability %s",
                    hide_serial(json_payload),
                )
                hass.bus.async_fire(
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"player_state": json_payload},
                )
        elif command == "PUSH_BLUETOOTH_STATE_CHANGE":
            # Player bluetooth update
            bt_event = json_payload["bluetoothEvent"]
            bt_success = json_payload["bluetoothEventSuccess"]
            if (
                serial
                and serial in existing_serials
                and bt_success
                and bt_event
                and bt_event in ["DEVICE_CONNECTED", "DEVICE_DISCONNECTED"]
            ):
                _LOGGER.debug(
                    "Updating media_player bluetooth %s", hide_serial(json_payload)
                )
                bluetooth_state = await update_bluetooth_state(login_obj, serial)
                # _LOGGER.debug("bluetooth_state %s",
                #               hide_serial(bluetooth_state))
                if bluetooth_state:
                    hass.bus.async_fire(
                        f"{DOMAIN}_{hide_email(email)}"[0:32],
                        {"bluetooth_change": bluetooth_state},
                    )
        elif command == "PUSH_MEDIA_QUEUE_CHANGE":
            # Player availability update
            if serial and serial in existing_serials:
                _LOGGER.debug(
                    "Updating media_player queue %s", hide_serial(json_payload)
                )
                hass.bus.async_fire(
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"queue_state": json_payload},
                )
        elif command == "PUSH_NOTIFICATION_CHANGE":
            # Player update
            await process_notifications(login_obj)
            if serial and serial in existing_serials:
                _LOGGER.debug(
                    "Updating mediaplayer notifications: %s",
                    hide_serial(json_payload),
                )
                hass.bus.async_fire(
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"notification_update": json_payload},
                )
        elif command in [
            "PUSH_DELETE_DOPPLER_ACTIVITIES",  # delete Alexa history
            "PUSH_LIST_ITEM_CHANGE",  # update shopping list
            "PUSH_CONTENT_FOCUS_CHANGE",  # likely prime related refocus
        ]:
            pass
        else:
            _LOGGER.warning(
                "Unhandled command: %s with data %s. Please report at %s",
                command,
                hide_serial(json_payload),
                ISSUE_URL,
            )
        if serial in existing_serials:
            hass.data[DATA_ALEXAMEDIA]["accounts"][email]["websocket_activity"][
                "serials"
            ][serial] = time.time()
        if (
            serial
            and serial not in existing_serials
            and serial
            not in (hass.data[DATA_ALEXAMEDIA]["accounts"][email]["excluded"].keys())
        ):
            _LOGGER.debug("Discovered new media_player %s", serial)
            (hass.data[DATA_ALEXAMEDIA]["accounts"][email]["new_devices"]) = True
            await update_devices(  # pylint: disable=unexpected-keyword-arg
                login_obj, no_throttle=True
            )


# Traceback (ValueError)
2019-10-26 14:43:05 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry ***REDACTED*** - amazon.com for media_player
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 190, in async_setup
hass, self
File "/usr/src/homeassistant/homeassistant/components/media_player/__init__.py", line 340, in async_setup_entry
return await hass.data[DOMAIN].async_setup_entry(entry)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 151, in async_setup_entry
raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!
2019-10-26 14:43:05 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry ***REDACTED*** - amazon.com for alarm_control_panel
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 190, in async_setup
hass, self
File "/usr/src/homeassistant/homeassistant/components/alarm_control_panel/__init__.py", line 74, in async_setup_entry
return await hass.data[DOMAIN].async_setup_entry(entry)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 151, in async_setup_entry
raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!
2019-10-26 14:43:05 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry ***REDACTED*** - amazon.com for switch
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 190, in async_setup
hass, self
File "/usr/src/homeassistant/homeassistant/components/switch/__init__.py", line 79, in async_setup_entry
return await hass.data[DOMAIN].async_setup_entry(entry)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 151, in async_setup_entry
raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!
2019-10-26 14:43:05 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry ***REDACTED*** - amazon.com for sensor
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/config_entries.py", line 190, in async_setup
hass, self
File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 60, in async_setup_entry
return await hass.data[DOMAIN].async_setup_entry(entry)
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 151, in async_setup_entry
raise ValueError("Config entry has already been setup!")
ValueError: Config entry has already been setup!**System details**```

# Fixed code
async def ws_handler(message_obj):
    """Handle websocket messages.

    This allows push notifications from Alexa to update last_called
    and media state.
    """

    command = (
        message_obj.json_payload["command"]
        if isinstance(message_obj.json_payload, dict)
        and "command" in message_obj.json_payload
        else None
    )
    json_payload = (
        message_obj.json_payload["payload"]
        if isinstance(message_obj.json_payload, dict)
        and "payload" in message_obj.json_payload
        else None
    )
    existing_serials = _existing_serials(hass, login_obj)
    seen_commands = hass.data[DATA_ALEXAMEDIA]["accounts"][email]["websocket_commands"]
    if command and json_payload:
        _LOGGER.debug(
            "%s: Received websocket command: %s : %s",
            hide_email(email),
            command,
            hide_serial(json_payload),
        )
        serial = None
        if command not in seen_commands:
            seen_commands[command] = time.time()
            _LOGGER.debug("Adding %s to seen_commands: %s", command, seen_commands)
        if (
            "dopplerId" in json_payload
            and "deviceSerialNumber" in json_payload["dopplerId"]
        ):
            serial = json_payload["dopplerId"]["deviceSerialNumber"]
        elif (
            "key" in json_payload
            and "entryId" in json_payload["key"]
            and json_payload["key"]["entryId"].find("#") != -1
        ):
            serial = (json_payload["key"]["entryId"]).split("#")[2]
            json_payload["key"]["serialNumber"] = serial
        else:
            serial = None
        if command == "PUSH_ACTIVITY":
            #  Last_Alexa Updated
            last_called = {
                "serialNumber": serial,
                "timestamp": json_payload["timestamp"],
            }
            if serial and serial in existing_serials:
                await update_last_called(login_obj, last_called)
            async_dispatcher_send(
                hass,
                f"{DOMAIN}_{hide_email(email)}"[0:32],
                {"push_activity": json_payload},
            )
        elif command in (
            "PUSH_AUDIO_PLAYER_STATE",
            "PUSH_MEDIA_CHANGE",
            "PUSH_MEDIA_PROGRESS_CHANGE",
        ):
            # Player update/ Push_media from tune_in
            if serial and serial in existing_serials:
                _LOGGER.debug("Updating media_player: %s", hide_serial(json_payload))
                async_dispatcher_send(
                    hass,
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"player_state": json_payload},
                )
        elif command == "PUSH_VOLUME_CHANGE":
            # Player volume update
            if serial and serial in existing_serials:
                _LOGGER.debug(
                    "Updating media_player volume: %s", hide_serial(json_payload)
                )
                async_dispatcher_send(
                    hass,
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"player_state": json_payload},
                )
        elif command in (
            "PUSH_DOPPLER_CONNECTION_CHANGE",
            "PUSH_EQUALIZER_STATE_CHANGE",
        ):
            # Player availability update
            if serial and serial in existing_serials:
                _LOGGER.debug(
                    "Updating media_player availability %s",
                    hide_serial(json_payload),
                )
                async_dispatcher_send(
                    hass,
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"player_state": json_payload},
                )
        elif command == "PUSH_BLUETOOTH_STATE_CHANGE":
            # Player bluetooth update
            bt_event = json_payload["bluetoothEvent"]
            bt_success = json_payload["bluetoothEventSuccess"]
            if (
                serial
                and serial in existing_serials
                and bt_success
                and bt_event
                and bt_event in ["DEVICE_CONNECTED", "DEVICE_DISCONNECTED"]
            ):
                _LOGGER.debug(
                    "Updating media_player bluetooth %s", hide_serial(json_payload)
                )
                bluetooth_state = await update_bluetooth_state(login_obj, serial)
                # _LOGGER.debug("bluetooth_state %s",
                #               hide_serial(bluetooth_state))
                if bluetooth_state:
                    async_dispatcher_send(
                        hass,
                        f"{DOMAIN}_{hide_email(email)}"[0:32],
                        {"bluetooth_change": bluetooth_state},
                    )
        elif command == "PUSH_MEDIA_QUEUE_CHANGE":
            # Player availability update
            if serial and serial in existing_serials:
                _LOGGER.debug(
                    "Updating media_player queue %s", hide_serial(json_payload)
                )
                async_dispatcher_send(
                    hass,
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"queue_state": json_payload},
                )
        elif command == "PUSH_NOTIFICATION_CHANGE":
            # Player update
            await process_notifications(login_obj)
            if serial and serial in existing_serials:
                _LOGGER.debug(
                    "Updating mediaplayer notifications: %s",
                    hide_serial(json_payload),
                )
                async_dispatcher_send(
                    hass,
                    f"{DOMAIN}_{hide_email(email)}"[0:32],
                    {"notification_update": json_payload},
                )
        elif command in [
            "PUSH_DELETE_DOPPLER_ACTIVITIES",  # delete Alexa history
            "PUSH_LIST_ITEM_CHANGE",  # update shopping list
            "PUSH_CONTENT_FOCUS_CHANGE",  # likely prime related refocus
        ]:
            pass
        else:
            _LOGGER.warning(
                "Unhandled command: %s with data %s. Please report at %s",
                command,
                hide_serial(json_payload),
                ISSUE_URL,
            )
        if serial in existing_serials:
            hass.data[DATA_ALEXAMEDIA]["accounts"][email]["websocket_activity"][
                "serials"
            ][serial] = time.time()
        if (
            serial
            and serial not in existing_serials
            and serial
            not in (hass.data[DATA_ALEXAMEDIA]["accounts"][email]["excluded"].keys())
        ):
            _LOGGER.debug("Discovered new media_player %s", serial)
            (hass.data[DATA_ALEXAMEDIA]["accounts"][email]["new_devices"]) = True
            coordinator = hass.data[DATA_ALEXAMEDIA]["accounts"][email].get(
                "coordinator"
            )
            if coordinator:
                await coordinator.async_request_refresh()