ha-ble-pinning 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.
@@ -0,0 +1,89 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+ workflow_dispatch:
7
+ schedule:
8
+ # Weekly check for habluetooth / bleak changes that break the pin.
9
+ - cron: "17 9 * * 1"
10
+
11
+ permissions:
12
+ contents: read
13
+ issues: write
14
+
15
+ jobs:
16
+ test:
17
+ name: tests (${{ matrix.target }})
18
+ runs-on: ubuntu-latest
19
+ strategy:
20
+ fail-fast: false
21
+ matrix:
22
+ # stable: the versions the latest Home Assistant release pins
23
+ # dev: the versions Home Assistant's dev branch pins (next release)
24
+ # latest: the newest releases on PyPI
25
+ target: [stable, dev, latest]
26
+ steps:
27
+ - uses: actions/checkout@v4
28
+
29
+ - uses: actions/setup-python@v5
30
+ with:
31
+ python-version: "3.14"
32
+
33
+ - name: Resolve library versions
34
+ id: versions
35
+ env:
36
+ GH_TOKEN: ${{ github.token }}
37
+ TARGET: ${{ matrix.target }}
38
+ run: |
39
+ set -euo pipefail
40
+ packages="habluetooth bleak bleak-retry-connector dbus-fast"
41
+ if [ "$TARGET" = latest ]; then
42
+ echo "spec=$packages" >> "$GITHUB_OUTPUT"
43
+ exit 0
44
+ fi
45
+ if [ "$TARGET" = stable ]; then
46
+ ref=$(gh api repos/home-assistant/core/releases/latest --jq .tag_name)
47
+ else
48
+ ref=dev
49
+ fi
50
+ constraints=$(gh api -H "Accept: application/vnd.github.raw" \
51
+ "repos/home-assistant/core/contents/homeassistant/package_constraints.txt?ref=$ref")
52
+ spec=""
53
+ for p in $packages; do
54
+ line=$(printf '%s\n' "$constraints" | grep -iE "^${p}==" || true)
55
+ if [ -z "$line" ]; then
56
+ echo "::error::$p is not pinned in Home Assistant $ref"
57
+ exit 1
58
+ fi
59
+ spec="$spec $line"
60
+ done
61
+ echo "Home Assistant $ref pins:$spec"
62
+ echo "spec=$spec" >> "$GITHUB_OUTPUT"
63
+
64
+ - name: Install
65
+ run: |
66
+ python -m pip install --upgrade pip
67
+ python -m pip install -e . ${{ steps.versions.outputs.spec }} pytest pytest-asyncio
68
+ python -m pip list | grep -iE "habluetooth|bleak|dbus-fast"
69
+
70
+ - name: Test
71
+ run: python -m pytest -v
72
+
73
+ - name: Open an issue when the scheduled check fails
74
+ if: failure() && github.event_name == 'schedule'
75
+ env:
76
+ GH_TOKEN: ${{ github.token }}
77
+ TARGET: ${{ matrix.target }}
78
+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
79
+ run: |
80
+ title="Compatibility check failed: $TARGET"
81
+ body="The weekly check against **$TARGET** library versions failed: $RUN_URL
82
+
83
+ A failing \`test_the_private_hooks_still_exist\` means habluetooth renamed or removed a method the pinned client overrides; until fixed, \`pinned_client_class()\` returns None and integrations fall back to Home Assistant's own routing (with the post-connect path check)."
84
+ existing=$(gh issue list --state open --search "\"$title\" in:title" --json number --jq '.[0].number')
85
+ if [ -n "$existing" ]; then
86
+ gh issue comment "$existing" --body "Still failing: $RUN_URL"
87
+ else
88
+ gh issue create --title "$title" --body "$body"
89
+ fi
@@ -0,0 +1,31 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ environment: pypi
11
+ permissions:
12
+ id-token: write # PyPI trusted publishing; no API token is stored
13
+ contents: read
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.14"
20
+
21
+ - name: Check the tag matches the package version
22
+ run: |
23
+ version=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
24
+ test "v$version" = "${GITHUB_REF_NAME}" || { echo "::error::tag ${GITHUB_REF_NAME} != v$version"; exit 1; }
25
+
26
+ - name: Build
27
+ run: |
28
+ python -m pip install --upgrade build
29
+ python -m build
30
+
31
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .pytest_cache/
8
+ CLAUDE.md
9
+ .vscode/
10
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pete Hurth
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.
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.5
2
+ Name: ha-ble-pinning
3
+ Version: 0.1.0
4
+ Summary: Pin a Home Assistant Bluetooth connection to chosen adapters or proxies (for bonded devices and dedicated proxies).
5
+ Project-URL: Homepage, https://github.com/phurth/ha-ble-pinning
6
+ Project-URL: Issues, https://github.com/phurth/ha-ble-pinning/issues
7
+ Author: phurth
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Framework :: AsyncIO
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.13
15
+ Requires-Dist: bleak
16
+ Requires-Dist: bleak-retry-connector
17
+ Provides-Extra: test
18
+ Requires-Dist: dbus-fast; extra == 'test'
19
+ Requires-Dist: habluetooth; extra == 'test'
20
+ Requires-Dist: pytest; extra == 'test'
21
+ Requires-Dist: pytest-asyncio; extra == 'test'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # ha-ble-pinning
25
+
26
+ Make a Home Assistant custom integration connect to a Bluetooth device **only through the adapters or proxies you choose**.
27
+
28
+ > **AI-written code.** Every line of code, test and documentation in this repository was written by an AI model (Anthropic's Claude), working under the direction of the maintainer, who reviewed, tested and deployed it. It has been exercised against real hardware (see [Status](#status)), but judge it as you would any third-party code before depending on it.
29
+
30
+ > **Not affiliated** with Home Assistant, the Open Home Foundation or the habluetooth project. It relies on private internals of Home Assistant's Bluetooth library; see [Caveats](#caveats).
31
+
32
+ ## The problem
33
+
34
+ In Home Assistant, an integration does not choose which Bluetooth adapter or ESPHome proxy a connection goes through. Home Assistant's Bluetooth library ([habluetooth](https://github.com/Bluetooth-Devices/habluetooth)) wraps every `BleakClient`. The wrapper keeps only the **address** of the device the integration passes in, and when it connects it ranks every scanner that has heard that device by signal strength, free connection slots, connects in progress and recent failures, then uses the winner. Passing a `BLEDevice` from a particular adapter, or `adapter="hci1"`, makes no difference.
35
+
36
+ That is the right default for most devices, but it breaks two kinds of setup:
37
+
38
+ - **Devices that need a bond (pairing).** BlueZ stores a bond, the long-term key, per adapter, and only the adapter that made the bond can open an encrypted link. On a host with a second adapter, or with an ESPHome proxy nearby, Home Assistant can route the connection somewhere without the bond. The device then refuses with *insufficient authentication*. On a second local adapter, a GATT read can even hang once the device drops the unencrypted link, which leaves the integration stuck until Home Assistant restarts. Which path wins depends on signal strength and load at that moment, so the failure comes and goes.
39
+ - **Dedicated proxies.** Two devices, each with its own proxy nearby, where both proxies hear both devices. Each proxy keeps taking over the other's device as signal strengths shift ([habluetooth #602](https://github.com/Bluetooth-Devices/habluetooth/issues/602)).
40
+
41
+ Home Assistant has no per-device pin. Both cases are open upstream ([#602](https://github.com/Bluetooth-Devices/habluetooth/issues/602), [#628](https://github.com/Bluetooth-Devices/habluetooth/issues/628)), and the maintainer has said a pin would defeat the purpose of the library. So this lives outside it, for the integrations that need it.
42
+
43
+ ## How it works
44
+
45
+ `pinned_client_class()` returns a subclass of Home Assistant's own client wrapper (`HaBleakClientWrapper`) that overrides **one** method: the one that picks the connection path. Instead of every scanner that heard the device, habluetooth is offered:
46
+
47
+ 1. the scanners in `pinned_sources`, strongest signal first;
48
+ 2. only if none of those can take the connection, the scanners in `fallback_sources`.
49
+
50
+ Everything else stays with Home Assistant: connection-slot accounting, connect tracking, connection parameters, failure counting, and disconnecting clients when a scanner goes away. If no allowed scanner can take the connection, because none has heard the device recently or none has a free slot, connecting raises `PinnedAdapterUnavailable`, a `BleakError`. It never quietly falls through to a path you didn't allow; your integration's normal retry logic tries again later.
51
+
52
+ The pin goes through `bleak_retry_connector.establish_connection`, which passes extra keyword arguments to the client class. `establish_pinned_connection()` does that for you and then **checks where the link really landed**. It reads habluetooth's record of the scanner used and bleak's BlueZ device path (`/org/bluez/hciN/dev_…`). If the link is on a path that isn't allowed, it disconnects quietly, without calling your disconnect callback, and raises `PinnedAdapterUnavailable`. That check also covers a future habluetooth version where the override no longer takes effect.
53
+
54
+ For bonded devices, `async_get_bonded_device_paths(address)` asks BlueZ (over D-Bus) which local adapters hold a bond for the device. That is the natural set to pin to.
55
+
56
+ ## Usage
57
+
58
+ ```python
59
+ from ha_ble_pinning import (
60
+ PinnedAdapterUnavailable,
61
+ async_get_bonded_device_paths,
62
+ establish_pinned_connection,
63
+ )
64
+
65
+ bonded = await async_get_bonded_device_paths(address) # {adapter MAC: BlueZ device path}
66
+
67
+ if bonded:
68
+ client = await establish_pinned_connection(
69
+ ble_device,
70
+ address,
71
+ pinned_sources=bonded.keys(), # only the adapter(s) holding the bond
72
+ local_device_paths=bonded.values(), # makes the post-connect check exact
73
+ disconnected_callback=self._on_disconnect,
74
+ )
75
+ else:
76
+ # No bond: let Home Assistant route as usual.
77
+ client = await establish_connection(BleakClient, ble_device, address, ...)
78
+ ```
79
+
80
+ Pin to a dedicated proxy by its source (the proxy's MAC as Home Assistant reports it):
81
+
82
+ ```python
83
+ client = await establish_pinned_connection(ble_device, address, pinned_sources=[PROXY_MAC])
84
+ ```
85
+
86
+ Or keep your own `establish_connection` call and use the client class directly:
87
+
88
+ ```python
89
+ from ha_ble_pinning import pinned_client_class
90
+
91
+ cls = pinned_client_class() # None if this Home Assistant version lacks the hooks
92
+ client = await establish_connection(
93
+ cls or BleakClient, ble_device, address, pinned_sources={ADAPTER_MAC}
94
+ )
95
+ ```
96
+
97
+ Each pinned connect logs which path it used and which it skipped, and the path Home Assistant would have picked when the pin overrode it:
98
+
99
+ ```
100
+ AA:BB:CC:00:00:01: connecting through hci1 (11:11:11:11:11:11) (RSSI -60), a pinned path;
101
+ not using hci0 (22:22:22:22:22:22) (RSSI -40) (Home Assistant would have used hci0 …)
102
+ ```
103
+
104
+ ### `fallback_sources`
105
+
106
+ Use it for a path that has worked before but should only be the second choice, such as a proxy that holds its own bond. It is tried only when no pinned scanner can take the connection, so a louder but stale fallback can never win over a working pinned adapter.
107
+
108
+ ## When not to use it
109
+
110
+ - **Devices that don't need a particular path.** Home Assistant's own routing (best signal, free slots, failover) is better.
111
+ - **Home Assistant core integrations.** Core does not accept code that relies on private internals. This is for custom integrations.
112
+ - **A broken pinned adapter.** If the pinned adapter itself has stopped working (it scans but can't connect, which happens with some USB dongles), pinning means waiting instead of failing some other way. The fix is to replug or replace the adapter, or to pair through a different one.
113
+
114
+ ## Caveats
115
+
116
+ - **Private internals.** It overrides two private habluetooth methods, `_async_get_best_available_backend_and_device` and `_async_get_backend_for_ble_device`. `pinned_client_class()` checks that both exist and returns `None` when they don't, with a logged warning. `establish_pinned_connection()` then connects through Home Assistant's own client and still refuses a link on a disallowed path.
117
+ - **Weekly breakage check.** A [weekly CI job](.github/workflows/ci.yml) runs the tests against the versions pinned by the latest Home Assistant release, by Home Assistant's `dev` branch, and by the newest PyPI releases. It opens an issue in this repository when one fails. The integration tests drive the real `HaBleakClientWrapper.connect` and `establish_connection`, with stand-in scanners and backends.
118
+ - **Linux/BlueZ for bond lookups.** `async_get_bonded_device_paths()` needs BlueZ on D-Bus, as on Home Assistant OS. Pinning by source works with any scanner type.
119
+
120
+ ## Status
121
+
122
+ Used by two custom integrations, [ha-onecontrol](https://github.com/phurth/ha-onecontrol) (Lippert OneControl RV gateways) and [ha-gopower](https://github.com/phurth/ha-gopower) (GoPower solar controllers). Tested on Home Assistant 2026.11 (habluetooth 7.1.x, bleak 3.x):
123
+
124
+ - a host with one local adapter and an ESPHome proxy, where Home Assistant had routed a bonded gateway through the proxy;
125
+ - a host with two local adapters and a proxy, where it now consistently uses the bonded adapter even when another is louder;
126
+ - a host with two local adapters, where Home Assistant had preferred the adapter without the bond: the pin consistently chose the bonded one. A working connection there is still awaiting confirmation, because that adapter turned out to be faulty.
127
+
128
+ Version 0.1.0. Install it by adding `"ha-ble-pinning==0.1.0"` to your integration's `manifest.json` `requirements`. It has no Home Assistant imports and no dependencies beyond what Home Assistant already ships.
129
+
130
+ ## License
131
+
132
+ MIT
@@ -0,0 +1,109 @@
1
+ # ha-ble-pinning
2
+
3
+ Make a Home Assistant custom integration connect to a Bluetooth device **only through the adapters or proxies you choose**.
4
+
5
+ > **AI-written code.** Every line of code, test and documentation in this repository was written by an AI model (Anthropic's Claude), working under the direction of the maintainer, who reviewed, tested and deployed it. It has been exercised against real hardware (see [Status](#status)), but judge it as you would any third-party code before depending on it.
6
+
7
+ > **Not affiliated** with Home Assistant, the Open Home Foundation or the habluetooth project. It relies on private internals of Home Assistant's Bluetooth library; see [Caveats](#caveats).
8
+
9
+ ## The problem
10
+
11
+ In Home Assistant, an integration does not choose which Bluetooth adapter or ESPHome proxy a connection goes through. Home Assistant's Bluetooth library ([habluetooth](https://github.com/Bluetooth-Devices/habluetooth)) wraps every `BleakClient`. The wrapper keeps only the **address** of the device the integration passes in, and when it connects it ranks every scanner that has heard that device by signal strength, free connection slots, connects in progress and recent failures, then uses the winner. Passing a `BLEDevice` from a particular adapter, or `adapter="hci1"`, makes no difference.
12
+
13
+ That is the right default for most devices, but it breaks two kinds of setup:
14
+
15
+ - **Devices that need a bond (pairing).** BlueZ stores a bond, the long-term key, per adapter, and only the adapter that made the bond can open an encrypted link. On a host with a second adapter, or with an ESPHome proxy nearby, Home Assistant can route the connection somewhere without the bond. The device then refuses with *insufficient authentication*. On a second local adapter, a GATT read can even hang once the device drops the unencrypted link, which leaves the integration stuck until Home Assistant restarts. Which path wins depends on signal strength and load at that moment, so the failure comes and goes.
16
+ - **Dedicated proxies.** Two devices, each with its own proxy nearby, where both proxies hear both devices. Each proxy keeps taking over the other's device as signal strengths shift ([habluetooth #602](https://github.com/Bluetooth-Devices/habluetooth/issues/602)).
17
+
18
+ Home Assistant has no per-device pin. Both cases are open upstream ([#602](https://github.com/Bluetooth-Devices/habluetooth/issues/602), [#628](https://github.com/Bluetooth-Devices/habluetooth/issues/628)), and the maintainer has said a pin would defeat the purpose of the library. So this lives outside it, for the integrations that need it.
19
+
20
+ ## How it works
21
+
22
+ `pinned_client_class()` returns a subclass of Home Assistant's own client wrapper (`HaBleakClientWrapper`) that overrides **one** method: the one that picks the connection path. Instead of every scanner that heard the device, habluetooth is offered:
23
+
24
+ 1. the scanners in `pinned_sources`, strongest signal first;
25
+ 2. only if none of those can take the connection, the scanners in `fallback_sources`.
26
+
27
+ Everything else stays with Home Assistant: connection-slot accounting, connect tracking, connection parameters, failure counting, and disconnecting clients when a scanner goes away. If no allowed scanner can take the connection, because none has heard the device recently or none has a free slot, connecting raises `PinnedAdapterUnavailable`, a `BleakError`. It never quietly falls through to a path you didn't allow; your integration's normal retry logic tries again later.
28
+
29
+ The pin goes through `bleak_retry_connector.establish_connection`, which passes extra keyword arguments to the client class. `establish_pinned_connection()` does that for you and then **checks where the link really landed**. It reads habluetooth's record of the scanner used and bleak's BlueZ device path (`/org/bluez/hciN/dev_…`). If the link is on a path that isn't allowed, it disconnects quietly, without calling your disconnect callback, and raises `PinnedAdapterUnavailable`. That check also covers a future habluetooth version where the override no longer takes effect.
30
+
31
+ For bonded devices, `async_get_bonded_device_paths(address)` asks BlueZ (over D-Bus) which local adapters hold a bond for the device. That is the natural set to pin to.
32
+
33
+ ## Usage
34
+
35
+ ```python
36
+ from ha_ble_pinning import (
37
+ PinnedAdapterUnavailable,
38
+ async_get_bonded_device_paths,
39
+ establish_pinned_connection,
40
+ )
41
+
42
+ bonded = await async_get_bonded_device_paths(address) # {adapter MAC: BlueZ device path}
43
+
44
+ if bonded:
45
+ client = await establish_pinned_connection(
46
+ ble_device,
47
+ address,
48
+ pinned_sources=bonded.keys(), # only the adapter(s) holding the bond
49
+ local_device_paths=bonded.values(), # makes the post-connect check exact
50
+ disconnected_callback=self._on_disconnect,
51
+ )
52
+ else:
53
+ # No bond: let Home Assistant route as usual.
54
+ client = await establish_connection(BleakClient, ble_device, address, ...)
55
+ ```
56
+
57
+ Pin to a dedicated proxy by its source (the proxy's MAC as Home Assistant reports it):
58
+
59
+ ```python
60
+ client = await establish_pinned_connection(ble_device, address, pinned_sources=[PROXY_MAC])
61
+ ```
62
+
63
+ Or keep your own `establish_connection` call and use the client class directly:
64
+
65
+ ```python
66
+ from ha_ble_pinning import pinned_client_class
67
+
68
+ cls = pinned_client_class() # None if this Home Assistant version lacks the hooks
69
+ client = await establish_connection(
70
+ cls or BleakClient, ble_device, address, pinned_sources={ADAPTER_MAC}
71
+ )
72
+ ```
73
+
74
+ Each pinned connect logs which path it used and which it skipped, and the path Home Assistant would have picked when the pin overrode it:
75
+
76
+ ```
77
+ AA:BB:CC:00:00:01: connecting through hci1 (11:11:11:11:11:11) (RSSI -60), a pinned path;
78
+ not using hci0 (22:22:22:22:22:22) (RSSI -40) (Home Assistant would have used hci0 …)
79
+ ```
80
+
81
+ ### `fallback_sources`
82
+
83
+ Use it for a path that has worked before but should only be the second choice, such as a proxy that holds its own bond. It is tried only when no pinned scanner can take the connection, so a louder but stale fallback can never win over a working pinned adapter.
84
+
85
+ ## When not to use it
86
+
87
+ - **Devices that don't need a particular path.** Home Assistant's own routing (best signal, free slots, failover) is better.
88
+ - **Home Assistant core integrations.** Core does not accept code that relies on private internals. This is for custom integrations.
89
+ - **A broken pinned adapter.** If the pinned adapter itself has stopped working (it scans but can't connect, which happens with some USB dongles), pinning means waiting instead of failing some other way. The fix is to replug or replace the adapter, or to pair through a different one.
90
+
91
+ ## Caveats
92
+
93
+ - **Private internals.** It overrides two private habluetooth methods, `_async_get_best_available_backend_and_device` and `_async_get_backend_for_ble_device`. `pinned_client_class()` checks that both exist and returns `None` when they don't, with a logged warning. `establish_pinned_connection()` then connects through Home Assistant's own client and still refuses a link on a disallowed path.
94
+ - **Weekly breakage check.** A [weekly CI job](.github/workflows/ci.yml) runs the tests against the versions pinned by the latest Home Assistant release, by Home Assistant's `dev` branch, and by the newest PyPI releases. It opens an issue in this repository when one fails. The integration tests drive the real `HaBleakClientWrapper.connect` and `establish_connection`, with stand-in scanners and backends.
95
+ - **Linux/BlueZ for bond lookups.** `async_get_bonded_device_paths()` needs BlueZ on D-Bus, as on Home Assistant OS. Pinning by source works with any scanner type.
96
+
97
+ ## Status
98
+
99
+ Used by two custom integrations, [ha-onecontrol](https://github.com/phurth/ha-onecontrol) (Lippert OneControl RV gateways) and [ha-gopower](https://github.com/phurth/ha-gopower) (GoPower solar controllers). Tested on Home Assistant 2026.11 (habluetooth 7.1.x, bleak 3.x):
100
+
101
+ - a host with one local adapter and an ESPHome proxy, where Home Assistant had routed a bonded gateway through the proxy;
102
+ - a host with two local adapters and a proxy, where it now consistently uses the bonded adapter even when another is louder;
103
+ - a host with two local adapters, where Home Assistant had preferred the adapter without the bond: the pin consistently chose the bonded one. A working connection there is still awaiting confirmation, because that adapter turned out to be faulty.
104
+
105
+ Version 0.1.0. Install it by adding `"ha-ble-pinning==0.1.0"` to your integration's `manifest.json` `requirements`. It has no Home Assistant imports and no dependencies beyond what Home Assistant already ships.
106
+
107
+ ## License
108
+
109
+ MIT
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ha-ble-pinning"
7
+ version = "0.1.0"
8
+ description = "Pin a Home Assistant Bluetooth connection to chosen adapters or proxies (for bonded devices and dedicated proxies)."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.13"
12
+ authors = [{ name = "phurth" }]
13
+ classifiers = [
14
+ "Framework :: AsyncIO",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Operating System :: POSIX :: Linux",
17
+ "Programming Language :: Python :: 3",
18
+ ]
19
+ # bleak, bleak-retry-connector, habluetooth and dbus-fast are provided by Home
20
+ # Assistant; no versions are pinned here so installing into Home Assistant
21
+ # never conflicts with its own constraints.
22
+ dependencies = ["bleak", "bleak-retry-connector"]
23
+
24
+ [project.optional-dependencies]
25
+ test = ["habluetooth", "dbus-fast", "pytest", "pytest-asyncio"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/phurth/ha-ble-pinning"
29
+ Issues = "https://github.com/phurth/ha-ble-pinning/issues"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/ha_ble_pinning"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
36
+ pythonpath = ["src"]
37
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,30 @@
1
+ """Pin a Home Assistant Bluetooth connection to chosen adapters or proxies."""
2
+
3
+ from .bluez import async_get_bonded_device_paths, bonded_device_paths_in
4
+ from .client import (
5
+ PinnedAdapterUnavailable,
6
+ make_pinned_client_class,
7
+ normalize_source,
8
+ pinned_candidates,
9
+ pinned_client_class,
10
+ stock_choice,
11
+ )
12
+ from .connect import establish_pinned_connection
13
+ from .path import ConnectionPath, connection_path, path_matches_pin
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ __all__ = [
18
+ "ConnectionPath",
19
+ "PinnedAdapterUnavailable",
20
+ "async_get_bonded_device_paths",
21
+ "bonded_device_paths_in",
22
+ "connection_path",
23
+ "establish_pinned_connection",
24
+ "make_pinned_client_class",
25
+ "normalize_source",
26
+ "path_matches_pin",
27
+ "pinned_candidates",
28
+ "pinned_client_class",
29
+ "stock_choice",
30
+ ]
@@ -0,0 +1,75 @@
1
+ """Which local adapter holds a BlueZ bond (pairing) for a device."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+
8
+ _LOGGER = logging.getLogger(__name__)
9
+
10
+ ADAPTER_IFACE = "org.bluez.Adapter1"
11
+ DEVICE_IFACE = "org.bluez.Device1"
12
+
13
+
14
+ def _unwrap(value: Any) -> Any:
15
+ """Return the payload of a dbus-fast Variant (or the value itself)."""
16
+ return value.value if hasattr(value, "value") else value
17
+
18
+
19
+ def bonded_device_paths_in(objects: dict, address: str) -> dict[str, str]:
20
+ """Map each adapter MAC holding a bond for *address* to its device path.
21
+
22
+ *objects* is a BlueZ ``GetManagedObjects`` result. BlueZ keeps one device
23
+ object, and one bond, per adapter (``/org/bluez/hci0/dev_…``,
24
+ ``/org/bluez/hci1/dev_…``).
25
+ """
26
+ target = address.upper()
27
+ paths: dict[str, str] = {}
28
+ for path_str, interfaces in objects.items():
29
+ path = str(path_str)
30
+ device = interfaces.get(DEVICE_IFACE)
31
+ if device is None or not _unwrap(device.get("Paired")):
32
+ continue
33
+ device_address = _unwrap(device.get("Address"))
34
+ if device_address is not None:
35
+ if str(device_address).upper() != target:
36
+ continue
37
+ elif target.replace(":", "_") not in path.upper():
38
+ continue
39
+ adapter = objects.get(path.rsplit("/", 1)[0], {}).get(ADAPTER_IFACE, {})
40
+ adapter_mac = _unwrap(adapter.get("Address"))
41
+ if adapter_mac is not None:
42
+ paths[str(adapter_mac).upper()] = path
43
+ return dict(sorted(paths.items()))
44
+
45
+
46
+ async def async_get_bonded_device_paths(address: str) -> dict[str, str]:
47
+ """Return ``{adapter MAC: BlueZ device path}`` for each adapter bonded to *address*.
48
+
49
+ Queries BlueZ over D-Bus (``dbus-fast``, which Home Assistant ships).
50
+ Returns an empty dict when BlueZ or D-Bus is unavailable or on any error.
51
+ """
52
+ try:
53
+ from dbus_fast import BusType, Message, MessageType # noqa: PLC0415
54
+ from dbus_fast.aio import MessageBus # noqa: PLC0415
55
+ except ImportError:
56
+ return {}
57
+ try:
58
+ bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
59
+ try:
60
+ reply = await bus.call(
61
+ Message(
62
+ destination="org.bluez",
63
+ path="/",
64
+ interface="org.freedesktop.DBus.ObjectManager",
65
+ member="GetManagedObjects",
66
+ )
67
+ )
68
+ finally:
69
+ bus.disconnect()
70
+ if reply.message_type == MessageType.ERROR or not reply.body:
71
+ return {}
72
+ return bonded_device_paths_in(reply.body[0], address)
73
+ except Exception as exc: # noqa: BLE001
74
+ _LOGGER.debug("Could not read BlueZ bonds for %s: %s", address, exc)
75
+ return {}