Exemple #1
0
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
    """Validate the configuration and return a Tile scanner."""
    from pytile import Client

    websession = aiohttp_client.async_get_clientsession(hass)

    config_file = hass.config.path(".{}{}".format(
        slugify(config[CONF_USERNAME]), CLIENT_UUID_CONFIG_FILE))
    config_data = await hass.async_add_job(load_json, config_file)
    if config_data:
        client = Client(config[CONF_USERNAME],
                        config[CONF_PASSWORD],
                        websession,
                        client_uuid=config_data['client_uuid'])
    else:
        client = Client(config[CONF_USERNAME], config[CONF_PASSWORD],
                        websession)

        config_data = {'client_uuid': client.client_uuid}
        await hass.async_add_job(save_json, config_file, config_data)

    scanner = TileScanner(client, hass, async_see,
                          config[CONF_MONITORED_VARIABLES],
                          config[CONF_SHOW_INACTIVE])
    return await scanner.async_init()
    def __init__(self, hass, config, see):
        """Initialize."""
        from pytile import Client

        _LOGGER.debug('Received configuration data: %s', config)

        # Load the client UUID (if it exists):
        config_data = load_json(hass.config.path(CLIENT_UUID_CONFIG_FILE))
        if config_data:
            _LOGGER.debug('Using existing client UUID')
            self._client = Client(config[CONF_USERNAME], config[CONF_PASSWORD],
                                  config_data['client_uuid'])
        else:
            _LOGGER.debug('Generating new client UUID')
            self._client = Client(config[CONF_USERNAME], config[CONF_PASSWORD])

            if not save_json(hass.config.path(CLIENT_UUID_CONFIG_FILE),
                             {'client_uuid': self._client.client_uuid}):
                _LOGGER.error("Failed to save configuration file")

        _LOGGER.debug('Client UUID: %s', self._client.client_uuid)
        _LOGGER.debug('User UUID: %s', self._client.user_uuid)

        self._show_inactive = config.get(CONF_SHOW_INACTIVE)
        self._types = config.get(CONF_MONITORED_VARIABLES)

        self.devices = {}
        self.see = see

        track_utc_time_change(hass, self._update_info, second=range(0, 60, 30))

        self._update_info()
Exemple #3
0
async def async_setup_scanner(hass, config, async_see, discovery_info=None):
    """Validate the configuration and return a Tile scanner."""
    from pytile import Client

    websession = aiohttp_client.async_get_clientsession(hass)

    config_data = await hass.async_add_job(
        load_json, hass.config.path(CLIENT_UUID_CONFIG_FILE))
    if config_data:
        client = Client(config[CONF_USERNAME],
                        config[CONF_PASSWORD],
                        websession,
                        client_uuid=config_data['client_uuid'])
    else:
        client = Client(config[CONF_USERNAME], config[CONF_PASSWORD],
                        websession)

        config_data = {'client_uuid': client.client_uuid}
        config_saved = await hass.async_add_job(
            save_json, hass.config.path(CLIENT_UUID_CONFIG_FILE), config_data)
        if not config_saved:
            _LOGGER.error('Failed to save the client UUID')

    scanner = TileScanner(client, hass, async_see,
                          config[CONF_MONITORED_VARIABLES],
                          config[CONF_SHOW_INACTIVE])
    return await scanner.async_init()
Exemple #4
0
async def test_async_init(aresponses, event_loop, fixture_create_client,
                          fixture_create_session):
    """Test initializing a client with a Tile session."""
    aresponses.add(
        "production.tile-api.com",
        f"/api/v1/clients/{TILE_CLIENT_UUID}",
        "put",
        aresponses.Response(text=json.dumps(fixture_create_client),
                            status=200),
    )
    aresponses.add(
        "production.tile-api.com",
        f"/api/v1/clients/{TILE_CLIENT_UUID}/sessions",
        "post",
        aresponses.Response(text=json.dumps(fixture_create_session),
                            status=200),
    )

    async with aiohttp.ClientSession(loop=event_loop) as websession:
        client = Client(TILE_EMAIL,
                        TILE_PASSWORD,
                        websession,
                        client_uuid=TILE_CLIENT_UUID)
        await client.async_init()
        assert client.client_uuid == TILE_CLIENT_UUID
        assert client.user_uuid == TILE_USER_UUID
