How to use alexapy - 10 common examples

To help you get started, we’ve selected a few alexapy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github scottsweb / ham / homeassistant / custom_components / alexa_media / media_player.py View on Github external
async def init(self, device):
        from alexapy import AlexaAPI
        self.auth = await AlexaAPI.get_authentication(self._login)
        await self._set_authentication_details(self.auth)
        await self.refresh(device)
github ikifar2012 / Home-AssistantConfig / custom_components / alexa_media / __init__.py View on Github external
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]
github eifinger / homeassistant-config / custom_components / alexa_media / __init__.py View on Github external
):
                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},
github custom-components / alexa_media_player / custom_components / alexa_media / config_flow.py View on Github external
else:
            self.config[CONF_INCLUDE_DEVICES] = user_input[CONF_INCLUDE_DEVICES]
        if isinstance(user_input[CONF_EXCLUDE_DEVICES], str):
            self.config[CONF_EXCLUDE_DEVICES] = (
                user_input[CONF_EXCLUDE_DEVICES].split(",")
                if CONF_EXCLUDE_DEVICES in user_input and
                user_input[CONF_EXCLUDE_DEVICES] != ""
                else []
            )
        else:
            self.config[CONF_EXCLUDE_DEVICES] = user_input[CONF_EXCLUDE_DEVICES]

        if not self.login:
            _LOGGER.debug("Creating new login")
            try:
                self.login = AlexaLogin(
                    self.config[CONF_URL],
                    self.config[CONF_EMAIL],
                    self.config[CONF_PASSWORD],
                    self.hass.config.path,
                    self.config[CONF_DEBUG],
                )
                await self.login.login_with_cookie()
                return await self._test_login()
            except BaseException:
                raise
                return await self._show_form(errors={"base": "invalid_credentials"})
        else:
            _LOGGER.debug("Using existing login")
            await self.login.login(data=user_input)
            return await self._test_login()
github eliseomartelli / ParentsHomeAutomation / homeassistant / custom_components / alexa_media / config_flow.py View on Github external
)
        else:
            self.config[CONF_INCLUDE_DEVICES] = user_input[CONF_INCLUDE_DEVICES]
        if isinstance(user_input[CONF_EXCLUDE_DEVICES], str):
            self.config[CONF_EXCLUDE_DEVICES] = (
                user_input[CONF_EXCLUDE_DEVICES].split(",")
                if CONF_EXCLUDE_DEVICES in user_input
                and user_input[CONF_EXCLUDE_DEVICES] != ""
                else []
            )
        else:
            self.config[CONF_EXCLUDE_DEVICES] = user_input[CONF_EXCLUDE_DEVICES]
        try:
            if not self.login:
                _LOGGER.debug("Creating new login")
                self.login = AlexaLogin(
                    self.config[CONF_URL],
                    self.config[CONF_EMAIL],
                    self.config[CONF_PASSWORD],
                    self.hass.config.path,
                    self.config[CONF_DEBUG],
                )
                await self.login.login_with_cookie()
                return await self._test_login()
            else:
                _LOGGER.debug("Using existing login")
                await self.login.login(data=user_input)
                return await self._test_login()
        except AlexapyConnectionError:
            return await self._show_form(errors={"base": "connection_error"})
        except BaseException as ex:
            _LOGGER.warning("Unknown error: %s", ex)
github aneisch / home-assistant-config / custom_components / alexa_media / config_flow.py View on Github external
)
        else:
            self.config[CONF_INCLUDE_DEVICES] = user_input[CONF_INCLUDE_DEVICES]
        if isinstance(user_input[CONF_EXCLUDE_DEVICES], str):
            self.config[CONF_EXCLUDE_DEVICES] = (
                user_input[CONF_EXCLUDE_DEVICES].split(",")
                if CONF_EXCLUDE_DEVICES in user_input and
                user_input[CONF_EXCLUDE_DEVICES] != ""
                else []
            )
        else:
            self.config[CONF_EXCLUDE_DEVICES] = user_input[CONF_EXCLUDE_DEVICES]
        try:
            if not self.login:
                _LOGGER.debug("Creating new login")
                self.login = AlexaLogin(
                    self.config[CONF_URL],
                    self.config[CONF_EMAIL],
                    self.config[CONF_PASSWORD],
                    self.hass.config.path,
                    self.config[CONF_DEBUG],
                )
                await self.login.login_with_cookie()
                return await self._test_login()
            else:
                _LOGGER.debug("Using existing login")
                await self.login.login(data=user_input)
                return await self._test_login()
        except AlexapyConnectionError:
            return await self._show_form(errors={"base": "connection_error"})
        except BaseException as ex:
            _LOGGER.warning("Unknown error: %s", ex)
