tile-ble 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tile_ble/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """Asynchronous Python client for Tile trackers over Bluetooth."""
2
+
3
+ from .const import TILE_SERVICE_UUID, TileVolume
4
+ from .device import TileBleDevice, async_read_tile_id
5
+ from .exceptions import TileBleAuthenticationError, TileBleConnectionError, TileBleError
6
+ from .protocol import address_matches_tile_id
7
+
8
+ __all__ = [
9
+ "TILE_SERVICE_UUID",
10
+ "TileBleAuthenticationError",
11
+ "TileBleConnectionError",
12
+ "TileBleDevice",
13
+ "TileBleError",
14
+ "TileVolume",
15
+ "address_matches_tile_id",
16
+ "async_read_tile_id",
17
+ ]
tile_ble/const.py ADDED
@@ -0,0 +1,94 @@
1
+ """Constants for Tile BLE."""
2
+
3
+ from enum import IntEnum
4
+
5
+ TILE_SERVICE_UUID = "0000feed-0000-1000-8000-00805f9b34fb"
6
+ TOA_CMD_CHAR_UUID = "9d410018-35d6-f4dd-ba60-e7bd8dc491c0"
7
+ TOA_RSP_CHAR_UUID = "9d410019-35d6-f4dd-ba60-e7bd8dc491c0"
8
+ # Only Tiles that use a Private ID have this characteristic.
9
+ TILE_ID_CHAR_UUID = "9d410007-35d6-f4dd-ba60-e7bd8dc491c0"
10
+
11
+ CONNECTIONLESS_CID = 0
12
+ AUTH_KEY_LEN = 16
13
+ SESSION_KEY_LEN = 16
14
+ TOKEN_LEN = 4
15
+ RAND_A_LEN = 14
16
+ RAND_T_LEN = 13
17
+ MIC_LEN = 4
18
+ TILE_ID_LEN = 8
19
+
20
+ # Maximum payload size the client announces in its READY command.
21
+ CLIENT_MPS = 0x13
22
+
23
+ TILE_SONG_FIND = 0x01
24
+
25
+ # Bit in the TDI AVAILABLE response that is set when the Tile can send its Tile ID.
26
+ TDI_TILE_ID_AVAILABLE = 0x01
27
+
28
+ RESPONSE_TIMEOUT = 10.0
29
+
30
+
31
+ class ToaCommand(IntEnum):
32
+ """Commands sent by the client."""
33
+
34
+ SONG = 0x05
35
+ OPEN_CHANNEL = 0x10
36
+ CLOSE_CHANNEL = 0x11
37
+ READY = 0x12
38
+ TDI = 0x13
39
+ AUTHENTICATE = 0x14
40
+
41
+
42
+ class ToaResponse(IntEnum):
43
+ """Responses sent by the Tile."""
44
+
45
+ READY = 0x01
46
+ ERROR = 0x05
47
+ SONG = 0x07
48
+ OPEN_CHANNEL = 0x12
49
+ CLOSE_CHANNEL = 0x13
50
+ TDI = 0x14
51
+ AUTHENTICATE = 0x15
52
+
53
+
54
+ class SongCommand(IntEnum):
55
+ """Song sub-commands."""
56
+
57
+ PLAY = 0x02
58
+
59
+
60
+ class SongResponse(IntEnum):
61
+ """Song sub-responses."""
62
+
63
+ PLAY_OK = 0x02
64
+ ERROR = 0x20
65
+
66
+
67
+ class TdiCommand(IntEnum):
68
+ """Tile Data Information sub-commands."""
69
+
70
+ AVAILABLE = 0x01
71
+ TILE_ID = 0x02
72
+
73
+
74
+ class TdiResponse(IntEnum):
75
+ """Tile Data Information sub-responses."""
76
+
77
+ ERROR = 0x20
78
+
79
+
80
+ class CloseReason(IntEnum):
81
+ """Reasons the Tile gives for closing a channel."""
82
+
83
+ NO_ERROR = 0x00
84
+ MIC_FAILURE = 0x01
85
+ TKA_MISSING = 0x02
86
+ BROADCAST_MIC_FAILURE = 0x03
87
+
88
+
89
+ class TileVolume(IntEnum):
90
+ """Volume used when ringing a Tile."""
91
+
92
+ LOW = 1
93
+ MEDIUM = 2
94
+ HIGH = 3
tile_ble/device.py ADDED
@@ -0,0 +1,271 @@
1
+ """Asynchronous Python client for Tile trackers over Bluetooth."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from contextlib import asynccontextmanager, suppress
7
+ import logging
8
+ import os
9
+ from typing import TYPE_CHECKING
10
+
11
+ from bleak import BleakClient
12
+ from bleak.exc import BleakError
13
+ from bleak_retry_connector import establish_connection
14
+
15
+ from tile_ble.const import (
16
+ CLIENT_MPS,
17
+ CONNECTIONLESS_CID,
18
+ RAND_A_LEN,
19
+ RAND_T_LEN,
20
+ RESPONSE_TIMEOUT,
21
+ TDI_TILE_ID_AVAILABLE,
22
+ TILE_ID_CHAR_UUID,
23
+ TILE_SONG_FIND,
24
+ TOA_CMD_CHAR_UUID,
25
+ TOA_RSP_CHAR_UUID,
26
+ TOKEN_LEN,
27
+ CloseReason,
28
+ SongCommand,
29
+ SongResponse,
30
+ TdiCommand,
31
+ TileVolume,
32
+ ToaCommand,
33
+ ToaResponse,
34
+ )
35
+ from tile_ble.exceptions import (
36
+ TileBleAuthenticationError,
37
+ TileBleConnectionError,
38
+ TileBleError,
39
+ )
40
+ from tile_ble.protocol import (
41
+ ToaMessage,
42
+ build_channel_frame,
43
+ build_connectionless_frame,
44
+ compute_sres,
45
+ decode_auth_key,
46
+ derive_session_key,
47
+ parse_channel_frame,
48
+ parse_connectionless_frame,
49
+ parse_tdi_response,
50
+ parse_tile_id,
51
+ )
52
+
53
+ if TYPE_CHECKING:
54
+ from collections.abc import AsyncIterator
55
+
56
+ from bleak.backends.characteristic import BleakGATTCharacteristic
57
+ from bleak.backends.device import BLEDevice
58
+
59
+ _LOGGER = logging.getLogger(__package__)
60
+
61
+
62
+ class _Channel:
63
+ """A TOA channel on a connected Tile.
64
+
65
+ Until a channel is open, the client talks on the connectionless CID.
66
+ """
67
+
68
+ def __init__(self, client: BleakClient) -> None:
69
+ self._client = client
70
+ self._token = os.urandom(TOKEN_LEN)
71
+ self._cid = CONNECTIONLESS_CID
72
+ self._session_key = b""
73
+ self._nonce = 0
74
+ self._closed = False
75
+ self._waiters: dict[int, asyncio.Future[ToaMessage]] = {}
76
+
77
+ def handle_notification(
78
+ self, _characteristic: BleakGATTCharacteristic, data: bytearray
79
+ ) -> None:
80
+ """Dispatch a response from the Tile to the request waiting for it."""
81
+ frame = bytes(data)
82
+ if self._cid == CONNECTIONLESS_CID:
83
+ message = parse_connectionless_frame(frame, self._token)
84
+ else:
85
+ message = parse_channel_frame(frame, self._cid)
86
+ if message is None:
87
+ return
88
+
89
+ if message.code == ToaResponse.CLOSE_CHANNEL:
90
+ self._closed = True
91
+ reason = message.payload[0] if message.payload else None
92
+ if reason == CloseReason.MIC_FAILURE:
93
+ self._fail_waiters(
94
+ TileBleAuthenticationError("The Tile rejected the auth key")
95
+ )
96
+ else:
97
+ self._fail_waiters(
98
+ TileBleError(f"The Tile closed the channel: {reason}")
99
+ )
100
+ return
101
+ if message.code == ToaResponse.ERROR:
102
+ self._fail_waiters(
103
+ TileBleError(f"The Tile returned an error: {message.payload.hex()}")
104
+ )
105
+ return
106
+
107
+ if (waiter := self._waiters.pop(message.code, None)) and not waiter.done():
108
+ waiter.set_result(message)
109
+
110
+ def _fail_waiters(self, err: TileBleError) -> None:
111
+ for waiter in self._waiters.values():
112
+ if not waiter.done():
113
+ waiter.set_exception(err)
114
+ self._waiters.clear()
115
+
116
+ async def _send(self, frame: bytes, response: ToaResponse) -> ToaMessage:
117
+ waiter: asyncio.Future[ToaMessage] = asyncio.get_running_loop().create_future()
118
+ self._waiters[response] = waiter
119
+ try:
120
+ await self._client.write_gatt_char(TOA_CMD_CHAR_UUID, frame, response=False)
121
+ async with asyncio.timeout(RESPONSE_TIMEOUT):
122
+ return await waiter
123
+ except TimeoutError as err:
124
+ msg = f"Timed out waiting for {response.name} from the Tile"
125
+ raise TileBleConnectionError(msg) from err
126
+ finally:
127
+ self._waiters.pop(response, None)
128
+
129
+ async def _send_connectionless(
130
+ self, command: ToaCommand, payload: bytes, response: ToaResponse
131
+ ) -> ToaMessage:
132
+ frame = build_connectionless_frame(self._token, command, payload)
133
+ return await self._send(frame, response)
134
+
135
+ async def request(self, message: bytes, response: ToaResponse) -> ToaMessage:
136
+ """Send a signed message on the channel and wait for the response."""
137
+ self._nonce += 1
138
+ frame = build_channel_frame(self._cid, self._session_key, self._nonce, message)
139
+ return await self._send(frame, response)
140
+
141
+ async def open(self, auth_key: bytes) -> None:
142
+ """Authenticate and open a channel."""
143
+ rand_a = os.urandom(RAND_A_LEN)
144
+ authenticated = await self._send_connectionless(
145
+ ToaCommand.AUTHENTICATE, rand_a, ToaResponse.AUTHENTICATE
146
+ )
147
+ rand_t, sres = authenticated.payload[:10], authenticated.payload[10:14]
148
+ # Only logged: the channel handshake below is what proves the key.
149
+ _LOGGER.debug(
150
+ "Tile SRES %s the auth key",
151
+ "matches"
152
+ if sres == compute_sres(auth_key, rand_a, rand_t)
153
+ else "does not match",
154
+ )
155
+
156
+ opened = await self._send_connectionless(
157
+ ToaCommand.OPEN_CHANNEL, rand_a, ToaResponse.OPEN_CHANNEL
158
+ )
159
+ if len(opened.payload) < 1 + RAND_T_LEN:
160
+ msg = "The Tile sent an invalid OPEN_CHANNEL response"
161
+ raise TileBleError(msg)
162
+ cid = opened.payload[0]
163
+ self._session_key = derive_session_key(
164
+ auth_key, rand_a, opened.payload[1 : 1 + RAND_T_LEN], cid, self._token
165
+ )
166
+ self._cid = cid
167
+ await self.request(bytes([ToaCommand.READY, CLIENT_MPS]), ToaResponse.READY)
168
+
169
+ async def read_tile_id(self) -> str:
170
+ """Request the Tile ID with connectionless TDI commands."""
171
+ available = parse_tdi_response(
172
+ await self._send_connectionless(
173
+ ToaCommand.TDI, bytes([TdiCommand.AVAILABLE]), ToaResponse.TDI
174
+ )
175
+ )
176
+ if not available or not available[0] & TDI_TILE_ID_AVAILABLE:
177
+ msg = "The Tile does not provide its Tile ID"
178
+ raise TileBleError(msg)
179
+ tile_id = parse_tdi_response(
180
+ await self._send_connectionless(
181
+ ToaCommand.TDI, bytes([TdiCommand.TILE_ID]), ToaResponse.TDI
182
+ )
183
+ )
184
+ return parse_tile_id(tile_id)
185
+
186
+ async def close(self) -> None:
187
+ """Close the channel if it is still open."""
188
+ if self._cid == CONNECTIONLESS_CID or self._closed:
189
+ return
190
+ self._closed = True
191
+ self._nonce += 1
192
+ frame = build_channel_frame(
193
+ self._cid,
194
+ self._session_key,
195
+ self._nonce,
196
+ bytes([ToaCommand.CLOSE_CHANNEL, CloseReason.NO_ERROR]),
197
+ )
198
+ await self._client.write_gatt_char(TOA_CMD_CHAR_UUID, frame, response=False)
199
+
200
+
201
+ @asynccontextmanager
202
+ async def _connect(ble_device: BLEDevice) -> AsyncIterator[BleakClient]:
203
+ """Connect to the Tile and raise Bluetooth errors as TileBleConnectionError."""
204
+ try:
205
+ client = await establish_connection(
206
+ BleakClient, ble_device, ble_device.name or ble_device.address
207
+ )
208
+ except (BleakError, TimeoutError) as err:
209
+ msg = f"Could not connect to the Tile: {err}"
210
+ raise TileBleConnectionError(msg) from err
211
+
212
+ try:
213
+ yield client
214
+ except BleakError as err:
215
+ msg = f"Could not communicate with the Tile: {err}"
216
+ raise TileBleConnectionError(msg) from err
217
+ finally:
218
+ with suppress(BleakError):
219
+ await client.disconnect()
220
+
221
+
222
+ @asynccontextmanager
223
+ async def _listen(client: BleakClient) -> AsyncIterator[_Channel]:
224
+ """Receive TOA responses on a channel, and close the channel on exit."""
225
+ channel = _Channel(client)
226
+ try:
227
+ await client.start_notify(TOA_RSP_CHAR_UUID, channel.handle_notification)
228
+ yield channel
229
+ finally:
230
+ with suppress(BleakError):
231
+ await channel.close()
232
+
233
+
234
+ class TileBleDevice:
235
+ """A Tile that can be reached over Bluetooth."""
236
+
237
+ def __init__(self, ble_device: BLEDevice, auth_key: str) -> None:
238
+ """Initialize the device with the base64 auth key from the Tile cloud."""
239
+ self._ble_device = ble_device
240
+ self._auth_key = decode_auth_key(auth_key)
241
+
242
+ @asynccontextmanager
243
+ async def _channel(self) -> AsyncIterator[_Channel]:
244
+ async with _connect(self._ble_device) as client, _listen(client) as channel:
245
+ await channel.open(self._auth_key)
246
+ yield channel
247
+
248
+ async def async_authenticate(self) -> None:
249
+ """Check that the auth key belongs to this Tile."""
250
+ async with self._channel():
251
+ pass
252
+
253
+ async def async_ring(self, volume: TileVolume = TileVolume.HIGH) -> None:
254
+ """Make the Tile play its find song."""
255
+ async with self._channel() as channel:
256
+ response = await channel.request(
257
+ bytes([ToaCommand.SONG, SongCommand.PLAY, TILE_SONG_FIND, volume]),
258
+ ToaResponse.SONG,
259
+ )
260
+ if response.payload[:1] != bytes([SongResponse.PLAY_OK]):
261
+ msg = f"The Tile refused to ring: {response.payload.hex()}"
262
+ raise TileBleError(msg)
263
+
264
+
265
+ async def async_read_tile_id(ble_device: BLEDevice) -> str:
266
+ """Return the Tile ID of a Tile as hex. This does not need an auth key."""
267
+ async with _connect(ble_device) as client:
268
+ if characteristic := client.services.get_characteristic(TILE_ID_CHAR_UUID):
269
+ return parse_tile_id(bytes(await client.read_gatt_char(characteristic)))
270
+ async with _listen(client) as channel:
271
+ return await channel.read_tile_id()
tile_ble/exceptions.py ADDED
@@ -0,0 +1,13 @@
1
+ """Asynchronous Python client for Tile trackers over Bluetooth."""
2
+
3
+
4
+ class TileBleError(Exception):
5
+ """Base exception for talking to a Tile over Bluetooth."""
6
+
7
+
8
+ class TileBleConnectionError(TileBleError):
9
+ """Raised when the Tile cannot be reached or does not respond."""
10
+
11
+
12
+ class TileBleAuthenticationError(TileBleError):
13
+ """Raised when the Tile rejects the auth key."""
tile_ble/protocol.py ADDED
@@ -0,0 +1,138 @@
1
+ """Tile Over-the-Air (TOA) protocol, used to talk to a Tile over Bluetooth.
2
+
3
+ The protocol is undocumented; this follows node-tile
4
+ (https://github.com/lesleyxyz/node-tile, MIT, Copyright (c) 2024 Lesley De Keyser).
5
+ """
6
+
7
+ import base64
8
+ import binascii
9
+ from dataclasses import dataclass
10
+ import hashlib
11
+ import hmac
12
+
13
+ from tile_ble.const import (
14
+ AUTH_KEY_LEN,
15
+ CONNECTIONLESS_CID,
16
+ MIC_LEN,
17
+ SESSION_KEY_LEN,
18
+ TILE_ID_LEN,
19
+ TdiResponse,
20
+ )
21
+ from tile_ble.exceptions import TileBleError
22
+
23
+ _HMAC_INPUT_LEN = 32
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class ToaMessage:
28
+ """A response received from the Tile."""
29
+
30
+ code: int
31
+ payload: bytes
32
+
33
+
34
+ def _hmac_sha256(key: bytes, *parts: bytes) -> bytes:
35
+ """Return HMAC-SHA256 over the parts, zero-padded or truncated to 32 bytes."""
36
+ data = b"".join(parts)[:_HMAC_INPUT_LEN].ljust(_HMAC_INPUT_LEN, b"\x00")
37
+ return hmac.new(key, data, hashlib.sha256).digest()
38
+
39
+
40
+ def decode_auth_key(auth_key: str) -> bytes:
41
+ """Decode the base64 auth key provided by the Tile cloud API."""
42
+ try:
43
+ key = base64.b64decode(auth_key, validate=True)
44
+ except binascii.Error as err:
45
+ msg = "Auth key is not valid base64"
46
+ raise ValueError(msg) from err
47
+ if len(key) != AUTH_KEY_LEN:
48
+ msg = f"Auth key must be {AUTH_KEY_LEN} bytes, got {len(key)}"
49
+ raise ValueError(msg)
50
+ return key
51
+
52
+
53
+ def compute_sres(auth_key: bytes, rand_a: bytes, rand_t: bytes) -> bytes:
54
+ """Return the SRES the Tile sends in its AUTHENTICATE response."""
55
+ data = rand_a.ljust(16, b"\x00") + rand_t.ljust(16, b"\x00")
56
+ return hmac.new(auth_key, data, hashlib.sha256).digest()[4:8]
57
+
58
+
59
+ def derive_session_key(
60
+ auth_key: bytes, rand_a: bytes, rand_t: bytes, cid: int, token: bytes
61
+ ) -> bytes:
62
+ """Derive the key used to sign messages on an open channel."""
63
+ return _hmac_sha256(auth_key, rand_a, rand_t, bytes([cid]), token)[:SESSION_KEY_LEN]
64
+
65
+
66
+ def compute_mic(session_key: bytes, nonce: int, message: bytes) -> bytes:
67
+ """Return the message integrity code for a channel message."""
68
+ return _hmac_sha256(
69
+ session_key,
70
+ nonce.to_bytes(8, "little"),
71
+ bytes([0x01, len(message)]),
72
+ message,
73
+ )[:MIC_LEN]
74
+
75
+
76
+ def build_connectionless_frame(token: bytes, command: int, payload: bytes) -> bytes:
77
+ """Build a frame for the connectionless channel."""
78
+ return bytes([CONNECTIONLESS_CID]) + token + bytes([command]) + payload
79
+
80
+
81
+ def build_channel_frame(
82
+ cid: int, session_key: bytes, nonce: int, message: bytes
83
+ ) -> bytes:
84
+ """Build a signed frame for an open channel."""
85
+ return bytes([cid]) + message + compute_mic(session_key, nonce, message)
86
+
87
+
88
+ def parse_connectionless_frame(data: bytes, token: bytes) -> ToaMessage | None:
89
+ """Parse a connectionless response addressed to this client."""
90
+ if len(data) < 6 or data[0] != CONNECTIONLESS_CID or data[1:5] != token:
91
+ return None
92
+ return ToaMessage(data[5], data[6:])
93
+
94
+
95
+ def parse_channel_frame(data: bytes, cid: int) -> ToaMessage | None:
96
+ """Parse a response on an open channel.
97
+
98
+ The trailing MIC is stripped but not verified, as the Tile's signing scheme
99
+ for responses is not documented.
100
+ """
101
+ if len(data) < 2 + MIC_LEN or data[0] != cid:
102
+ return None
103
+ return ToaMessage(data[1], data[2:-MIC_LEN])
104
+
105
+
106
+ def parse_tdi_response(message: ToaMessage) -> bytes:
107
+ """Return the data of a TDI response, without its sub-response code."""
108
+ if not message.payload or message.payload[0] == TdiResponse.ERROR:
109
+ msg = f"The Tile returned a TDI error: {message.payload.hex()}"
110
+ raise TileBleError(msg)
111
+ return message.payload[1:]
112
+
113
+
114
+ def parse_tile_id(data: bytes) -> str:
115
+ """Return the Tile ID sent by the Tile as hex."""
116
+ if len(data) != TILE_ID_LEN:
117
+ msg = f"The Tile sent an invalid Tile ID: {data.hex()}"
118
+ raise TileBleError(msg)
119
+ return data.hex()
120
+
121
+
122
+ def address_matches_tile_id(address: str, tile_id: str) -> bool:
123
+ """Return whether a Bluetooth address belongs to the Tile with this Tile ID.
124
+
125
+ Older Tiles use the first 6 bytes of their Tile ID as address. Tiles with a
126
+ Private ID set the two highest bits of the first byte, as Bluetooth requires
127
+ for a static random address. That rule is inferred from two Tiles only:
128
+ Tile ID 5176… uses D1:76…, and Tile ID b9b4… uses F9:B4….
129
+ """
130
+ try:
131
+ mac = bytes.fromhex(address.replace(":", ""))
132
+ tile = bytes.fromhex(tile_id)
133
+ except ValueError:
134
+ return False
135
+ if len(mac) != 6 or len(tile) != TILE_ID_LEN:
136
+ return False
137
+ prefix = tile[:6]
138
+ return mac in (prefix, bytes([prefix[0] | 0xC0]) + prefix[1:])
tile_ble/py.typed ADDED
File without changes
@@ -0,0 +1,245 @@
1
+ Metadata-Version: 2.5
2
+ Name: tile-ble
3
+ Version: 0.0.1
4
+ Summary: Asynchronous Python client for Tile trackers over Bluetooth.
5
+ Project-URL: Homepage, https://github.com/joostlek/python-tile-ble
6
+ Project-URL: Repository, https://github.com/joostlek/python-tile-ble
7
+ Project-URL: Documentation, https://github.com/joostlek/python-tile-ble
8
+ Project-URL: Bug Tracker, https://github.com/joostlek/python-tile-ble/issues
9
+ Project-URL: Changelog, https://github.com/joostlek/python-tile-ble/releases
10
+ Author-email: Joost Lekkerkerker <joostlek@outlook.com>
11
+ Maintainer-email: Joost Lekkerkerker <joostlek@outlook.com>
12
+ License-Expression: MIT
13
+ License-File: LICENSE.md
14
+ Keywords: async,ble,bluetooth,client,tile
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Framework :: AsyncIO
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Natural Language :: English
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: <4,>=3.13
24
+ Requires-Dist: bleak-retry-connector>=3.5.0
25
+ Requires-Dist: bleak>=0.22.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # Python: Tile BLE
29
+
30
+ [![GitHub Release][releases-shield]][releases]
31
+ [![Python Versions][python-versions-shield]][pypi]
32
+ ![Project Stage][project-stage-shield]
33
+ ![Project Maintenance][maintenance-shield]
34
+ [![License][license-shield]](LICENSE.md)
35
+
36
+ [![Build Status][build-shield]][build]
37
+ [![Code Coverage][codecov-shield]][codecov]
38
+
39
+ Asynchronous Python client for Tile trackers over Bluetooth.
40
+
41
+ ## About
42
+
43
+ This package talks to a Tile over Bluetooth Low Energy with [bleak][bleak]. It can:
44
+
45
+ - check that an auth key belongs to a Tile;
46
+ - make a Tile ring;
47
+ - read the Tile ID of a Tile, without an auth key.
48
+
49
+ This package is not affiliated with, endorsed by, or connected to Tile or Life360.
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install tile-ble
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ 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.
60
+
61
+ ```python
62
+ import asyncio
63
+
64
+ from bleak import BleakScanner
65
+
66
+ from tile_ble import TileBleDevice, TileVolume
67
+
68
+
69
+ async def main() -> None:
70
+ """Ring a Tile."""
71
+ ble_device = await BleakScanner.find_device_by_address("D1:76:AA:BB:CC:DD")
72
+ assert ble_device is not None
73
+
74
+ tile = TileBleDevice(ble_device, "AAECAwQFBgcICQoLDA0ODw==")
75
+ await tile.async_authenticate()
76
+ await tile.async_ring(volume=TileVolume.MEDIUM)
77
+
78
+
79
+ if __name__ == "__main__":
80
+ asyncio.run(main())
81
+ ```
82
+
83
+ `async_authenticate()` proves that the key belongs to this Tile. It does not ring the Tile.
84
+
85
+ Tiles advertise the `TILE_SERVICE_UUID` service. Use it to find Tiles in a scan.
86
+
87
+ ### Find which Tile is which
88
+
89
+ The Tile cloud lists each Tile with its Tile ID. You can match a Tile ID to a Bluetooth address without a connection:
90
+
91
+ ```python
92
+ from tile_ble import address_matches_tile_id
93
+
94
+ address_matches_tile_id("D1:76:AA:BB:CC:DD", "5176aabbccdd0102") # True
95
+ ```
96
+
97
+ You can also connect to a Tile and read its Tile ID. This does not need an auth key:
98
+
99
+ ```python
100
+ from tile_ble import async_read_tile_id
101
+
102
+ tile_id = await async_read_tile_id(ble_device)
103
+ ```
104
+
105
+ ### Exceptions
106
+
107
+ All exceptions derive from `TileBleError`.
108
+
109
+ | Exception | Raised when |
110
+ | ---------------------------- | -------------------------------------------------------------------- |
111
+ | `TileBleConnectionError` | The Tile cannot be reached, a Bluetooth call fails, or it times out. |
112
+ | `TileBleAuthenticationError` | The Tile rejects the auth key. |
113
+ | `TileBleError` | The Tile returns an error, or refuses to ring. |
114
+
115
+ `TileBleDevice` raises `ValueError` when the auth key is not a 16-byte base64 value.
116
+
117
+ ## Known limitations
118
+
119
+ - Only Tiles that support multi-endpoint TOA are supported.
120
+ - Newer Tiles (firmware 48.x) are reported to fail to enable notifications under BlueZ.
121
+ - It is unknown whether a Tile accepts a connection while the phone of the owner is connected to it.
122
+ - There is no command to stop a ring. A ring stops by itself after a time-out.
123
+ - The protocol is not documented. Tile can change it at any time.
124
+ - `address_matches_tile_id()` uses a rule for Tiles with a Private ID that is inferred from two Tiles only.
125
+
126
+ ## Credits
127
+
128
+ The protocol implementation follows [node-tile][node-tile], MIT License, Copyright (c) 2024 Lesley De Keyser. [jeretile][jeretile] uses the same sequence. The Tile header `toa.h` in the Nordic nRF5 SDK 16 and the paper ["Security and Privacy Analysis of Tile's Location Tracking Protocol"][paper] also document parts of the protocol.
129
+
130
+ ## Changelog & Releases
131
+
132
+ This repository keeps a change log using [GitHub's releases][releases]
133
+ functionality. The format of the log is based on
134
+ [Keep a Changelog][keepchangelog].
135
+
136
+ Releases are based on [Semantic Versioning][semver], and use the format
137
+ of `MAJOR.MINOR.PATCH`. In a nutshell, the version will be incremented
138
+ based on the following:
139
+
140
+ - `MAJOR`: Incompatible or major changes.
141
+ - `MINOR`: Backwards-compatible new features and enhancements.
142
+ - `PATCH`: Backwards-compatible bugfixes and package updates.
143
+
144
+ ## Contributing
145
+
146
+ This is an active open-source project. We are always open to people who want to
147
+ use the code or contribute to it.
148
+
149
+ We've set up a separate document for our
150
+ [contribution guidelines](.github/CONTRIBUTING.md).
151
+
152
+ Thank you for being involved! :heart_eyes:
153
+
154
+ ## Setting up development environment
155
+
156
+ This Python project is fully managed using the [uv][uv] dependency manager. But also relies on the use of NodeJS for certain checks during development.
157
+
158
+ You need at least:
159
+
160
+ - Python 3.13+
161
+ - [uv][uv-install]
162
+ - NodeJS 12+ (including NPM)
163
+
164
+ To install all packages, including all development requirements:
165
+
166
+ ```bash
167
+ npm install
168
+ uv sync --all-groups
169
+ ```
170
+
171
+ As this repository uses the [prek][prek] framework, all changes
172
+ are linted and tested with each commit. You can run all checks and tests
173
+ manually, using the following command:
174
+
175
+ ```bash
176
+ uv run prek run --all-files
177
+ ```
178
+
179
+ To run just the Python tests:
180
+
181
+ ```bash
182
+ uv run pytest
183
+ ```
184
+
185
+ ## Authors & contributors
186
+
187
+ The content is by [Joost Lekkerkerker][joostlek].
188
+
189
+ For a full list of all authors and contributors,
190
+ check [the contributor's page][contributors].
191
+
192
+ ## License
193
+
194
+ MIT License
195
+
196
+ Copyright (c) 2026 Joost Lekkerkerker
197
+
198
+ Permission is hereby granted, free of charge, to any person obtaining a copy
199
+ of this software and associated documentation files (the "Software"), to deal
200
+ in the Software without restriction, including without limitation the rights
201
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
202
+ copies of the Software, and to permit persons to whom the Software is
203
+ furnished to do so, subject to the following conditions:
204
+
205
+ The above copyright notice and this permission notice shall be included in all
206
+ copies or substantial portions of the Software.
207
+
208
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
209
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
210
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
211
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
212
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
213
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
214
+ SOFTWARE.
215
+
216
+ The protocol implementation is based on [node-tile][node-tile]. See
217
+ [LICENSE.md](LICENSE.md) for its copyright and permission notice.
218
+
219
+ [bleak]: https://github.com/hbldh/bleak
220
+ [build-shield]: https://github.com/joostlek/python-tile-ble/actions/workflows/tests.yaml/badge.svg
221
+ [build]: https://github.com/joostlek/python-tile-ble/actions
222
+ [codecov-shield]: https://codecov.io/gh/joostlek/python-tile-ble/branch/master/graph/badge.svg
223
+ [codecov]: https://codecov.io/gh/joostlek/python-tile-ble
224
+ [commits-shield]: https://img.shields.io/github/commit-activity/y/joostlek/python-tile-ble.svg
225
+ [commits]: https://github.com/joostlek/python-tile-ble/commits/master
226
+ [contributors]: https://github.com/joostlek/python-tile-ble/graphs/contributors
227
+ [jeretile]: https://github.com/jeremad/jeretile
228
+ [joostlek]: https://github.com/joostlek
229
+ [keepchangelog]: http://keepachangelog.com/en/1.0.0/
230
+ [license-shield]: https://img.shields.io/github/license/joostlek/python-tile-ble.svg
231
+ [maintenance-shield]: https://img.shields.io/maintenance/yes/2026.svg
232
+ [node-tile]: https://github.com/lesleyxyz/node-tile
233
+ [paper]: https://arxiv.org/abs/2510.00350
234
+ [poetry-install]: https://python-poetry.org/docs/#installation
235
+ [poetry]: https://python-poetry.org
236
+ [prek]: https://prek.j178.dev/
237
+ [pytile]: https://github.com/bachya/pytile
238
+ [uv]: https://docs.astral.sh/uv/
239
+ [uv-install]: https://docs.astral.sh/uv/getting-started/installation/
240
+ [project-stage-shield]: https://img.shields.io/badge/project%20stage-beta-yellow.svg
241
+ [python-versions-shield]: https://img.shields.io/pypi/pyversions/tile-ble
242
+ [releases-shield]: https://img.shields.io/github/release/joostlek/python-tile-ble.svg
243
+ [releases]: https://github.com/joostlek/python-tile-ble/releases
244
+ [semver]: http://semver.org/spec/v2.0.0.html
245
+ [pypi]: https://pypi.org/project/tile-ble/
@@ -0,0 +1,10 @@
1
+ tile_ble/__init__.py,sha256=wgOGd9asIyGa-1cI43kNK89LsAOQJEzW6B0LQZ1oA4A,526
2
+ tile_ble/const.py,sha256=05xA_1RgoCjnf_GBzyC_1ttY0TTFPwW70AEDtoUWnqM,1819
3
+ tile_ble/device.py,sha256=xuDx2aSxH0IBuvxavymai4IQ71wxU8SrHSqWWm-n3Is,9689
4
+ tile_ble/exceptions.py,sha256=SpDtAlKSsN0UqLD_fSL_GuLqljul1PbCDhCU2sPDezQ,382
5
+ tile_ble/protocol.py,sha256=BqaG9SrJm7VnanVMFyvq26lDBVYzq2e2tfF_nEKSheM,4665
6
+ tile_ble/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ tile_ble-0.0.1.dist-info/METADATA,sha256=JSmhzSPjC233LlrMKFaMjPwFgmv6FWpP_Tf6QvwB3qU,9308
8
+ tile_ble-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ tile_ble-0.0.1.dist-info/licenses/LICENSE.md,sha256=aQQY0UdiaOlkDCLDvG0wvFxxJjfEXaPAO8RiZ7wk3NI,2279
10
+ tile_ble-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,48 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2026 Joost Lekkerkerker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ The Tile protocol implementation is based on node-tile
26
+ (https://github.com/lesleyxyz/node-tile), which uses this license:
27
+
28
+ MIT License
29
+
30
+ Copyright (c) 2024 Lesley De Keyser
31
+
32
+ Permission is hereby granted, free of charge, to any person obtaining a copy
33
+ of this software and associated documentation files (the "Software"), to deal
34
+ in the Software without restriction, including without limitation the rights
35
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
36
+ copies of the Software, and to permit persons to whom the Software is
37
+ furnished to do so, subject to the following conditions:
38
+
39
+ The above copyright notice and this permission notice shall be included in all
40
+ copies or substantial portions of the Software.
41
+
42
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
45
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
47
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
48
+ SOFTWARE.