Skip to main content

blesession

PyPI Python versions CI License: MIT

One BLE session, instrumented — for Home Assistant BLE integrations built on bleak.

Connect, subscribe to notifications, exchange frames with per-step timeouts, disconnect — and come out the other side with where the time went, where it failed, which radio it went over, and one sentence on what that most likely means, ready to publish as sensor attributes so a failed session at 3 am can be read off the entity without debug logging.

Status

Verified on device over a Bluetooth proxy. The library is tested without Home Assistant (pytest).

Where to start

you want to read
learn about or set up a Bluetooth proxy user guide (한국어): how proxies work, hardware, installation, Home Assistant registration and connection checks; no library installation required
troubleshoot a Bluetooth device common troubleshooting (한국어): discovery versus connection, failure stages, route facts and safe recovery; use with your integration’s device-specific guide
integrate a device docs/adopting.md: a whole integration end to end, what the library writes for you, how to test it without bleak or Home Assistant
standardize an integration's diagnostics diagnostics implementation guide (한국어): recording, entities, updates, downloads, redaction and adoption checks
know exactly what a call guarantees docs/contract.md: every public name, error, report key, cause key and callback shape, and the versioning rule
understand why it is shaped this way docs/design.md: what belongs here, what deliberately does not, how a Bluetooth-proxy route works without importing Home Assistant
see what changed CHANGELOG.md

Adopting needs only this repository: the guide and the contract are written so you can integrate a device without reading the source.

The design is extracted from integrations that already carry this instrumentation (and had drifted apart), and is meant to be adopted by others that today each hand-roll the same notification wait and have no failure attribution at all.

Install

pip install blesession

Requires Python 3.13+. The core depends only on bleak / bleak-retry-connector; blesession.hass imports Home Assistant lazily and is not needed outside HA.

What it provides

piece one line
ble_session() connect inside the block (or reuse a link left up), watch the link, bounded disconnect in finally
Notifications queued replies from one characteristic; every wait names its step and ends the moment the link drops; request() is write-then-reply
write_chunks() / guarded_write() a payload as consecutive writes; every write is bounded and a dropped link ends it as SessionDropped
characteristic_or_raise() the service/characteristic lookup with required properties and write size, or GattMismatch
write_limit() the payload one write can carry (characteristic limit, else MTU less the ATT header, else your default) and which of the three it was
SessionTrace nested stage timings; the innermost stage an exception escaped from
stage vocabulary unreachable · connect · session · auth · transfer · finish · disconnect, plus a device detail
run_attempts() the lock-per-attempt / fresh-handle-per-attempt contract; policy stays yours
blesession.hass.ble_device_or_raise() the handle, resolved fresh inside the attempt, or Unreachable
blesession.hass.radio_facts() via, via_type, rssi, paths, advertised_via as scanner names, and via_unconfirmed (a flag)
link.py the one place that probes bleak / habluetooth internals for the radio a link took
blesession.testing FakeClient / fake_connect() so every integration's tests fake bleak the same way
build_report() fixed attribute key order; generic likely-cause sentences with a translatable key, your device sentences first
SessionReports the last session, the last failure (with its count and time) and the last retried attempt, so a success does not erase the evidence
errors ConnectionError subclasses so an off device never becomes a traceback; retryable says whether another attempt can help; DeviceError is yours to raise for a device-reported fault
Failure what your cause callback receives: the stage, the error, the radio facts

What it does not provide

Retry counts, backoff, packet pacing, lock scope, bonding and pairing, cooldowns, advertisement parsing, protocol frames. Those are the parts each integration learned from its own device and keeps.

Layout

src/blesession/         pure Python + bleak, tested without Home Assistant
src/blesession/hass.py  imports homeassistant lazily; only used inside HA
docs/adopting.md        how to use it, with a whole integration
docs/contract.md        what every name guarantees; versioning and deprecation
docs/design.md          why it is shaped this way
from blesession import Notifications, SessionTrace, ble_session, build_report, stages
from blesession.hass import radio_facts

trace = SessionTrace(stage_map={"start": stages.AUTH})
try:
    async with ble_session(ble_device, trace=trace) as client:
        async with Notifications(client, NOTIFY_UUID, settle=0.5) as replies:
            with trace.timed("start"):
                await replies.request(WRITE_UUID, START, timeout=5, step="start")
            with trace.timed("transfer"):
                ...
except ConnectionError as exc:          # every session error is one
    report = build_report(operation="write", trace=trace, exc=exc,
                          facts=radio_facts(hass, address, trace.link), noun="device")
    # {'operation': 'write', 'success': False, 'error': ..., 'failed_stage': 'auth',
    #  'failed_detail': 'start', 'likely_cause': ..., 'via': ..., 'connect_s': ..., ...}

Development & testing

pip install -e ".[dev]"
pytest                 # unit tests; FakeClient fakes bleak the same way for adopters
ruff check . && ruff format --check .
mypy                   # type-check src/ (the package ships py.typed)
python -m build

CI runs on every push/PR (.github/workflows/ci.yml): ruff lint+format, mypy, the test suite on Python 3.13/3.14 (plus a lowest-pinned-dependencies job), and a build that asserts py.typed and the licence are in the wheel.

Releasing: add a version section to CHANGELOG.md (behaviour changes go under Changed with before/after), bump version in src/blesession/__init__.py, and merge. Then create a GitHub Release whose title and tag use the version name (for example, v0.5.0). Publishing the release triggers .github/workflows/release.yml to build and publish to PyPI with trusted publishing.

License

MIT

Metadata

Release files for blesession 0.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for blesession 0.10.0
File Size Uploaded Provenance Actions
blesession-0.10.0.tar.gz 331.2 kB With provenance Details for blesession-0.10.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for blesession 0.10.0
File Interpreter ABI Platform Actions
blesession-0.10.0-py3-none-any.whl Python 3 none any Details for blesession-0.10.0-py3-none-any.whl

Total release size: 383.8 kB

Release files / blesession-0.10.0.tar.gz

Download URL blesession-0.10.0.tar.gz
Size 331.2 kB
Tags Source
SHA-256 checksum
How to use checksums
da44e5f22cd5f2a664398cc081fd692e6755800c3dfd6ea051c6059b1803edf4
BLAKE2b-256 checksum
How to use checksums
8cd2c15fab9a9c056e2d9f150f08872a2f89e49fa49e44c4972e1d589f850a3d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / blesession-0.10.0-py3-none-any.whl

Download URL blesession-0.10.0-py3-none-any.whl
Size 52.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4bfda2be3beb6da2d8a1fdeffe6bb8da8773d7ccd2cf26bc4f586b57b6fde31f
BLAKE2b-256 checksum
How to use checksums
cdb95f7fa5946630ed8f4247f19aa9cc2768b3d7c6f00dc8ece0b7f73e1e8289
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for blesession 0.10.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for blesession-0.10.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page