github macbury / SmartHouse / home-assistant / custom_components / alexa_media / media_player.py View on Github external
def __init__(self, device, login, hass):
        """Initialize the Alexa device."""
        from alexapy import AlexaAPI

        # Class info
        self._login = login
        self.alexa_api = AlexaAPI(self, login)
        self.auth = AlexaAPI.get_authentication(login)
        self.alexa_api_session = login.session
        self.account = hide_email(login.email)

        # Logged in info
        self._authenticated = None
        self._can_access_prime_music = None
        self._customer_email = None
        self._customer_id = None
        self._customer_name = None
        self._set_authentication_details(self.auth)

        # Device info
        self._device = None
        self._device_name = None
        self._device_serial_number = None
github eifinger / homeassistant-config / custom_components / alexa_media / __init__.py View on Github external
async def update_bluetooth_state(login_obj, device_serial):
        """Update the bluetooth state on ws bluetooth event."""
        from alexapy import AlexaAPI

        bluetooth = await AlexaAPI.get_bluetooth(login_obj)
        device = hass.data[DATA_ALEXAMEDIA]["accounts"][email]["devices"][
            "media_player"
        ][device_serial]

        if "bluetoothStates" in bluetooth:
            for b_state in bluetooth["bluetoothStates"]:
                if device_serial == b_state["deviceSerialNumber"]:
                    # _LOGGER.debug("%s: setting value for: %s to %s",
                    #               hide_email(email),
                    #               hide_serial(device_serial),
                    #               hide_serial(b_state))
                    device["bluetooth_state"] = b_state
                    return device["bluetooth_state"]
        _LOGGER.debug(
            "%s: get_bluetooth for: %s failed with %s",
            hide_email(email),
github eifinger / homeassistant-config / custom_components / alexa_media / alarm_control_panel.py View on Github external
def __init__(self, login, media_players=None) -> None:
        # pylint: disable=unexpected-keyword-arg
        """Initialize the Alexa device."""
        from alexapy import AlexaAPI

        # Class info
        self._login = login
        self.alexa_api = AlexaAPI(self, login)
        self.email = login.email
        self.account = hide_email(login.email)
        self._available = None
        self._assumed_state = None

        # Guard info
        self._appliance_id = None
        self._guard_entity_id = None
        self._friendly_name = "Alexa Guard"
        self._state = None
        self._should_poll = False
        self._attrs: Dict[Text, Text] = {}
        self._media_players = {} or media_players
github michaeldvinci / Home-AssistantConfig / custom_components / alexa_media / __init__.py View on Github external
existing_serials = (hass.data[DATA_ALEXAMEDIA]
                            ['accounts']
                            [email]
                            ['entities']
                            ['media_player'].keys())
        existing_entities = (hass.data[DATA_ALEXAMEDIA]
                             ['accounts']
                             [email]
                             ['entities']
                             ['media_player'].values())
        if (hass.data[DATA_ALEXAMEDIA]['accounts'][email]['websocket']
                and not (hass.data[DATA_ALEXAMEDIA]
                         ['accounts'][email]['new_devices'])):
            return
        hass.data[DATA_ALEXAMEDIA]['accounts'][email]['new_devices'] = False
        devices = AlexaAPI.get_devices(login_obj)
        bluetooth = AlexaAPI.get_bluetooth(login_obj)
        preferences = AlexaAPI.get_device_preferences(login_obj)
        _LOGGER.debug("%s: Found %s devices, %s bluetooth",
                      hide_email(email),
                      len(devices) if devices is not None else '',
                      len(bluetooth) if bluetooth is not None else '')
        if ((devices is None or bluetooth is None)
                and not (hass.data[DATA_ALEXAMEDIA]
                         ['accounts'][email]['config'])):
            _LOGGER.debug("Alexa API disconnected; attempting to relogin")
            login_obj.login_with_cookie()
            test_login_status(hass, config, login_obj, setup_platform_callback)
            return

        new_alexa_clients = []  # list of newly discovered device names
        excluded = []