Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ This package talks to a Tile over Bluetooth Low Energy with [bleak][bleak]. It c

- check that an auth key belongs to a Tile;
- make a Tile ring;
- read the Tile ID of a Tile, without an auth key.
- read the Tile ID of a Tile, without an auth key;
- get the auth keys of the Tiles of an account from the Tile cloud.

This package is not affiliated with, endorsed by, or connected to Tile or Life360.

Expand All @@ -29,7 +30,7 @@ pip install tile-ble

## Usage

Each Tile has its own auth key. The key is a base64 string from the Tile cloud. For example, [pytile][pytile] exposes it as `Tile.auth_key` once that change is released.
Each Tile has its own auth key. The key is a base64 string from the Tile cloud.

```python
import asyncio
Expand All @@ -55,6 +56,21 @@ if __name__ == "__main__":

`async_authenticate()` proves that the key belongs to this Tile. It does not ring the Tile.

### Get the auth keys from the Tile cloud

`async_get_tiles()` logs in to the Tile cloud with the account email and password. It returns a `TileCloudTile` with `tile_id`, `name` and `auth_key` for each Tile. `auth_key` is `None` when the cloud sends no key. Tile Labels are not returned.

```python
from aiohttp import ClientSession

from tile_ble import async_get_tiles

async with ClientSession() as session:
tiles = await async_get_tiles(session, "user@example.com", "password")
```

Use `address_matches_tile_id()` to find the Bluetooth device of each Tile.

Tiles advertise the `TILE_SERVICE_UUID` service. Use it to find Tiles in a scan.

### Find which Tile is which
Expand All @@ -79,11 +95,13 @@ tile_id = await async_read_tile_id(ble_device)

All exceptions derive from `TileBleError`.

| Exception | Raised when |
| ---------------------------- | -------------------------------------------------------------------- |
| `TileBleConnectionError` | The Tile cannot be reached, a Bluetooth call fails, or it times out. |
| `TileBleAuthenticationError` | The Tile rejects the auth key. |
| `TileBleError` | The Tile returns an error, or refuses to ring. |
| Exception | Raised when |
| ------------------------------ | -------------------------------------------------------------------- |
| `TileBleConnectionError` | The Tile cannot be reached, a Bluetooth call fails, or it times out. |
| `TileBleAuthenticationError` | The Tile rejects the auth key. |
| `TileBleError` | The Tile returns an error, or refuses to ring. |
| `TileCloudAuthenticationError` | The Tile cloud rejects the email or password. |
| `TileCloudError` | A Tile cloud request fails. |

`TileBleDevice` raises `ValueError` when the auth key is not a 16-byte base64 value.

Expand Down Expand Up @@ -207,7 +225,6 @@ The protocol implementation is based on [node-tile][node-tile]. See
[poetry-install]: https://python-poetry.org/docs/#installation
[poetry]: https://python-poetry.org
[prek]: https://prek.j178.dev/
[pytile]: https://github.com/bachya/pytile
[uv]: https://docs.astral.sh/uv/
[uv-install]: https://docs.astral.sh/uv/getting-started/installation/
[project-stage-shield]: https://img.shields.io/badge/project%20stage-beta-yellow.svg
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ classifiers = [
"Topic :: Software Development :: Libraries :: Python Modules",
]
dependencies = [
"aiohttp>=3.9.0",
"bleak>=0.22.0",
"bleak-retry-connector>=3.5.0",
]
Expand Down
13 changes: 12 additions & 1 deletion src/tile_ble/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
"""Asynchronous Python client for Tile trackers over Bluetooth."""

from .cloud import TileCloudTile, async_get_tiles
from .const import TILE_SERVICE_UUID, TileVolume
from .device import TileBleDevice, async_read_tile_id
from .exceptions import TileBleAuthenticationError, TileBleConnectionError, TileBleError
from .exceptions import (
TileBleAuthenticationError,
TileBleConnectionError,
TileBleError,
TileCloudAuthenticationError,
TileCloudError,
)
from .protocol import address_matches_tile_id

__all__ = [
Expand All @@ -11,7 +18,11 @@
"TileBleConnectionError",
"TileBleDevice",
"TileBleError",
"TileCloudAuthenticationError",
"TileCloudError",
"TileCloudTile",
"TileVolume",
"address_matches_tile_id",
"async_get_tiles",
"async_read_tile_id",
]
100 changes: 100 additions & 0 deletions src/tile_ble/cloud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Fetch Tile auth keys from the Tile cloud."""

from __future__ import annotations

import asyncio
from dataclasses import dataclass
from http import HTTPStatus
from typing import TYPE_CHECKING, Any
from uuid import uuid4

from aiohttp import ClientError, ClientResponseError

from .exceptions import TileCloudAuthenticationError, TileCloudError

if TYPE_CHECKING:
from aiohttp import ClientSession

API_URL = "https://production.tile-api.com/api/v1"
API_VERSION = "1.0"
APP_ID = "ios-tile-production"
APP_VERSION = "2.89.1.4774"
USER_AGENT = "Tile/4774 CFNetwork/1312 Darwin/21.0.0"


@dataclass(frozen=True, slots=True)
class TileCloudTile:
"""A Tile as the Tile cloud lists it."""

tile_id: str
name: str
auth_key: str | None


async def async_get_tiles(
session: ClientSession, email: str, password: str, *, locale: str = "en-US"
) -> list[TileCloudTile]:
"""Log in to the Tile cloud and return the Tiles of the account."""
client_uuid = str(uuid4())

async def request(method: str, endpoint: str, **kwargs: Any) -> Any:
headers = {
"User-Agent": USER_AGENT,
"tile_api_version": API_VERSION,
"tile_app_id": APP_ID,
"tile_app_version": APP_VERSION,
"tile_client_uuid": client_uuid,
}
try:
async with session.request(
method, f"{API_URL}/{endpoint}", headers=headers, **kwargs
) as resp:
resp.raise_for_status()
result = (await resp.json())["result"]
except ClientResponseError as err:
if err.status == HTTPStatus.UNAUTHORIZED:
msg = "Invalid Tile credentials"
raise TileCloudAuthenticationError(msg) from err
msg = f"Error requesting {endpoint}: {err}"
raise TileCloudError(msg) from err
except (ClientError, TimeoutError) as err:
msg = f"Error requesting {endpoint}: {err}"
raise TileCloudError(msg) from err
return result

await request(
"put",
f"clients/{client_uuid}",
data={"app_id": APP_ID, "app_version": APP_VERSION, "locale": locale},
)
await request(
"post",
f"clients/{client_uuid}/sessions",
data={"email": email, "password": password},
)

async def details(tile_id: str) -> dict[str, Any] | None:
try:
result: dict[str, Any] = await request("get", f"tiles/{tile_id}")
except TileCloudError as err:
# Tile Labels return HTTP 412 because they have no details.
if (
isinstance(err.__cause__, ClientResponseError)
and err.__cause__.status == HTTPStatus.PRECONDITION_FAILED
):
return None
raise
return result

states = await request("get", "tiles/tile_states")
# The state list holds no auth key, so each Tile needs its own details request.
results = await asyncio.gather(*(details(state["tile_id"]) for state in states))
return [
TileCloudTile(
tile_id=result["tile_uuid"],
name=result["name"],
auth_key=result.get("auth_key"),
)
for result in results
if result is not None
]
8 changes: 8 additions & 0 deletions src/tile_ble/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,11 @@ class TileBleConnectionError(TileBleError):

class TileBleAuthenticationError(TileBleError):
"""Raised when the Tile rejects the auth key."""


class TileCloudError(TileBleError):
"""Raised when a Tile cloud request fails."""


class TileCloudAuthenticationError(TileCloudError):
"""Raised when the Tile cloud rejects the credentials."""
102 changes: 102 additions & 0 deletions tests/test_cloud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Tests for fetching auth keys from the Tile cloud."""

from __future__ import annotations

from typing import TYPE_CHECKING

from aiohttp import ClientSession, web
from aiohttp.test_utils import TestServer
import pytest

from tile_ble import (
TileCloudAuthenticationError,
TileCloudError,
TileCloudTile,
async_get_tiles,
)

if TYPE_CHECKING:
from collections.abc import AsyncIterator

AUTH_KEY = "AAECAwQFBgcICQoLDA0ODw=="


def _ok(result: object) -> web.Response:
return web.json_response({"result": result})


async def _client(_: web.Request) -> web.Response:
return _ok({})


async def _session(request: web.Request) -> web.Response:
if (await request.post())["password"] != "secret":
raise web.HTTPUnauthorized
return _ok({})


async def _details(request: web.Request) -> web.Response:
tile_id = request.match_info["tile_id"]
if tile_id == "19264d2dffdbca32":
return _ok({"tile_uuid": tile_id, "name": "Wallet", "auth_key": AUTH_KEY})
if tile_id == "aaaaaaaaaaaaaaaa":
return _ok({"tile_uuid": tile_id, "name": "Keys"})
if tile_id == "bbbbbbbbbbbbbbbb":
raise web.HTTPPreconditionFailed
raise web.HTTPInternalServerError


@pytest.fixture(name="tile_ids")
def tile_ids_fixture() -> list[str]:
"""Return the Tile IDs the fake Tile cloud lists."""
return ["19264d2dffdbca32", "aaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbb"]


@pytest.fixture(name="session")
async def session_fixture(
monkeypatch: pytest.MonkeyPatch, tile_ids: list[str]
) -> AsyncIterator[ClientSession]:
"""Return a session pointed at a fake Tile cloud."""

async def _states(_: web.Request) -> web.Response:
return _ok([{"tile_id": tile_id} for tile_id in tile_ids])

app = web.Application()
app.router.add_put("/clients/{client_uuid}", _client)
app.router.add_post("/clients/{client_uuid}/sessions", _session)
app.router.add_get("/tiles/tile_states", _states)
app.router.add_get("/tiles/{tile_id}", _details)
async with TestServer(app) as server, ClientSession() as client_session:
monkeypatch.setattr(
"tile_ble.cloud.API_URL", str(server.make_url("")).rstrip("/")
)
yield client_session


async def test_get_tiles(session: ClientSession) -> None:
"""Test Tiles are returned with their auth keys and labels are skipped."""
assert await async_get_tiles(session, "user@example.com", "secret") == [
TileCloudTile("19264d2dffdbca32", "Wallet", AUTH_KEY),
TileCloudTile("aaaaaaaaaaaaaaaa", "Keys", None),
]


async def test_invalid_credentials(session: ClientSession) -> None:
"""Test a 401 on login raises an authentication error."""
with pytest.raises(TileCloudAuthenticationError):
await async_get_tiles(session, "user@example.com", "wrong")


@pytest.mark.parametrize("tile_ids", [["cccccccccccccccc"]])
async def test_details_error(session: ClientSession) -> None:
"""Test a failed details request other than 412 raises."""
with pytest.raises(TileCloudError):
await async_get_tiles(session, "user@example.com", "secret")


async def test_connection_error(monkeypatch: pytest.MonkeyPatch) -> None:
"""Test a connection error raises a cloud error."""
monkeypatch.setattr("tile_ble.cloud.API_URL", "http://127.0.0.1:1")
async with ClientSession() as session:
with pytest.raises(TileCloudError):
await async_get_tiles(session, "user@example.com", "secret")
Loading
Loading