Exemple #5
0
async def test_get_all(  # pylint: disable=too-many-arguments
        aresponses, event_loop, fixture_tile_details, fixture_tile_list,
        fixture_create_client, fixture_create_session):
    """Test getting details on all of a user's tiles."""
    aresponses.add(
        'production.tile-api.com',
        '/api/v1/clients/{0}'.format(TILE_CLIENT_UUID), 'put',
        aresponses.Response(text=json.dumps(fixture_create_client),
                            status=200))
    aresponses.add(
        'production.tile-api.com',
        '/api/v1/clients/{0}/sessions'.format(TILE_CLIENT_UUID), 'post',
        aresponses.Response(text=json.dumps(fixture_create_session),
                            status=200))
    aresponses.add(
        'production.tile-api.com',
        '/api/v1/users/{0}/user_tiles'.format(TILE_USER_UUID), 'get',
        aresponses.Response(text=json.dumps(fixture_tile_list), status=200))
    aresponses.add(
        'production.tile-api.com', '/api/v1/tiles', 'get',
        aresponses.Response(text=json.dumps(fixture_tile_details), status=200))

    async with aiohttp.ClientSession(loop=event_loop) as websession:
        client = Client(TILE_EMAIL,
                        TILE_PASSWORD,
                        websession,
                        client_uuid=TILE_CLIENT_UUID)
        await client.async_init()
        tiles = await client.tiles.all()

        assert tiles[0]['name'] == TILE_TILE_NAME
Exemple #6
0
async def test_expired_session(aresponses, event_loop, fixture_create_client,
                               fixture_expired_session):
    """Test raising an exception on an expired session."""
    aresponses.add(
        "production.tile-api.com",
        f"/api/v1/clients/{TILE_CLIENT_UUID}",
        "put",
        aresponses.Response(text=json.dumps(fixture_create_client),
                            status=200),
    )
    aresponses.add(
        "production.tile-api.com",
        f"/api/v1/clients/{TILE_CLIENT_UUID}/sessions",
        "post",
        aresponses.Response(text=json.dumps(fixture_expired_session),
                            status=200),
    )

    with pytest.raises(SessionExpiredError):
        async with aiohttp.ClientSession(loop=event_loop) as websession:
            client = Client(TILE_EMAIL,
                            TILE_PASSWORD,
                            websession,
                            client_uuid=TILE_CLIENT_UUID)
            await client.async_init()
            await client.tiles.all()
Exemple #7
0
async def test_create_existing(event_loop):
    """Test the creation of a client with an existing client UUID."""
    async with aiohttp.ClientSession(loop=event_loop) as websession:
        client = Client(TILE_EMAIL,
                        TILE_PASSWORD,
                        websession,
                        client_uuid=TILE_CLIENT_UUID)
        assert client.client_uuid == TILE_CLIENT_UUID
Exemple #8
0
async def test_bad_endpoint(aresponses, event_loop):
    """Test that an exception is raised on a bad endpoint."""
    aresponses.add('production.tile-api.com', '/api/v1/bad_endpoint', 'get',
                   aresponses.Response(text='', status=404))

    with pytest.raises(RequestError):
        async with aiohttp.ClientSession(loop=event_loop) as websession:
            client = Client(TILE_EMAIL,
                            TILE_PASSWORD,
                            websession,
                            client_uuid=TILE_CLIENT_UUID)
            await client.request('get', 'bad_endpoint')
