tile-ble 0.0.1__tar.gz

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.
@@ -0,0 +1,122 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # OSX useful to ignore
7
+ *.DS_Store
8
+ .AppleDouble
9
+ .LSOverride
10
+
11
+ # Thumbnails
12
+ ._*
13
+
14
+ # Files that might appear in the root of a volume
15
+ .DocumentRevisions-V100
16
+ .fseventsd
17
+ .Spotlight-V100
18
+ .TemporaryItems
19
+ .Trashes
20
+ .VolumeIcon.icns
21
+ .com.apple.timemachine.donotpresent
22
+
23
+ # Directories potentially created on remote AFP share
24
+ .AppleDB
25
+ .AppleDesktop
26
+ Network Trash Folder
27
+ Temporary Items
28
+ .apdisk
29
+
30
+ # C extensions
31
+ *.so
32
+
33
+ # Distribution / packaging
34
+ .Python
35
+ env/
36
+ build/
37
+ develop-eggs/
38
+ dist/
39
+ downloads/
40
+ eggs/
41
+ .eggs/
42
+ lib/
43
+ lib64/
44
+ parts/
45
+ sdist/
46
+ var/
47
+ *.egg-info/
48
+ .installed.cfg
49
+ *.egg
50
+
51
+ # PyInstaller
52
+ # Usually these files are written by a python script from a template
53
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
54
+ *.manifest
55
+ *.spec
56
+
57
+ # Installer logs
58
+ pip-log.txt
59
+ pip-delete-this-directory.txt
60
+
61
+ # Unit test / coverage reports
62
+ htmlcov/
63
+ .tox/
64
+ .coverage
65
+ .coverage.*
66
+ .cache
67
+ nosetests.xml
68
+ coverage.xml
69
+ *,cover
70
+ .hypothesis/
71
+ .pytest_cache/
72
+
73
+ # Translations
74
+ *.mo
75
+ *.pot
76
+
77
+ # Django stuff:
78
+ *.log
79
+
80
+ # Sphinx documentation
81
+ docs/_build/
82
+
83
+ # pyenv
84
+ .python-version
85
+
86
+ # virtualenv
87
+ .venv
88
+ venv/
89
+ ENV/
90
+
91
+ # mypy
92
+ .mypy_cache/
93
+
94
+ # ruff
95
+ .ruff_cache
96
+
97
+ # Visual Studio Code
98
+ .vscode
99
+
100
+ # IntelliJ Idea family of suites
101
+ .idea
102
+ *.iml
103
+
104
+ ## File-based project format:
105
+ *.ipr
106
+ *.iws
107
+
108
+ ## mpeltonen/sbt-idea plugin
109
+ .idea_modules/
110
+
111
+ # PyBuilder
112
+ target/
113
+
114
+ # Cookiecutter
115
+ output/
116
+ python_boilerplate/
117
+
118
+ # Node
119
+ node_modules/
120
+
121
+ # Deepcode AI
122
+ .dccache
@@ -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.
@@ -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,218 @@
1
+ # Python: Tile BLE
2
+
3
+ [![GitHub Release][releases-shield]][releases]
4
+ [![Python Versions][python-versions-shield]][pypi]
5
+ ![Project Stage][project-stage-shield]
6
+ ![Project Maintenance][maintenance-shield]
7
+ [![License][license-shield]](LICENSE.md)
8
+
9
+ [![Build Status][build-shield]][build]
10
+ [![Code Coverage][codecov-shield]][codecov]
11
+
12
+ Asynchronous Python client for Tile trackers over Bluetooth.
13
+
14
+ ## About
15
+
16
+ This package talks to a Tile over Bluetooth Low Energy with [bleak][bleak]. It can:
17
+
18
+ - check that an auth key belongs to a Tile;
19
+ - make a Tile ring;
20
+ - read the Tile ID of a Tile, without an auth key.
21
+
22
+ This package is not affiliated with, endorsed by, or connected to Tile or Life360.
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pip install tile-ble
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ 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.
33
+
34
+ ```python
35
+ import asyncio
36
+
37
+ from bleak import BleakScanner
38
+
39
+ from tile_ble import TileBleDevice, TileVolume
40
+
41
+
42
+ async def main() -> None:
43
+ """Ring a Tile."""
44
+ ble_device = await BleakScanner.find_device_by_address("D1:76:AA:BB:CC:DD")
45
+ assert ble_device is not None
46
+
47
+ tile = TileBleDevice(ble_device, "AAECAwQFBgcICQoLDA0ODw==")
48
+ await tile.async_authenticate()
49
+ await tile.async_ring(volume=TileVolume.MEDIUM)
50
+
51
+
52
+ if __name__ == "__main__":
53
+ asyncio.run(main())
54
+ ```
55
+
56
+ `async_authenticate()` proves that the key belongs to this Tile. It does not ring the Tile.
57
+
58
+ Tiles advertise the `TILE_SERVICE_UUID` service. Use it to find Tiles in a scan.
59
+
60
+ ### Find which Tile is which
61
+
62
+ The Tile cloud lists each Tile with its Tile ID. You can match a Tile ID to a Bluetooth address without a connection:
63
+
64
+ ```python
65
+ from tile_ble import address_matches_tile_id
66
+
67
+ address_matches_tile_id("D1:76:AA:BB:CC:DD", "5176aabbccdd0102") # True
68
+ ```
69
+
70
+ You can also connect to a Tile and read its Tile ID. This does not need an auth key:
71
+
72
+ ```python
73
+ from tile_ble import async_read_tile_id
74
+
75
+ tile_id = await async_read_tile_id(ble_device)
76
+ ```
77
+
78
+ ### Exceptions
79
+
80
+ All exceptions derive from `TileBleError`.
81
+
82
+ | Exception | Raised when |
83
+ | ---------------------------- | -------------------------------------------------------------------- |
84
+ | `TileBleConnectionError` | The Tile cannot be reached, a Bluetooth call fails, or it times out. |
85
+ | `TileBleAuthenticationError` | The Tile rejects the auth key. |
86
+ | `TileBleError` | The Tile returns an error, or refuses to ring. |
87
+
88
+ `TileBleDevice` raises `ValueError` when the auth key is not a 16-byte base64 value.
89
+
90
+ ## Known limitations
91
+
92
+ - Only Tiles that support multi-endpoint TOA are supported.
93
+ - Newer Tiles (firmware 48.x) are reported to fail to enable notifications under BlueZ.
94
+ - It is unknown whether a Tile accepts a connection while the phone of the owner is connected to it.
95
+ - There is no command to stop a ring. A ring stops by itself after a time-out.
96
+ - The protocol is not documented. Tile can change it at any time.
97
+ - `address_matches_tile_id()` uses a rule for Tiles with a Private ID that is inferred from two Tiles only.
98
+
99
+ ## Credits
100
+
101
+ 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.
102
+
103
+ ## Changelog & Releases
104
+
105
+ This repository keeps a change log using [GitHub's releases][releases]
106
+ functionality. The format of the log is based on
107
+ [Keep a Changelog][keepchangelog].
108
+
109
+ Releases are based on [Semantic Versioning][semver], and use the format
110
+ of `MAJOR.MINOR.PATCH`. In a nutshell, the version will be incremented
111
+ based on the following:
112
+
113
+ - `MAJOR`: Incompatible or major changes.
114
+ - `MINOR`: Backwards-compatible new features and enhancements.
115
+ - `PATCH`: Backwards-compatible bugfixes and package updates.
116
+
117
+ ## Contributing
118
+
119
+ This is an active open-source project. We are always open to people who want to
120
+ use the code or contribute to it.
121
+
122
+ We've set up a separate document for our
123
+ [contribution guidelines](.github/CONTRIBUTING.md).
124
+
125
+ Thank you for being involved! :heart_eyes:
126
+
127
+ ## Setting up development environment
128
+
129
+ 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.
130
+
131
+ You need at least:
132
+
133
+ - Python 3.13+
134
+ - [uv][uv-install]
135
+ - NodeJS 12+ (including NPM)
136
+
137
+ To install all packages, including all development requirements:
138
+
139
+ ```bash
140
+ npm install
141
+ uv sync --all-groups
142
+ ```
143
+
144
+ As this repository uses the [prek][prek] framework, all changes
145
+ are linted and tested with each commit. You can run all checks and tests
146
+ manually, using the following command:
147
+
148
+ ```bash
149
+ uv run prek run --all-files
150
+ ```
151
+
152
+ To run just the Python tests:
153
+
154
+ ```bash
155
+ uv run pytest
156
+ ```
157
+
158
+ ## Authors & contributors
159
+
160
+ The content is by [Joost Lekkerkerker][joostlek].
161
+
162
+ For a full list of all authors and contributors,
163
+ check [the contributor's page][contributors].
164
+
165
+ ## License
166
+
167
+ MIT License
168
+
169
+ Copyright (c) 2026 Joost Lekkerkerker
170
+
171
+ Permission is hereby granted, free of charge, to any person obtaining a copy
172
+ of this software and associated documentation files (the "Software"), to deal
173
+ in the Software without restriction, including without limitation the rights
174
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
175
+ copies of the Software, and to permit persons to whom the Software is
176
+ furnished to do so, subject to the following conditions:
177
+
178
+ The above copyright notice and this permission notice shall be included in all
179
+ copies or substantial portions of the Software.
180
+
181
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
182
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
183
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
184
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
185
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
186
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
187
+ SOFTWARE.
188
+
189
+ The protocol implementation is based on [node-tile][node-tile]. See
190
+ [LICENSE.md](LICENSE.md) for its copyright and permission notice.
191
+
192
+ [bleak]: https://github.com/hbldh/bleak
193
+ [build-shield]: https://github.com/joostlek/python-tile-ble/actions/workflows/tests.yaml/badge.svg
194
+ [build]: https://github.com/joostlek/python-tile-ble/actions
195
+ [codecov-shield]: https://codecov.io/gh/joostlek/python-tile-ble/branch/master/graph/badge.svg
196
+ [codecov]: https://codecov.io/gh/joostlek/python-tile-ble
197
+ [commits-shield]: https://img.shields.io/github/commit-activity/y/joostlek/python-tile-ble.svg
198
+ [commits]: https://github.com/joostlek/python-tile-ble/commits/master
199
+ [contributors]: https://github.com/joostlek/python-tile-ble/graphs/contributors
200
+ [jeretile]: https://github.com/jeremad/jeretile
201
+ [joostlek]: https://github.com/joostlek
202
+ [keepchangelog]: http://keepachangelog.com/en/1.0.0/
203
+ [license-shield]: https://img.shields.io/github/license/joostlek/python-tile-ble.svg
204
+ [maintenance-shield]: https://img.shields.io/maintenance/yes/2026.svg
205
+ [node-tile]: https://github.com/lesleyxyz/node-tile
206
+ [paper]: https://arxiv.org/abs/2510.00350
207
+ [poetry-install]: https://python-poetry.org/docs/#installation
208
+ [poetry]: https://python-poetry.org
209
+ [prek]: https://prek.j178.dev/
210
+ [pytile]: https://github.com/bachya/pytile
211
+ [uv]: https://docs.astral.sh/uv/
212
+ [uv-install]: https://docs.astral.sh/uv/getting-started/installation/
213
+ [project-stage-shield]: https://img.shields.io/badge/project%20stage-beta-yellow.svg
214
+ [python-versions-shield]: https://img.shields.io/pypi/pyversions/tile-ble
215
+ [releases-shield]: https://img.shields.io/github/release/joostlek/python-tile-ble.svg
216
+ [releases]: https://github.com/joostlek/python-tile-ble/releases
217
+ [semver]: http://semver.org/spec/v2.0.0.html
218
+ [pypi]: https://pypi.org/project/tile-ble/
@@ -0,0 +1,179 @@
1
+ [project]
2
+ name = "tile-ble"
3
+ version = "0.0.1"
4
+ description = "Asynchronous Python client for Tile trackers over Bluetooth."
5
+ authors = [{ name = "Joost Lekkerkerker", email = "joostlek@outlook.com" }]
6
+ requires-python = ">=3.13,<4"
7
+ readme = "README.md"
8
+ license = "MIT"
9
+ maintainers = [{ name = "Joost Lekkerkerker", email = "joostlek@outlook.com" }]
10
+ keywords = [
11
+ "tile",
12
+ "bluetooth",
13
+ "ble",
14
+ "async",
15
+ "client",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Framework :: AsyncIO",
20
+ "Intended Audience :: Developers",
21
+ "Natural Language :: English",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Programming Language :: Python :: 3",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ ]
27
+ dependencies = [
28
+ "bleak>=0.22.0",
29
+ "bleak-retry-connector>=3.5.0",
30
+ ]
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/joostlek/python-tile-ble"
34
+ Repository = "https://github.com/joostlek/python-tile-ble"
35
+ Documentation = "https://github.com/joostlek/python-tile-ble"
36
+ "Bug Tracker" = "https://github.com/joostlek/python-tile-ble/issues"
37
+ Changelog = "https://github.com/joostlek/python-tile-ble/releases"
38
+
39
+ [dependency-groups]
40
+ dev = [
41
+ "codespell==2.4.3",
42
+ "covdefaults==2.3.0",
43
+ "coverage[toml]==7.17.1",
44
+ "mypy==2.4.1",
45
+ "prek==0.5.10",
46
+ "pre-commit-hooks==6.0.0",
47
+ "pylint==4.1.3",
48
+ "pytest==9.2.0",
49
+ "pytest-asyncio==1.4.1.post1",
50
+ "pytest-cov==7.1.0",
51
+ "ruff==0.17.3",
52
+ "safety==3.8.1",
53
+ "yamllint==1.38.0",
54
+ "syrupy==6.1.1",
55
+ ]
56
+
57
+ [tool.uv]
58
+ default-groups = "all"
59
+
60
+ [tool.hatch.build.targets.sdist]
61
+ include = ["src/tile_ble"]
62
+
63
+ [tool.hatch.build.targets.wheel]
64
+ include = ["src/tile_ble"]
65
+
66
+ [tool.hatch.build.targets.wheel.sources]
67
+ "src/tile_ble" = "tile_ble"
68
+
69
+ [build-system]
70
+ requires = ["hatchling"]
71
+ build-backend = "hatchling.build"
72
+
73
+ [tool.coverage.report]
74
+ show_missing = true
75
+ fail_under = 50
76
+
77
+ [tool.coverage.run]
78
+ plugins = ["covdefaults"]
79
+ source = ["tile_ble"]
80
+
81
+ [tool.mypy]
82
+ # Specify the target platform details in config, so your developers are
83
+ # free to run mypy on Windows, Linux, or macOS and get consistent
84
+ # results.
85
+ platform = "linux"
86
+ python_version = "3.13"
87
+
88
+ # show error messages from unrelated files
89
+ follow_imports = "normal"
90
+
91
+ # suppress errors about unsatisfied imports
92
+ ignore_missing_imports = true
93
+
94
+ # be strict
95
+ check_untyped_defs = true
96
+ disallow_any_generics = true
97
+ disallow_incomplete_defs = true
98
+ disallow_subclassing_any = true
99
+ disallow_untyped_calls = true
100
+ disallow_untyped_decorators = true
101
+ disallow_untyped_defs = true
102
+ no_implicit_optional = true
103
+ strict_optional = true
104
+ warn_incomplete_stub = true
105
+ warn_no_return = true
106
+ warn_redundant_casts = true
107
+ warn_return_any = true
108
+ warn_unused_configs = true
109
+ warn_unused_ignores = true
110
+
111
+ [tool.pylint.MASTER]
112
+ ignore = [
113
+ "tests",
114
+ ]
115
+
116
+ [tool.pylint.BASIC]
117
+ good-names = [
118
+ "_",
119
+ "ex",
120
+ "fp",
121
+ "i",
122
+ "id",
123
+ "j",
124
+ "k",
125
+ "on",
126
+ "Run",
127
+ "T",
128
+ ]
129
+
130
+ [tool.pylint.DESIGN]
131
+ max-attributes = 8
132
+
133
+ [tool.pylint."MESSAGES CONTROL"]
134
+ disable = [
135
+ "duplicate-code",
136
+ "format",
137
+ "unsubscriptable-object",
138
+ "too-many-instance-attributes",
139
+ "wrong-import-order",
140
+ "too-many-arguments",
141
+ "too-many-positional-arguments",
142
+ ]
143
+
144
+ [tool.pylint.SIMILARITIES]
145
+ ignore-imports = true
146
+
147
+ [tool.pylint.FORMAT]
148
+ max-line-length = 88
149
+
150
+ [tool.pytest.ini_options]
151
+ addopts = "--cov"
152
+ asyncio_mode = "auto"
153
+
154
+ [tool.ruff.lint]
155
+ ignore = [
156
+ "ANN401", # Opinioated warning on disallowing dynamically typed expressions
157
+ "COM812", # Conflicts with other rules
158
+ "CPY001", # This project doesn't use copyright headers
159
+ "D203", # Conflicts with other rules
160
+ "D213", # Conflicts with other rules
161
+ "D417", # False positives in some occasions
162
+ "ISC001", # Conflicts with other rules
163
+ "PLR0917", # Too many positional arguments, also disabled in pylint
164
+ "PLR2004", # Just annoying, not really useful
165
+ ]
166
+ select = ["ALL"]
167
+
168
+ [tool.ruff.lint.flake8-pytest-style]
169
+ fixture-parentheses = false
170
+ mark-parentheses = false
171
+
172
+ [tool.ruff.lint.isort]
173
+ known-first-party = ["tile_ble"]
174
+ force-sort-within-sections = true
175
+ split-on-trailing-comma = false
176
+ combine-as-imports = true
177
+
178
+ [tool.ruff.lint.mccabe]
179
+ max-complexity = 25
@@ -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
+ ]
@@ -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
@@ -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()
@@ -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."""
@@ -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:])
File without changes