bluetooth-classic 0.1.0__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.
- bluetooth_classic-0.1.0/LICENSE +202 -0
- bluetooth_classic-0.1.0/PKG-INFO +136 -0
- bluetooth_classic-0.1.0/README.md +101 -0
- bluetooth_classic-0.1.0/pyproject.toml +123 -0
- bluetooth_classic-0.1.0/src/bluetooth_classic/__init__.py +28 -0
- bluetooth_classic-0.1.0/src/bluetooth_classic/agent.py +80 -0
- bluetooth_classic-0.1.0/src/bluetooth_classic/client.py +502 -0
- bluetooth_classic-0.1.0/src/bluetooth_classic/const.py +42 -0
- bluetooth_classic-0.1.0/src/bluetooth_classic/exceptions.py +19 -0
- bluetooth_classic-0.1.0/src/bluetooth_classic/models.py +50 -0
- bluetooth_classic-0.1.0/src/bluetooth_classic/py.typed +0 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2022 J. Nick Koston
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bluetooth-classic
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Bluetooth Classic (BR/EDR) discovery, pairing and presence on Linux, through BlueZ
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: bluetooth,bluetooth classic,br/edr,bluez,pairing,presence,asyncio
|
|
8
|
+
Author: jeverley
|
|
9
|
+
Author-email: 46714706+jeverley@users.noreply.github.com
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Natural Language :: English
|
|
15
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Home Automation
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
23
|
+
Classifier: Topic :: System :: Hardware
|
|
24
|
+
Provides-Extra: docs
|
|
25
|
+
Requires-Dist: Sphinx (>=8.1.3,<9) ; extra == "docs"
|
|
26
|
+
Requires-Dist: dbus-fast (>=2.0.0)
|
|
27
|
+
Requires-Dist: myst-parser (>=4.0.1,<4.1) ; extra == "docs"
|
|
28
|
+
Requires-Dist: sphinx-rtd-theme (>=3.1.0,<4) ; extra == "docs"
|
|
29
|
+
Project-URL: Bug Tracker, https://github.com/jeverley/bluetooth-classic/issues
|
|
30
|
+
Project-URL: Changelog, https://github.com/jeverley/bluetooth-classic/blob/main/CHANGELOG.md
|
|
31
|
+
Project-URL: Documentation, https://bluetooth-classic.readthedocs.io
|
|
32
|
+
Project-URL: Repository, https://github.com/jeverley/bluetooth-classic
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# Bluetooth Classic
|
|
36
|
+
|
|
37
|
+
<p align="center">
|
|
38
|
+
<a href="https://github.com/jeverley/bluetooth-classic/actions/workflows/ci.yml">
|
|
39
|
+
<img src="https://img.shields.io/github/actions/workflow/status/jeverley/bluetooth-classic/ci.yml?branch=main&label=CI&logo=github&style=flat-square" alt="CI Status" >
|
|
40
|
+
</a>
|
|
41
|
+
<a href="https://bluetooth-classic.readthedocs.io">
|
|
42
|
+
<img src="https://img.shields.io/readthedocs/bluetooth-classic.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
|
|
43
|
+
</a>
|
|
44
|
+
<a href="https://codecov.io/gh/jeverley/bluetooth-classic">
|
|
45
|
+
<img src="https://img.shields.io/codecov/c/github/jeverley/bluetooth-classic.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
|
|
46
|
+
</a>
|
|
47
|
+
</p>
|
|
48
|
+
<p align="center">
|
|
49
|
+
<a href="https://python-poetry.org/">
|
|
50
|
+
<img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square" alt="Poetry">
|
|
51
|
+
</a>
|
|
52
|
+
<a href="https://github.com/astral-sh/ruff">
|
|
53
|
+
<img src="https://img.shields.io/badge/code%20style-ruff-000000.svg?style=flat-square" alt="ruff">
|
|
54
|
+
</a>
|
|
55
|
+
<a href="https://github.com/pre-commit/pre-commit">
|
|
56
|
+
<img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
|
|
57
|
+
</a>
|
|
58
|
+
</p>
|
|
59
|
+
<p align="center">
|
|
60
|
+
<a href="https://pypi.org/project/bluetooth-classic/">
|
|
61
|
+
<img src="https://img.shields.io/pypi/v/bluetooth-classic.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
|
|
62
|
+
</a>
|
|
63
|
+
<img src="https://img.shields.io/pypi/pyversions/bluetooth-classic.svg?style=flat-square&logo=python&logoColor=fff" alt="Supported Python versions">
|
|
64
|
+
<img src="https://img.shields.io/pypi/l/bluetooth-classic.svg?style=flat-square" alt="License">
|
|
65
|
+
</p>
|
|
66
|
+
|
|
67
|
+
<!-- docs-start -->
|
|
68
|
+
|
|
69
|
+
Bluetooth Classic (BR/EDR) discovery, pairing and presence on Linux, through
|
|
70
|
+
BlueZ.
|
|
71
|
+
|
|
72
|
+
Python has good libraries for Bluetooth Low Energy, such as
|
|
73
|
+
[Bleak](https://github.com/hbldh/bleak), but none of them handle Bluetooth
|
|
74
|
+
Classic devices: speakers, headphones, printers and serial adapters. This
|
|
75
|
+
library fills that gap for the housekeeping around such a device. It talks to
|
|
76
|
+
BlueZ over D-Bus with [dbus-fast](https://github.com/Bluetooth-Devices/dbus-fast),
|
|
77
|
+
in your own asyncio event loop, without compiled extensions or command-line
|
|
78
|
+
tools.
|
|
79
|
+
|
|
80
|
+
- **Discover** nearby Classic devices, with their names, services and signal
|
|
81
|
+
strength.
|
|
82
|
+
- **Pair** with a built-in agent for devices without a screen or keyboard,
|
|
83
|
+
and **trust** them.
|
|
84
|
+
- **Check presence**: whether a known device is on, with a short Classic scan
|
|
85
|
+
that never connects to it, so it does not wake a device that wakes when
|
|
86
|
+
connected to.
|
|
87
|
+
|
|
88
|
+
Connections to a device's services are out of scope: use RFCOMM sockets, or a
|
|
89
|
+
library such as [aio-rfcomm](https://github.com/dlech/aio-rfcomm).
|
|
90
|
+
|
|
91
|
+
## Installation
|
|
92
|
+
|
|
93
|
+
Install this via pip (or your favourite package manager):
|
|
94
|
+
|
|
95
|
+
`pip install bluetooth-classic`
|
|
96
|
+
|
|
97
|
+
It needs Linux with BlueZ 5, and Python 3.11 or newer.
|
|
98
|
+
|
|
99
|
+
## Usage
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import asyncio
|
|
103
|
+
|
|
104
|
+
from bluetooth_classic import BluetoothClassic
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def main() -> None:
|
|
108
|
+
async with await BluetoothClassic.connect() as bluetooth:
|
|
109
|
+
for device in await bluetooth.discover(seconds=10):
|
|
110
|
+
print(device.address, device.name, device.rssi)
|
|
111
|
+
|
|
112
|
+
device = await bluetooth.pair("00:11:22:33:44:55")
|
|
113
|
+
await bluetooth.trust(device.address)
|
|
114
|
+
|
|
115
|
+
result = await bluetooth.check_presence(device.address)
|
|
116
|
+
print("on" if result.present else "off")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
asyncio.run(main())
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
A Classic scan uses the same radio as Low Energy scanning and interrupts it
|
|
123
|
+
while it runs. Keep scans short, and in an application that also scans for
|
|
124
|
+
Low Energy devices, let one part of it decide when they run.
|
|
125
|
+
|
|
126
|
+
## Contributing
|
|
127
|
+
|
|
128
|
+
See [CONTRIBUTING.md](https://github.com/jeverley/bluetooth-classic/blob/main/CONTRIBUTING.md).
|
|
129
|
+
|
|
130
|
+
## Credits
|
|
131
|
+
|
|
132
|
+
The project layout and tooling follow the
|
|
133
|
+
[Bluetooth-Devices](https://github.com/Bluetooth-Devices) libraries, which
|
|
134
|
+
were created with
|
|
135
|
+
[browniebroke/cookiecutter-pypackage](https://github.com/browniebroke/cookiecutter-pypackage).
|
|
136
|
+
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Bluetooth Classic
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://github.com/jeverley/bluetooth-classic/actions/workflows/ci.yml">
|
|
5
|
+
<img src="https://img.shields.io/github/actions/workflow/status/jeverley/bluetooth-classic/ci.yml?branch=main&label=CI&logo=github&style=flat-square" alt="CI Status" >
|
|
6
|
+
</a>
|
|
7
|
+
<a href="https://bluetooth-classic.readthedocs.io">
|
|
8
|
+
<img src="https://img.shields.io/readthedocs/bluetooth-classic.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
|
|
9
|
+
</a>
|
|
10
|
+
<a href="https://codecov.io/gh/jeverley/bluetooth-classic">
|
|
11
|
+
<img src="https://img.shields.io/codecov/c/github/jeverley/bluetooth-classic.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
|
|
12
|
+
</a>
|
|
13
|
+
</p>
|
|
14
|
+
<p align="center">
|
|
15
|
+
<a href="https://python-poetry.org/">
|
|
16
|
+
<img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square" alt="Poetry">
|
|
17
|
+
</a>
|
|
18
|
+
<a href="https://github.com/astral-sh/ruff">
|
|
19
|
+
<img src="https://img.shields.io/badge/code%20style-ruff-000000.svg?style=flat-square" alt="ruff">
|
|
20
|
+
</a>
|
|
21
|
+
<a href="https://github.com/pre-commit/pre-commit">
|
|
22
|
+
<img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
|
|
23
|
+
</a>
|
|
24
|
+
</p>
|
|
25
|
+
<p align="center">
|
|
26
|
+
<a href="https://pypi.org/project/bluetooth-classic/">
|
|
27
|
+
<img src="https://img.shields.io/pypi/v/bluetooth-classic.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
|
|
28
|
+
</a>
|
|
29
|
+
<img src="https://img.shields.io/pypi/pyversions/bluetooth-classic.svg?style=flat-square&logo=python&logoColor=fff" alt="Supported Python versions">
|
|
30
|
+
<img src="https://img.shields.io/pypi/l/bluetooth-classic.svg?style=flat-square" alt="License">
|
|
31
|
+
</p>
|
|
32
|
+
|
|
33
|
+
<!-- docs-start -->
|
|
34
|
+
|
|
35
|
+
Bluetooth Classic (BR/EDR) discovery, pairing and presence on Linux, through
|
|
36
|
+
BlueZ.
|
|
37
|
+
|
|
38
|
+
Python has good libraries for Bluetooth Low Energy, such as
|
|
39
|
+
[Bleak](https://github.com/hbldh/bleak), but none of them handle Bluetooth
|
|
40
|
+
Classic devices: speakers, headphones, printers and serial adapters. This
|
|
41
|
+
library fills that gap for the housekeeping around such a device. It talks to
|
|
42
|
+
BlueZ over D-Bus with [dbus-fast](https://github.com/Bluetooth-Devices/dbus-fast),
|
|
43
|
+
in your own asyncio event loop, without compiled extensions or command-line
|
|
44
|
+
tools.
|
|
45
|
+
|
|
46
|
+
- **Discover** nearby Classic devices, with their names, services and signal
|
|
47
|
+
strength.
|
|
48
|
+
- **Pair** with a built-in agent for devices without a screen or keyboard,
|
|
49
|
+
and **trust** them.
|
|
50
|
+
- **Check presence**: whether a known device is on, with a short Classic scan
|
|
51
|
+
that never connects to it, so it does not wake a device that wakes when
|
|
52
|
+
connected to.
|
|
53
|
+
|
|
54
|
+
Connections to a device's services are out of scope: use RFCOMM sockets, or a
|
|
55
|
+
library such as [aio-rfcomm](https://github.com/dlech/aio-rfcomm).
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
Install this via pip (or your favourite package manager):
|
|
60
|
+
|
|
61
|
+
`pip install bluetooth-classic`
|
|
62
|
+
|
|
63
|
+
It needs Linux with BlueZ 5, and Python 3.11 or newer.
|
|
64
|
+
|
|
65
|
+
## Usage
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
import asyncio
|
|
69
|
+
|
|
70
|
+
from bluetooth_classic import BluetoothClassic
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def main() -> None:
|
|
74
|
+
async with await BluetoothClassic.connect() as bluetooth:
|
|
75
|
+
for device in await bluetooth.discover(seconds=10):
|
|
76
|
+
print(device.address, device.name, device.rssi)
|
|
77
|
+
|
|
78
|
+
device = await bluetooth.pair("00:11:22:33:44:55")
|
|
79
|
+
await bluetooth.trust(device.address)
|
|
80
|
+
|
|
81
|
+
result = await bluetooth.check_presence(device.address)
|
|
82
|
+
print("on" if result.present else "off")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
asyncio.run(main())
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
A Classic scan uses the same radio as Low Energy scanning and interrupts it
|
|
89
|
+
while it runs. Keep scans short, and in an application that also scans for
|
|
90
|
+
Low Energy devices, let one part of it decide when they run.
|
|
91
|
+
|
|
92
|
+
## Contributing
|
|
93
|
+
|
|
94
|
+
See [CONTRIBUTING.md](https://github.com/jeverley/bluetooth-classic/blob/main/CONTRIBUTING.md).
|
|
95
|
+
|
|
96
|
+
## Credits
|
|
97
|
+
|
|
98
|
+
The project layout and tooling follow the
|
|
99
|
+
[Bluetooth-Devices](https://github.com/Bluetooth-Devices) libraries, which
|
|
100
|
+
were created with
|
|
101
|
+
[browniebroke/cookiecutter-pypackage](https://github.com/browniebroke/cookiecutter-pypackage).
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "bluetooth-classic"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
license = "Apache-2.0"
|
|
5
|
+
description = "Bluetooth Classic (BR/EDR) discovery, pairing and presence on Linux, through BlueZ"
|
|
6
|
+
authors = [{ name = "jeverley", email = "46714706+jeverley@users.noreply.github.com" }]
|
|
7
|
+
readme = "README.md"
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
keywords = ["bluetooth", "bluetooth classic", "br/edr", "bluez", "pairing", "presence", "asyncio"]
|
|
10
|
+
dynamic = ["classifiers", "dependencies", "optional-dependencies"]
|
|
11
|
+
|
|
12
|
+
[project.urls]
|
|
13
|
+
"Documentation" = "https://bluetooth-classic.readthedocs.io"
|
|
14
|
+
"Repository" = "https://github.com/jeverley/bluetooth-classic"
|
|
15
|
+
"Bug Tracker" = "https://github.com/jeverley/bluetooth-classic/issues"
|
|
16
|
+
"Changelog" = "https://github.com/jeverley/bluetooth-classic/blob/main/CHANGELOG.md"
|
|
17
|
+
|
|
18
|
+
[tool.poetry]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Development Status :: 3 - Alpha",
|
|
21
|
+
"Framework :: AsyncIO",
|
|
22
|
+
"Intended Audience :: Developers",
|
|
23
|
+
"Natural Language :: English",
|
|
24
|
+
"Operating System :: POSIX :: Linux",
|
|
25
|
+
"Topic :: Home Automation",
|
|
26
|
+
"Topic :: Software Development :: Libraries",
|
|
27
|
+
"Topic :: System :: Hardware",
|
|
28
|
+
]
|
|
29
|
+
packages = [
|
|
30
|
+
{ include = "bluetooth_classic", from = "src" },
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[tool.poetry.dependencies]
|
|
34
|
+
python = ">=3.11,<3.15"
|
|
35
|
+
dbus-fast = ">=2.0.0"
|
|
36
|
+
|
|
37
|
+
# Documentation Dependencies
|
|
38
|
+
Sphinx = {version = ">=8.1.3,<9", optional = true}
|
|
39
|
+
sphinx-rtd-theme = {version = ">=3.1.0,<4", optional = true}
|
|
40
|
+
myst-parser = {version = ">=4.0.1,<4.1", optional = true}
|
|
41
|
+
|
|
42
|
+
[tool.poetry.extras]
|
|
43
|
+
docs = [
|
|
44
|
+
"myst-parser",
|
|
45
|
+
"sphinx",
|
|
46
|
+
"sphinx-rtd-theme",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
[tool.poetry.group.dev.dependencies]
|
|
50
|
+
pytest = "^9.0"
|
|
51
|
+
pytest-cov = "^7.1"
|
|
52
|
+
pytest-asyncio = "^1.2.0"
|
|
53
|
+
|
|
54
|
+
[tool.semantic_release]
|
|
55
|
+
branch = "main"
|
|
56
|
+
version_toml = ["pyproject.toml:project.version"]
|
|
57
|
+
version_variables = ["src/bluetooth_classic/__init__.py:__version__"]
|
|
58
|
+
build_command = "pip install poetry && poetry build"
|
|
59
|
+
# A Conventional Commits message, so commitlint accepts the release commit.
|
|
60
|
+
commit_message = "chore(release): {version}\n\nAutomatically generated by python-semantic-release"
|
|
61
|
+
|
|
62
|
+
[tool.pytest.ini_options]
|
|
63
|
+
addopts = "-v -Wdefault --cov=bluetooth_classic --cov-report=term-missing:skip-covered"
|
|
64
|
+
pythonpath = ["src"]
|
|
65
|
+
log_format = "%(asctime)s.%(msecs)03d %(levelname)-8s %(threadName)s %(name)s:%(filename)s:%(lineno)s %(message)s"
|
|
66
|
+
log_date_format = "%Y-%m-%d %H:%M:%S"
|
|
67
|
+
asyncio_mode = "auto"
|
|
68
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
69
|
+
|
|
70
|
+
[tool.coverage.run]
|
|
71
|
+
branch = true
|
|
72
|
+
|
|
73
|
+
[tool.coverage.report]
|
|
74
|
+
exclude_lines = [
|
|
75
|
+
"pragma: no cover",
|
|
76
|
+
"@overload",
|
|
77
|
+
"if TYPE_CHECKING",
|
|
78
|
+
"raise NotImplementedError",
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
[tool.mypy]
|
|
82
|
+
check_untyped_defs = true
|
|
83
|
+
disallow_any_generics = true
|
|
84
|
+
disallow_incomplete_defs = true
|
|
85
|
+
disallow_untyped_defs = true
|
|
86
|
+
mypy_path = "src/"
|
|
87
|
+
no_implicit_optional = true
|
|
88
|
+
show_error_codes = true
|
|
89
|
+
warn_unreachable = true
|
|
90
|
+
warn_unused_ignores = true
|
|
91
|
+
exclude = [
|
|
92
|
+
'docs/.*',
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
[[tool.mypy.overrides]]
|
|
96
|
+
module = "tests.*"
|
|
97
|
+
allow_untyped_defs = true
|
|
98
|
+
|
|
99
|
+
[[tool.mypy.overrides]]
|
|
100
|
+
module = "docs.*"
|
|
101
|
+
ignore_errors = true
|
|
102
|
+
|
|
103
|
+
[tool.ruff]
|
|
104
|
+
target-version = "py311"
|
|
105
|
+
line-length = 88
|
|
106
|
+
|
|
107
|
+
[tool.ruff.lint]
|
|
108
|
+
select = ["E", "F", "I", "UP", "B", "SIM", "RUF", "D", "N"]
|
|
109
|
+
ignore = ["D105", "D107"]
|
|
110
|
+
|
|
111
|
+
[tool.ruff.lint.pydocstyle]
|
|
112
|
+
convention = "google"
|
|
113
|
+
|
|
114
|
+
[tool.ruff.lint.per-file-ignores]
|
|
115
|
+
"tests/**" = ["D", "N802"]
|
|
116
|
+
"docs/**" = ["D"]
|
|
117
|
+
|
|
118
|
+
[tool.ruff.lint.isort]
|
|
119
|
+
known-first-party = ["bluetooth_classic", "tests"]
|
|
120
|
+
|
|
121
|
+
[build-system]
|
|
122
|
+
requires = ["poetry-core>=2.0.0"]
|
|
123
|
+
build-backend = "poetry.core.masonry.api"
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Bluetooth Classic discovery, pairing and presence on Linux, through BlueZ."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .client import BluetoothClassic, normalize_address
|
|
6
|
+
from .const import DEFAULT_PIN, DISCOVERY_SECONDS, PAIR_TIMEOUT, PRESENCE_SECONDS
|
|
7
|
+
from .exceptions import (
|
|
8
|
+
BluetoothClassicError,
|
|
9
|
+
DeviceNotFoundError,
|
|
10
|
+
NoAdapterError,
|
|
11
|
+
PairingError,
|
|
12
|
+
)
|
|
13
|
+
from .models import ClassicDevice, PresenceResult
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"DEFAULT_PIN",
|
|
17
|
+
"DISCOVERY_SECONDS",
|
|
18
|
+
"PAIR_TIMEOUT",
|
|
19
|
+
"PRESENCE_SECONDS",
|
|
20
|
+
"BluetoothClassic",
|
|
21
|
+
"BluetoothClassicError",
|
|
22
|
+
"ClassicDevice",
|
|
23
|
+
"DeviceNotFoundError",
|
|
24
|
+
"NoAdapterError",
|
|
25
|
+
"PairingError",
|
|
26
|
+
"PresenceResult",
|
|
27
|
+
"normalize_address",
|
|
28
|
+
]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The pairing agent BlueZ asks during pairing.
|
|
2
|
+
|
|
3
|
+
This module does not use ``from __future__ import annotations``: dbus-fast
|
|
4
|
+
reads the D-Bus signatures from the methods' annotations, such as ``"o"``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# ruff: noqa: F821, N802
|
|
8
|
+
# mypy: disable-error-code="name-defined"
|
|
9
|
+
|
|
10
|
+
from dbus_fast import DBusError
|
|
11
|
+
from dbus_fast.service import ServiceInterface, method
|
|
12
|
+
|
|
13
|
+
from .const import AGENT_INTERFACE, DEFAULT_PIN
|
|
14
|
+
|
|
15
|
+
REJECTED = "org.bluez.Error.Rejected"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PairingAgent(ServiceInterface):
|
|
19
|
+
"""Accepts pairing for one device only, for the length of one pairing.
|
|
20
|
+
|
|
21
|
+
It suits devices without a screen or keyboard: "just works" pairing is
|
|
22
|
+
confirmed, and a device that asks for a PIN gets ``pin``. Requests about
|
|
23
|
+
any other device are rejected, so pairing one device cannot also accept
|
|
24
|
+
another that asks at the same time.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, device_path: str, pin: str = DEFAULT_PIN) -> None:
|
|
28
|
+
"""Create an agent for the device at ``device_path``."""
|
|
29
|
+
super().__init__(AGENT_INTERFACE)
|
|
30
|
+
self._device_path = device_path
|
|
31
|
+
self._pin = pin
|
|
32
|
+
|
|
33
|
+
def _check(self, device: str) -> None:
|
|
34
|
+
if device != self._device_path:
|
|
35
|
+
raise DBusError(REJECTED, "Not the device being paired")
|
|
36
|
+
|
|
37
|
+
@method()
|
|
38
|
+
def Release(self) -> None:
|
|
39
|
+
"""Release the agent; nothing to clean up."""
|
|
40
|
+
|
|
41
|
+
@method()
|
|
42
|
+
def RequestPinCode(self, device: "o") -> "s":
|
|
43
|
+
"""Return the PIN for a device that asks for one."""
|
|
44
|
+
self._check(device)
|
|
45
|
+
return self._pin
|
|
46
|
+
|
|
47
|
+
@method()
|
|
48
|
+
def DisplayPinCode(self, device: "o", pincode: "s") -> None:
|
|
49
|
+
"""Accept a PIN the device shows."""
|
|
50
|
+
self._check(device)
|
|
51
|
+
|
|
52
|
+
@method()
|
|
53
|
+
def RequestPasskey(self, device: "o") -> "u":
|
|
54
|
+
"""Return a passkey: the PIN as a number, or 0."""
|
|
55
|
+
self._check(device)
|
|
56
|
+
return int(self._pin) if self._pin.isdigit() else 0
|
|
57
|
+
|
|
58
|
+
@method()
|
|
59
|
+
def DisplayPasskey(self, device: "o", passkey: "u", entered: "q") -> None:
|
|
60
|
+
"""Accept a passkey the device shows."""
|
|
61
|
+
self._check(device)
|
|
62
|
+
|
|
63
|
+
@method()
|
|
64
|
+
def RequestConfirmation(self, device: "o", passkey: "u") -> None:
|
|
65
|
+
"""Confirm "just works" pairing."""
|
|
66
|
+
self._check(device)
|
|
67
|
+
|
|
68
|
+
@method()
|
|
69
|
+
def RequestAuthorization(self, device: "o") -> None:
|
|
70
|
+
"""Authorise pairing that the device started."""
|
|
71
|
+
self._check(device)
|
|
72
|
+
|
|
73
|
+
@method()
|
|
74
|
+
def AuthorizeService(self, device: "o", uuid: "s") -> None:
|
|
75
|
+
"""Authorise a service connection made during pairing."""
|
|
76
|
+
self._check(device)
|
|
77
|
+
|
|
78
|
+
@method()
|
|
79
|
+
def Cancel(self) -> None:
|
|
80
|
+
"""Note that BlueZ cancelled a request; nothing to undo."""
|
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
"""Bluetooth Classic discovery, pairing and presence through BlueZ."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import AsyncIterator, Callable, Iterable
|
|
10
|
+
from dataclasses import replace
|
|
11
|
+
from types import TracebackType
|
|
12
|
+
from typing import Any, Self, TypeAlias
|
|
13
|
+
|
|
14
|
+
from dbus_fast import BusType, Message, MessageType, Variant
|
|
15
|
+
from dbus_fast.aio import MessageBus
|
|
16
|
+
|
|
17
|
+
from .agent import PairingAgent
|
|
18
|
+
from .const import (
|
|
19
|
+
ADAPTER_INTERFACE,
|
|
20
|
+
AGENT_CAPABILITY,
|
|
21
|
+
AGENT_MANAGER_INTERFACE,
|
|
22
|
+
AGENT_PATH,
|
|
23
|
+
BLUEZ_PATH,
|
|
24
|
+
BLUEZ_SERVICE,
|
|
25
|
+
DBUS_PATH,
|
|
26
|
+
DBUS_SERVICE,
|
|
27
|
+
DEFAULT_PIN,
|
|
28
|
+
DEVICE_INTERFACE,
|
|
29
|
+
DISCOVERY_SECONDS,
|
|
30
|
+
NOT_INQUIRY,
|
|
31
|
+
OBJECT_MANAGER_INTERFACE,
|
|
32
|
+
PAIR_TIMEOUT,
|
|
33
|
+
PRESENCE_SECONDS,
|
|
34
|
+
PROPERTIES_INTERFACE,
|
|
35
|
+
TRANSPORT_BREDR,
|
|
36
|
+
)
|
|
37
|
+
from .exceptions import (
|
|
38
|
+
BluetoothClassicError,
|
|
39
|
+
DeviceNotFoundError,
|
|
40
|
+
NoAdapterError,
|
|
41
|
+
PairingError,
|
|
42
|
+
)
|
|
43
|
+
from .models import ClassicDevice, PresenceResult
|
|
44
|
+
|
|
45
|
+
_LOGGER = logging.getLogger(__name__)
|
|
46
|
+
|
|
47
|
+
_ADDRESS_RE = re.compile(r"^[0-9A-F]{2}(:[0-9A-F]{2}){5}$")
|
|
48
|
+
|
|
49
|
+
_ManagedObjects: TypeAlias = dict[str, dict[str, dict[str, Any]]]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def normalize_address(address: str) -> str:
|
|
53
|
+
"""Return an address in upper-case colon form, or raise ValueError."""
|
|
54
|
+
candidate = address.strip().upper().replace("-", ":")
|
|
55
|
+
if not _ADDRESS_RE.match(candidate):
|
|
56
|
+
raise ValueError(f"Not a Bluetooth address: {address}")
|
|
57
|
+
return candidate
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _unwrap(value: Any) -> Any:
|
|
61
|
+
return value.value if isinstance(value, Variant) else value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _summary(value: Any) -> Any:
|
|
65
|
+
"""Return a property value short enough to log."""
|
|
66
|
+
if isinstance(value, bool | int | float | str):
|
|
67
|
+
return value
|
|
68
|
+
if isinstance(value, dict):
|
|
69
|
+
return "{" + ", ".join(str(key) for key in value) + "}"
|
|
70
|
+
if isinstance(value, list | tuple | bytes | bytearray):
|
|
71
|
+
return f"[{len(value)}]"
|
|
72
|
+
return type(value).__name__
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _is_inquiry_answer(properties: dict[str, Any]) -> bool:
|
|
76
|
+
"""Return whether changed properties are an answer to a Classic inquiry.
|
|
77
|
+
|
|
78
|
+
A Classic inquiry answer brings a signal strength. Low Energy advertising
|
|
79
|
+
and a link changing can bring one too, but with other properties.
|
|
80
|
+
"""
|
|
81
|
+
return "RSSI" in properties and not properties.keys() & NOT_INQUIRY
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _device(path: str, properties: dict[str, Any]) -> ClassicDevice:
|
|
85
|
+
props = {key: _unwrap(value) for key, value in properties.items()}
|
|
86
|
+
rssi = props.get("RSSI")
|
|
87
|
+
device_class = props.get("Class")
|
|
88
|
+
return ClassicDevice(
|
|
89
|
+
address=str(props.get("Address", "")).upper(),
|
|
90
|
+
name=props.get("Name") or props.get("Alias"),
|
|
91
|
+
path=path,
|
|
92
|
+
adapter=path.split("/")[3] if path.count("/") >= 3 else "",
|
|
93
|
+
paired=bool(props.get("Paired", False)),
|
|
94
|
+
trusted=bool(props.get("Trusted", False)),
|
|
95
|
+
connected=bool(props.get("Connected", False)),
|
|
96
|
+
uuids=frozenset(uuid.lower() for uuid in props.get("UUIDs", [])),
|
|
97
|
+
device_class=int(device_class) if device_class is not None else None,
|
|
98
|
+
rssi=int(rssi) if rssi is not None else None,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class BluetoothClassic:
|
|
103
|
+
"""A connection to BlueZ for Bluetooth Classic devices on one adapter.
|
|
104
|
+
|
|
105
|
+
Use :meth:`connect`, ideally as an async context manager::
|
|
106
|
+
|
|
107
|
+
async with await BluetoothClassic.connect() as bluetooth:
|
|
108
|
+
devices = await bluetooth.discover()
|
|
109
|
+
|
|
110
|
+
Discovery and presence checks on one connection run one at a time.
|
|
111
|
+
A Classic scan uses the same radio as Low Energy scanning and interrupts
|
|
112
|
+
it while it runs, so keep them short and let one owner schedule them.
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
def __init__(self, bus: MessageBus, adapter_path: str, *, owns_bus: bool) -> None:
|
|
116
|
+
"""Wrap a connected bus; use :meth:`connect` instead."""
|
|
117
|
+
self._bus = bus
|
|
118
|
+
self._adapter_path = adapter_path
|
|
119
|
+
self._owns_bus = owns_bus
|
|
120
|
+
self._scan_lock = asyncio.Lock()
|
|
121
|
+
|
|
122
|
+
@classmethod
|
|
123
|
+
async def connect(
|
|
124
|
+
cls, adapter: str | None = None, *, bus: MessageBus | None = None
|
|
125
|
+
) -> Self:
|
|
126
|
+
"""Connect to BlueZ and choose an adapter.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
adapter: The adapter's name, such as ``"hci0"``. ``None`` picks the
|
|
130
|
+
first powered adapter, or the first adapter if none is powered.
|
|
131
|
+
bus: A system bus connection to use instead of opening one. It is
|
|
132
|
+
left open when this connection closes.
|
|
133
|
+
|
|
134
|
+
Raises:
|
|
135
|
+
BluetoothClassicError: The system bus could not be reached.
|
|
136
|
+
NoAdapterError: There is no adapter, or not the one asked for.
|
|
137
|
+
"""
|
|
138
|
+
owns_bus = bus is None
|
|
139
|
+
if bus is None:
|
|
140
|
+
try:
|
|
141
|
+
bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
|
|
142
|
+
except Exception as err:
|
|
143
|
+
raise BluetoothClassicError(
|
|
144
|
+
f"Could not connect to the system bus: {err}"
|
|
145
|
+
) from err
|
|
146
|
+
try:
|
|
147
|
+
path = _choose_adapter(await _managed_objects(bus), adapter)
|
|
148
|
+
except BaseException:
|
|
149
|
+
if owns_bus:
|
|
150
|
+
bus.disconnect()
|
|
151
|
+
raise
|
|
152
|
+
return cls(bus, path, owns_bus=owns_bus)
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def adapter(self) -> str:
|
|
156
|
+
"""Return the adapter's name, such as ``"hci0"``."""
|
|
157
|
+
return self._adapter_path.rsplit("/", 1)[-1]
|
|
158
|
+
|
|
159
|
+
def close(self) -> None:
|
|
160
|
+
"""Close the connection, unless it was given an existing bus."""
|
|
161
|
+
if self._owns_bus:
|
|
162
|
+
self._bus.disconnect()
|
|
163
|
+
|
|
164
|
+
async def __aenter__(self) -> Self:
|
|
165
|
+
"""Use as an async context manager."""
|
|
166
|
+
return self
|
|
167
|
+
|
|
168
|
+
async def __aexit__(
|
|
169
|
+
self,
|
|
170
|
+
exc_type: type[BaseException] | None,
|
|
171
|
+
exc: BaseException | None,
|
|
172
|
+
traceback: TracebackType | None,
|
|
173
|
+
) -> None:
|
|
174
|
+
"""Close on leaving the block."""
|
|
175
|
+
self.close()
|
|
176
|
+
|
|
177
|
+
async def devices(self, *, service: str | None = None) -> list[ClassicDevice]:
|
|
178
|
+
"""Return the devices BlueZ knows on this adapter.
|
|
179
|
+
|
|
180
|
+
Known devices are those paired, and those seen by a recent scan.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
service: Only devices that list this service UUID. Before pairing,
|
|
184
|
+
a device lists only the services it advertises in a scan.
|
|
185
|
+
"""
|
|
186
|
+
devices = [
|
|
187
|
+
_device(path, interfaces[DEVICE_INTERFACE])
|
|
188
|
+
for path, interfaces in (await _managed_objects(self._bus)).items()
|
|
189
|
+
if DEVICE_INTERFACE in interfaces
|
|
190
|
+
and path.startswith(f"{self._adapter_path}/")
|
|
191
|
+
]
|
|
192
|
+
if service is not None:
|
|
193
|
+
devices = [device for device in devices if device.offers(service)]
|
|
194
|
+
return sorted(devices, key=lambda device: device.address)
|
|
195
|
+
|
|
196
|
+
async def device(self, address: str) -> ClassicDevice | None:
|
|
197
|
+
"""Return the device with this address, if BlueZ knows it."""
|
|
198
|
+
address = normalize_address(address)
|
|
199
|
+
return next((d for d in await self.devices() if d.address == address), None)
|
|
200
|
+
|
|
201
|
+
async def discover(self, seconds: float = DISCOVERY_SECONDS) -> list[ClassicDevice]:
|
|
202
|
+
"""Scan for Bluetooth Classic devices and return those that answered.
|
|
203
|
+
|
|
204
|
+
Devices that answer become known to BlueZ, so they can be paired.
|
|
205
|
+
Only discoverable devices answer.
|
|
206
|
+
"""
|
|
207
|
+
answered: dict[str, int | None] = {}
|
|
208
|
+
|
|
209
|
+
def on_answer(path: str, properties: dict[str, Any]) -> None:
|
|
210
|
+
# Low Energy devices found by other programs' scans also come
|
|
211
|
+
# and go meanwhile; only Classic devices report a device class.
|
|
212
|
+
if "Class" in properties or _is_inquiry_answer(properties):
|
|
213
|
+
answered[path] = _unwrap(properties.get("RSSI"))
|
|
214
|
+
|
|
215
|
+
async with (
|
|
216
|
+
self._scan_lock,
|
|
217
|
+
self._listening(on_answer, new_devices=True),
|
|
218
|
+
self._discovery(),
|
|
219
|
+
):
|
|
220
|
+
await asyncio.sleep(seconds)
|
|
221
|
+
found = []
|
|
222
|
+
for device in await self.devices():
|
|
223
|
+
if device.path in answered:
|
|
224
|
+
rssi = answered[device.path]
|
|
225
|
+
if rssi is not None:
|
|
226
|
+
device = replace(device, rssi=int(rssi))
|
|
227
|
+
found.append(device)
|
|
228
|
+
_LOGGER.debug("Discovery on %s found %s devices", self.adapter, len(found))
|
|
229
|
+
return found
|
|
230
|
+
|
|
231
|
+
async def check_presence(
|
|
232
|
+
self, address: str, seconds: float = PRESENCE_SECONDS
|
|
233
|
+
) -> PresenceResult:
|
|
234
|
+
"""Return whether a known device answers a short Classic scan.
|
|
235
|
+
|
|
236
|
+
This does not connect to the device, so it does not wake one that
|
|
237
|
+
wakes when connected to. A device answers only while it is on and
|
|
238
|
+
discoverable.
|
|
239
|
+
|
|
240
|
+
Raises:
|
|
241
|
+
DeviceNotFoundError: BlueZ does not know the device; discover or
|
|
242
|
+
pair it first.
|
|
243
|
+
"""
|
|
244
|
+
device = await self.device(address)
|
|
245
|
+
if device is None:
|
|
246
|
+
raise DeviceNotFoundError(f"{address} is not known on {self.adapter}")
|
|
247
|
+
answered = asyncio.Event()
|
|
248
|
+
changed: dict[str, Any] = {}
|
|
249
|
+
|
|
250
|
+
def on_change(path: str, properties: dict[str, Any]) -> None:
|
|
251
|
+
if path != device.path or answered.is_set():
|
|
252
|
+
return
|
|
253
|
+
for key, value in properties.items():
|
|
254
|
+
changed[key] = _summary(_unwrap(value))
|
|
255
|
+
if _is_inquiry_answer(properties):
|
|
256
|
+
answered.set()
|
|
257
|
+
|
|
258
|
+
loop = asyncio.get_running_loop()
|
|
259
|
+
async with self._scan_lock, self._listening(on_change, path=device.path):
|
|
260
|
+
started = loop.time()
|
|
261
|
+
async with self._discovery():
|
|
262
|
+
try:
|
|
263
|
+
async with asyncio.timeout(seconds):
|
|
264
|
+
await answered.wait()
|
|
265
|
+
except TimeoutError:
|
|
266
|
+
return PresenceResult(False, linked=device.connected)
|
|
267
|
+
return PresenceResult(
|
|
268
|
+
True,
|
|
269
|
+
after=loop.time() - started,
|
|
270
|
+
changed=changed,
|
|
271
|
+
linked=device.connected,
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
async def pair(
|
|
275
|
+
self,
|
|
276
|
+
address: str,
|
|
277
|
+
*,
|
|
278
|
+
pin: str = DEFAULT_PIN,
|
|
279
|
+
timeout: float = PAIR_TIMEOUT,
|
|
280
|
+
) -> ClassicDevice:
|
|
281
|
+
"""Pair with a known device, if not paired already.
|
|
282
|
+
|
|
283
|
+
A temporary agent answers for this device only: it confirms "just
|
|
284
|
+
works" pairing and gives ``pin`` if the device asks for one.
|
|
285
|
+
|
|
286
|
+
Raises:
|
|
287
|
+
DeviceNotFoundError: BlueZ does not know the device; discover it
|
|
288
|
+
first.
|
|
289
|
+
PairingError: Pairing failed or timed out.
|
|
290
|
+
"""
|
|
291
|
+
device = await self._known(address)
|
|
292
|
+
if device.paired:
|
|
293
|
+
return device
|
|
294
|
+
agent = PairingAgent(device.path, pin)
|
|
295
|
+
self._bus.export(AGENT_PATH, agent)
|
|
296
|
+
try:
|
|
297
|
+
await self._call(
|
|
298
|
+
BLUEZ_PATH,
|
|
299
|
+
AGENT_MANAGER_INTERFACE,
|
|
300
|
+
"RegisterAgent",
|
|
301
|
+
"os",
|
|
302
|
+
[AGENT_PATH, AGENT_CAPABILITY],
|
|
303
|
+
)
|
|
304
|
+
try:
|
|
305
|
+
async with asyncio.timeout(timeout):
|
|
306
|
+
await self._call(device.path, DEVICE_INTERFACE, "Pair")
|
|
307
|
+
except TimeoutError as err:
|
|
308
|
+
with contextlib.suppress(BluetoothClassicError):
|
|
309
|
+
await self._call(device.path, DEVICE_INTERFACE, "CancelPairing")
|
|
310
|
+
raise PairingError(f"Pairing with {device.address} timed out") from err
|
|
311
|
+
except BluetoothClassicError as err:
|
|
312
|
+
if "AlreadyExists" not in str(err):
|
|
313
|
+
raise PairingError(str(err)) from err
|
|
314
|
+
finally:
|
|
315
|
+
try:
|
|
316
|
+
await self._call(
|
|
317
|
+
BLUEZ_PATH,
|
|
318
|
+
AGENT_MANAGER_INTERFACE,
|
|
319
|
+
"UnregisterAgent",
|
|
320
|
+
"o",
|
|
321
|
+
[AGENT_PATH],
|
|
322
|
+
)
|
|
323
|
+
except BluetoothClassicError as err:
|
|
324
|
+
_LOGGER.debug("Could not unregister the pairing agent: %s", err)
|
|
325
|
+
finally:
|
|
326
|
+
self._bus.unexport(AGENT_PATH, agent)
|
|
327
|
+
return await self._known(address)
|
|
328
|
+
|
|
329
|
+
async def trust(self, address: str) -> ClassicDevice:
|
|
330
|
+
"""Mark a known device as trusted, if it is not already.
|
|
331
|
+
|
|
332
|
+
BlueZ then accepts the device's connections without asking. Some
|
|
333
|
+
devices drop a connection from a host that does not trust them, as
|
|
334
|
+
phones trust what they pair with.
|
|
335
|
+
|
|
336
|
+
Raises:
|
|
337
|
+
DeviceNotFoundError: BlueZ does not know the device.
|
|
338
|
+
"""
|
|
339
|
+
device = await self._known(address)
|
|
340
|
+
if not device.trusted:
|
|
341
|
+
await self._call(
|
|
342
|
+
device.path,
|
|
343
|
+
PROPERTIES_INTERFACE,
|
|
344
|
+
"Set",
|
|
345
|
+
"ssv",
|
|
346
|
+
[DEVICE_INTERFACE, "Trusted", Variant("b", True)],
|
|
347
|
+
)
|
|
348
|
+
return await self._known(address)
|
|
349
|
+
|
|
350
|
+
async def _known(self, address: str) -> ClassicDevice:
|
|
351
|
+
if (device := await self.device(address)) is None:
|
|
352
|
+
raise DeviceNotFoundError(f"{address} is not known on {self.adapter}")
|
|
353
|
+
return device
|
|
354
|
+
|
|
355
|
+
@contextlib.asynccontextmanager
|
|
356
|
+
async def _discovery(self) -> AsyncIterator[None]:
|
|
357
|
+
"""Run Classic-only discovery on the adapter for the block's length.
|
|
358
|
+
|
|
359
|
+
BlueZ keeps a discovery filter per client and merges them, so this
|
|
360
|
+
does not stop Low Energy scanning other programs have asked for.
|
|
361
|
+
"""
|
|
362
|
+
await self._call(
|
|
363
|
+
self._adapter_path,
|
|
364
|
+
ADAPTER_INTERFACE,
|
|
365
|
+
"SetDiscoveryFilter",
|
|
366
|
+
"a{sv}",
|
|
367
|
+
[{"Transport": Variant("s", TRANSPORT_BREDR)}],
|
|
368
|
+
)
|
|
369
|
+
await self._call(self._adapter_path, ADAPTER_INTERFACE, "StartDiscovery")
|
|
370
|
+
try:
|
|
371
|
+
yield
|
|
372
|
+
finally:
|
|
373
|
+
try:
|
|
374
|
+
await self._call(self._adapter_path, ADAPTER_INTERFACE, "StopDiscovery")
|
|
375
|
+
except BluetoothClassicError as err:
|
|
376
|
+
_LOGGER.debug("Could not stop discovery: %s", err)
|
|
377
|
+
|
|
378
|
+
@contextlib.asynccontextmanager
|
|
379
|
+
async def _listening(
|
|
380
|
+
self,
|
|
381
|
+
callback: Callable[[str, dict[str, Any]], None],
|
|
382
|
+
*,
|
|
383
|
+
path: str | None = None,
|
|
384
|
+
new_devices: bool = False,
|
|
385
|
+
) -> AsyncIterator[None]:
|
|
386
|
+
"""Call back with each device's changed properties during the block.
|
|
387
|
+
|
|
388
|
+
With ``path``, only that device's; otherwise every device on the
|
|
389
|
+
adapter. With ``new_devices``, devices BlueZ adds are reported too.
|
|
390
|
+
"""
|
|
391
|
+
where = f"path='{path}'" if path else f"path_namespace='{self._adapter_path}'"
|
|
392
|
+
rules = [
|
|
393
|
+
f"type='signal',interface='{PROPERTIES_INTERFACE}',"
|
|
394
|
+
f"member='PropertiesChanged',{where}"
|
|
395
|
+
]
|
|
396
|
+
if new_devices:
|
|
397
|
+
rules.append(
|
|
398
|
+
f"type='signal',interface='{OBJECT_MANAGER_INTERFACE}',"
|
|
399
|
+
"member='InterfacesAdded'"
|
|
400
|
+
)
|
|
401
|
+
prefix = f"{self._adapter_path}/"
|
|
402
|
+
|
|
403
|
+
def handler(message: Message) -> None:
|
|
404
|
+
if message.message_type != MessageType.SIGNAL or not message.body:
|
|
405
|
+
return
|
|
406
|
+
if (
|
|
407
|
+
message.member == "PropertiesChanged"
|
|
408
|
+
and message.body[0] == DEVICE_INTERFACE
|
|
409
|
+
and message.path
|
|
410
|
+
and (message.path == path if path else message.path.startswith(prefix))
|
|
411
|
+
):
|
|
412
|
+
callback(message.path, message.body[1])
|
|
413
|
+
elif (
|
|
414
|
+
new_devices
|
|
415
|
+
and message.member == "InterfacesAdded"
|
|
416
|
+
and str(message.body[0]).startswith(prefix)
|
|
417
|
+
and DEVICE_INTERFACE in message.body[1]
|
|
418
|
+
):
|
|
419
|
+
callback(message.body[0], message.body[1][DEVICE_INTERFACE])
|
|
420
|
+
|
|
421
|
+
added: list[str] = []
|
|
422
|
+
self._bus.add_message_handler(handler)
|
|
423
|
+
try:
|
|
424
|
+
for rule in rules:
|
|
425
|
+
await self._bus_call("AddMatch", rule)
|
|
426
|
+
added.append(rule)
|
|
427
|
+
yield
|
|
428
|
+
finally:
|
|
429
|
+
self._bus.remove_message_handler(handler)
|
|
430
|
+
for rule in added:
|
|
431
|
+
with contextlib.suppress(BluetoothClassicError):
|
|
432
|
+
await self._bus_call("RemoveMatch", rule)
|
|
433
|
+
|
|
434
|
+
async def _bus_call(self, member: str, rule: str) -> None:
|
|
435
|
+
await _call(
|
|
436
|
+
self._bus, DBUS_SERVICE, DBUS_PATH, DBUS_SERVICE, member, "s", [rule]
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
async def _call(
|
|
440
|
+
self,
|
|
441
|
+
path: str,
|
|
442
|
+
interface: str,
|
|
443
|
+
member: str,
|
|
444
|
+
signature: str = "",
|
|
445
|
+
body: Iterable[Any] = (),
|
|
446
|
+
) -> list[Any]:
|
|
447
|
+
return await _call(
|
|
448
|
+
self._bus, BLUEZ_SERVICE, path, interface, member, signature, body
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _choose_adapter(objects: _ManagedObjects, adapter: str | None) -> str:
|
|
453
|
+
adapters = sorted(
|
|
454
|
+
(path, interfaces[ADAPTER_INTERFACE])
|
|
455
|
+
for path, interfaces in objects.items()
|
|
456
|
+
if ADAPTER_INTERFACE in interfaces
|
|
457
|
+
)
|
|
458
|
+
if adapter is not None:
|
|
459
|
+
path = f"{BLUEZ_PATH}/{adapter}"
|
|
460
|
+
if any(candidate == path for candidate, _ in adapters):
|
|
461
|
+
return path
|
|
462
|
+
raise NoAdapterError(f"Bluetooth adapter {adapter} not found")
|
|
463
|
+
if not adapters:
|
|
464
|
+
raise NoAdapterError("No Bluetooth adapter found")
|
|
465
|
+
powered = [path for path, props in adapters if _unwrap(props.get("Powered"))]
|
|
466
|
+
return (powered or [adapters[0][0]])[0]
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
async def _managed_objects(bus: MessageBus) -> _ManagedObjects:
|
|
470
|
+
reply = await _call(
|
|
471
|
+
bus, BLUEZ_SERVICE, "/", OBJECT_MANAGER_INTERFACE, "GetManagedObjects"
|
|
472
|
+
)
|
|
473
|
+
return reply[0] if reply else {}
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
async def _call(
|
|
477
|
+
bus: MessageBus,
|
|
478
|
+
destination: str,
|
|
479
|
+
path: str,
|
|
480
|
+
interface: str,
|
|
481
|
+
member: str,
|
|
482
|
+
signature: str = "",
|
|
483
|
+
body: Iterable[Any] = (),
|
|
484
|
+
) -> list[Any]:
|
|
485
|
+
try:
|
|
486
|
+
reply = await bus.call(
|
|
487
|
+
Message(
|
|
488
|
+
destination=destination,
|
|
489
|
+
path=path,
|
|
490
|
+
interface=interface,
|
|
491
|
+
member=member,
|
|
492
|
+
signature=signature,
|
|
493
|
+
body=list(body),
|
|
494
|
+
)
|
|
495
|
+
)
|
|
496
|
+
except Exception as err:
|
|
497
|
+
raise BluetoothClassicError(f"{member} failed: {err}") from err
|
|
498
|
+
if reply is None:
|
|
499
|
+
raise BluetoothClassicError(f"{member} got no reply")
|
|
500
|
+
if reply.message_type == MessageType.ERROR:
|
|
501
|
+
raise BluetoothClassicError(f"{member} failed: {reply.error_name} {reply.body}")
|
|
502
|
+
return list(reply.body)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Constants for talking to BlueZ about Bluetooth Classic devices."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Final
|
|
6
|
+
|
|
7
|
+
BLUEZ_SERVICE: Final = "org.bluez"
|
|
8
|
+
BLUEZ_PATH: Final = "/org/bluez"
|
|
9
|
+
ADAPTER_INTERFACE: Final = "org.bluez.Adapter1"
|
|
10
|
+
DEVICE_INTERFACE: Final = "org.bluez.Device1"
|
|
11
|
+
AGENT_INTERFACE: Final = "org.bluez.Agent1"
|
|
12
|
+
AGENT_MANAGER_INTERFACE: Final = "org.bluez.AgentManager1"
|
|
13
|
+
OBJECT_MANAGER_INTERFACE: Final = "org.freedesktop.DBus.ObjectManager"
|
|
14
|
+
PROPERTIES_INTERFACE: Final = "org.freedesktop.DBus.Properties"
|
|
15
|
+
DBUS_SERVICE: Final = "org.freedesktop.DBus"
|
|
16
|
+
DBUS_PATH: Final = "/org/freedesktop/DBus"
|
|
17
|
+
|
|
18
|
+
# Where the pairing agent is exported on this library's bus connection.
|
|
19
|
+
AGENT_PATH: Final = "/org/bluetooth_classic/agent"
|
|
20
|
+
# The agent's capability: pairing needs no display or keyboard, which suits
|
|
21
|
+
# speakers, headphones and most other Classic devices without a screen.
|
|
22
|
+
AGENT_CAPABILITY: Final = "NoInputNoOutput"
|
|
23
|
+
# Answered when a device asks for a PIN; the usual default of older audio
|
|
24
|
+
# devices.
|
|
25
|
+
DEFAULT_PIN: Final = "0000"
|
|
26
|
+
|
|
27
|
+
# How long a discovery runs by default.
|
|
28
|
+
DISCOVERY_SECONDS: Final = 12.0
|
|
29
|
+
# How long a presence check waits for a device to answer. A device that is on
|
|
30
|
+
# and discoverable answers a Classic inquiry within a few seconds.
|
|
31
|
+
PRESENCE_SECONDS: Final = 5.0
|
|
32
|
+
# How long pairing may take before it is cancelled.
|
|
33
|
+
PAIR_TIMEOUT: Final = 45.0
|
|
34
|
+
|
|
35
|
+
# The discovery filter value that limits discovery to Bluetooth Classic.
|
|
36
|
+
TRANSPORT_BREDR: Final = "bredr"
|
|
37
|
+
|
|
38
|
+
# Device properties that come with a signal strength for reasons other than
|
|
39
|
+
# answering a Classic inquiry: Low Energy advertising, or a link changing.
|
|
40
|
+
NOT_INQUIRY: Final = frozenset(
|
|
41
|
+
{"ManufacturerData", "AdvertisingFlags", "ServiceData", "Connected"}
|
|
42
|
+
)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Errors raised by bluetooth-classic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BluetoothClassicError(Exception):
|
|
7
|
+
"""BlueZ could not be reached, or refused a request."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class NoAdapterError(BluetoothClassicError):
|
|
11
|
+
"""No Bluetooth adapter is available, or the one asked for is missing."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DeviceNotFoundError(BluetoothClassicError):
|
|
15
|
+
"""BlueZ does not know the device."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PairingError(BluetoothClassicError):
|
|
19
|
+
"""The device could not be paired."""
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Models for Bluetooth Classic devices and what a scan found."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class ClassicDevice:
|
|
11
|
+
"""A Bluetooth device as BlueZ knows it."""
|
|
12
|
+
|
|
13
|
+
#: Address in upper-case colon form, such as ``"00:11:22:33:44:55"``.
|
|
14
|
+
address: str
|
|
15
|
+
#: The device's name, or its alias when it has not sent a name.
|
|
16
|
+
name: str | None
|
|
17
|
+
#: BlueZ's object path for the device.
|
|
18
|
+
path: str
|
|
19
|
+
#: The adapter it is known on, such as ``"hci0"``.
|
|
20
|
+
adapter: str
|
|
21
|
+
paired: bool = False
|
|
22
|
+
trusted: bool = False
|
|
23
|
+
connected: bool = False
|
|
24
|
+
#: Service class UUIDs, lower case. Before pairing, only those the
|
|
25
|
+
#: device advertises in a scan; the full list is read when it is paired.
|
|
26
|
+
uuids: frozenset[str] = frozenset()
|
|
27
|
+
#: The Classic Class of Device, which only Classic devices report.
|
|
28
|
+
device_class: int | None = None
|
|
29
|
+
#: Signal strength from the latest scan answer, if BlueZ has one.
|
|
30
|
+
rssi: int | None = None
|
|
31
|
+
|
|
32
|
+
def offers(self, service: str) -> bool:
|
|
33
|
+
"""Return whether the device lists a service, by its UUID."""
|
|
34
|
+
return service.lower() in self.uuids
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class PresenceResult:
|
|
39
|
+
"""Whether a device answered a short Classic scan, and how."""
|
|
40
|
+
|
|
41
|
+
#: Whether it answered within the time allowed.
|
|
42
|
+
present: bool
|
|
43
|
+
#: Seconds until it answered.
|
|
44
|
+
after: float | None = None
|
|
45
|
+
#: Device properties BlueZ changed up to the answer, summarised for logs.
|
|
46
|
+
#: A Classic inquiry answer changes the signal strength (``RSSI``), often
|
|
47
|
+
#: with ``TxPower``.
|
|
48
|
+
changed: dict[str, Any] = field(default_factory=dict)
|
|
49
|
+
#: Whether BlueZ already had a link to the device when the scan began.
|
|
50
|
+
linked: bool = False
|
|
File without changes
|