Exemple #9
0
    def __init__(self, hass, config, see):
        """Initialize."""
        from pytile import Client

        _LOGGER.debug('Received configuration data: %s', config)

        # Load the client UUID (if it exists):
        config_data = load_json(hass.config.path(CLIENT_UUID_CONFIG_FILE))
        if config_data:
            _LOGGER.debug('Using existing client UUID')
            self._client = Client(
                config[CONF_USERNAME],
                config[CONF_PASSWORD],
                config_data['client_uuid'])
        else:
            _LOGGER.debug('Generating new client UUID')
            self._client = Client(
                config[CONF_USERNAME],
                config[CONF_PASSWORD])

            if not save_json(
                    hass.config.path(CLIENT_UUID_CONFIG_FILE),
                    {'client_uuid': self._client.client_uuid}):
                _LOGGER.error("Failed to save configuration file")

        _LOGGER.debug('Client UUID: %s', self._client.client_uuid)
        _LOGGER.debug('User UUID: %s', self._client.user_uuid)

        self._types = config.get(CONF_MONITORED_VARIABLES)

        self.devices = {}
        self.see = see

        track_utc_time_change(
            hass, self._update_info, second=range(0, 60, 30))

        self._update_info()
Exemple #10
0
async def main():
    """Run."""
    async with ClientSession() as websession:
        try:
            # Create a client:
            client = Client('<EMAIL>', '<PASSWORD', websession)
            await client.async_init()

            print('Showing active Tiles:')
            print(await client.tiles.all())

            print('Showing all Tiles:')
            print(await client.tiles.all(show_inactive=True))
        except TileError as err:
            print(err)
Exemple #11
0
class TileDeviceScanner(DeviceScanner):
    """Define a device scanner for Tiles."""

    def __init__(self, hass, config, see):
        """Initialize."""
        from pytile import Client

        _LOGGER.debug('Received configuration data: %s', config)

        # Load the client UUID (if it exists):
        config_data = load_json(hass.config.path(CLIENT_UUID_CONFIG_FILE))
        if config_data:
            _LOGGER.debug('Using existing client UUID')
            self._client = Client(
                config[CONF_USERNAME],
                config[CONF_PASSWORD],
                config_data['client_uuid'])
        else:
            _LOGGER.debug('Generating new client UUID')
            self._client = Client(
                config[CONF_USERNAME],
                config[CONF_PASSWORD])

            if not save_json(
                    hass.config.path(CLIENT_UUID_CONFIG_FILE),
                    {'client_uuid': self._client.client_uuid}):
                _LOGGER.error("Failed to save configuration file")

        _LOGGER.debug('Client UUID: %s', self._client.client_uuid)
        _LOGGER.debug('User UUID: %s', self._client.user_uuid)

        self._types = config.get(CONF_MONITORED_VARIABLES)

        self.devices = {}
        self.see = see

        track_utc_time_change(
            hass, self._update_info, second=range(0, 60, 30))

        self._update_info()

    def _update_info(self, now=None) -> None:
        """Update the device info."""
        device_data = self._client.get_tiles(type_whitelist=self._types)

        try:
            self.devices = device_data['result']
        except KeyError:
            _LOGGER.warning('No Tiles found')
            _LOGGER.debug(device_data)
            return

        for info in self.devices.values():
            dev_id = 'tile_{0}'.format(slugify(info['name']))
            lat = info['tileState']['latitude']
            lon = info['tileState']['longitude']

            attrs = {
                ATTR_ALTITUDE: info['tileState']['altitude'],
                ATTR_CONNECTION_STATE: info['tileState']['connection_state'],
                ATTR_IS_DEAD: info['is_dead'],
                ATTR_IS_LOST: info['tileState']['is_lost'],
                ATTR_LAST_SEEN: info['tileState']['timestamp'],
                ATTR_LAST_UPDATED: device_data['timestamp_ms'],
                ATTR_RING_STATE: info['tileState']['ring_state'],
                ATTR_VOIP_STATE: info['tileState']['voip_state'],
            }

            self.see(
                dev_id=dev_id,
                gps=(lat, lon),
                attributes=attrs,
                icon=DEFAULT_ICON
            )
Exemple #12
0
async def test_create(event_loop):
    """Test the creation of a client."""
    async with aiohttp.ClientSession(loop=event_loop) as websession:
        client = Client(TILE_EMAIL, TILE_PASSWORD, websession)
        assert client.client_uuid != TILE_CLIENT_UUID