#19858·esphome

Bluetooth proxy (Bluedroid): aborted connects leave pending opens in the stack, then every connect fails with status=128 while slots show free

Author: michaelheichlerCreated Sep 28, 2026Updated Sep 28, 2026

The problem

After a few connects that the client gives up on, an ESP32 Bluetooth proxy (Bluedroid) rejects every new connect with Connection open failed, status=128 (ESP_GATT_NO_RESOURCES). The rejection comes 30 to 70 ms after the request, so the radio never tries. The proxy still reports 3 of 3 slots free. Only a reboot, or turning BLE off and on, clears it.

I see this on an Everything Presence Lite (ESP32, vendor firmware 1.5.0, 3 proxy slots). EPL users report the same symptom in EverythingSmartHome/everything-presence-lite#430.

Reproduction

The script (under Additional information) uses aioesphomeapi directly. It needs no Home Assistant and no real peripheral for the trigger.

  1. Subscribe to raw advertisements, so the proxy sends connection replies to this client.
  2. Connect to a random static address that never answers (address type 1). Give up after 1 s, so aioesphomeapi sends a disconnect.
  3. The proxy logs Disconnect scheduled. After 10 s it logs Timeout waiting for teardown, forcing IDLE and frees the slot.
  4. Repeat with a new random address each time. Six rounds were enough with 3 slots. In my run, round 3 used a real device instead of a phantom address.
  5. The seventh open fails at once with status 128. Every later open fails the same way, including one to a real, reachable device 90 s later.

Cause, as far as I can tell

  1. gatt_disconnect() in state CONNECTING only sets want_disconnect_ and waits for ESP_GATTC_OPEN_EVT.
  2. When that event does not come within GATT_DISCONNECT_TIMEOUT_MS (10 s), loop() forces the slot to IDLE without any Bluedroid call. The esp_ble_gattc_open stays pending in the stack.
  3. Each pending open to a new address holds a GATT client control block and a known-server entry. With 4 ACL connections, BTA_GATTC_KNOWN_SR_MAX is 4. The next open to a new address fails in bta_gattc_process_api_open with BTA_GATT_NO_RESOURCES (0x80).

A second leak is in the same file. If an open succeeds after the slot moved on to another address, check_addr_() rejects the ESP_GATTC_OPEN_EVT, and nobody closes that link.

What I have not verified

  1. Why the fault lasts until reboot. By the Bluedroid timeouts I expected the queued opens to drain in about 2 minutes. They did not. The device logged timeouts for the first two queued opens only (at 21 s and 41 s), then none. I do not know why the queue stops draining.
  2. I have not run the repro on a plain ESP32 proxy as a control. It happens on the EPL, which runs stock ESPHome 2026.9.0 components for the proxy.

Fix

ESP-IDF 5.5.5 and 6.0.1 add esp_ble_gattc_cancel_open(). Cancelling the pending open on disconnect (and in the teardown timeout) fixes it on my device. I will link a PR.

Which version of ESPHome has the issue?

2026.9.0

What type of installation are you using?

Home Assistant Add-on

What platform are you using?

ESP32

Component causing the issue

bluetooth_proxy / bluetooth_connection (Bluedroid backend)

YAML Config

yaml
esphome:
  name: ble-proxy

esp32:
  board: esp32dev
  framework:
    type: esp-idf

logger:

api:

wifi:
  ssid: test-ssid
  password: test-password

esp32_ble_tracker:

bluetooth_proxy:
  active: true
  connection_slots: 3

The affected device is an Everything Presence Lite on vendor firmware 1.5.0, with an active proxy and 3 connection slots. The config above is a minimal proxy config with the same slot count. I have not run the repro on it.

Anything in the logs that might be useful for us?

txt
Device log through the API, times relative to script start. Addresses replaced with placeholders.

[  1.07s] [I][bluetooth_connection:137]: [0] 0x01 Connecting
[  2.07s] [D][bluetooth_connection:181]: [0] Disconnect scheduled
[ 12.10s] [E][bluetooth_connection:066]: [0] Timeout waiting for teardown, forcing IDLE
[ 12.10s] [D][bluetooth_connection:168]: [0] [PHANTOM_1] Disconnected, reason=0x08, freeing slot
...  (5 more rounds, same pattern, one every 11 s)
[ 67.61s] [I][bluetooth_connection:137]: [0] 0x01 Connecting
[ 67.62s] [W][bluetooth_connection:368]: [0] Connection open failed, status=128
[ 67.63s] [D][bluetooth_connection:168]: [0] [PHANTOM_7] Disconnected, reason=0x80, freeing slot
[ 67.70s] [W][bluetooth_connection:368]: [0] Connection open failed, status=128   (real device REAL_DEVICE)
[157.74s] [W][bluetooth_connection:368]: [0] Connection open failed, status=128   (same real device, 90 s later)

The proxy reported free slots 3/3 to the client during the whole failure.

Additional information

Part Version
ESPHome 2026.9.0
Framework ESP-IDF 5.5.5 (recommended), Bluedroid
Proxy slots 3, so CONFIG_BT_ACL_CONNECTIONS = 4
Home Assistant 2026.9.3
aioesphomeapi 46.6.0

Test of the fix on the same device

I built the fix as a local external_components override of bluetooth_connection (ESPHome 2026.9.0, ESP-IDF 5.5.5) and flashed it OTA. Then I ran the same script.

  1. Run 1 had 9 aborted connects. Run 2 had 21. Each one ended within 10 ms with Pending open cancelled and reason=0x100.
  2. No Timeout waiting for teardown and no status 128 appeared. The unpatched firmware failed at the 7th connect.
  3. A real device connected right after each pile-up, and again 30 to 90 s later.
[  2.09s] [D][bluetooth_connection:207]: [0] Disconnect scheduled
[  2.10s] [D][bluetooth_connection:801]: [0] Pending open cancelled
[  2.11s] [D][bluetooth_connection:168]: [0] [PHANTOM_1] Disconnected, reason=0x100, freeing slot
...
[ 11.33s] [I][bluetooth_connection:620]: [0] Connection open   (real device, right after 9 aborted connects)

The repro does not reach two parts of the fix. I have not tested the close of a link from a stale successful OPEN_EVT. I have also not tested the esp_ble_gap_disconnect() call for a live link in the loop() teardown timeout.

Code references

Related

  • #16588 added the forced-IDLE safety net.
  • #19375 guards a different Bluedroid queue problem (stale queued connection requests that crash). It does not cancel pending opens.
  • #19449 reports intermittent GATT failures on 2026.9.0. I have not checked whether it has the same cause.
Repro script (aioesphomeapi)

Usage is python ble-proxy-repro.py --host <proxy host> --lamp <address of a real device>. For an encrypted API, set PROXY_NOISE_PSK.

python
"""Tests whether aborted connects leak Bluedroid opens, because the proxy then rejects every open with 128."""

from __future__ import annotations

import argparse
import asyncio
import os
import random
import sys
import time
from dataclasses import dataclass

from aioesphomeapi import APIClient, LogLevel

ESP_GATT_NO_RESOURCES = 128
RANDOM_ADDRESS_TYPE = 1
PUBLIC_ADDRESS_TYPE = 0
LAMP_TIMEOUT = 20.0
PHANTOM_TOKEN = "P"
LOG_KEYWORDS = ("bluetooth_connection", "bluetooth_proxy", "esp32_ble_server")

START = time.monotonic()


def stamp(text: str) -> None:
    print(f"[{time.monotonic() - START:7.2f}s] {text}", flush=True)


def mac_to_int(mac: str) -> int:
    return int(mac.replace(":", ""), 16)


def fresh_phantom_mac() -> str:
    octets = [random.randint(0, 255) for _ in range(6)]
    octets[0] |= 0xC0
    return ":".join(f"{octet:02X}" for octet in octets)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="BLE proxy status 128 repro. Optional key via PROXY_NOISE_PSK.")
    parser.add_argument("--host", required=True)
    parser.add_argument("--port", type=int, default=6053)
    parser.add_argument(
        "--sequence",
        default="P,P,P,P,P,P,P,P,P",
        help="aborted connects in order. P is a fresh random static address that never answers",
    )
    parser.add_argument("--lamp", required=True, help="address of a real public-address peripheral")
    parser.add_argument("--give-up-after", type=float, default=1.0)
    parser.add_argument("--retry-wait", type=float, default=90.0)
    return parser.parse_args()


@dataclass
class Target:
    mac: str
    address_type: int
    timeout: float


@dataclass
class Outcome:
    connected: bool
    error: int
    first_reply_s: float | None
    exception: str

    def describe(self) -> str:
        reply = "none" if self.first_reply_s is None else f"{self.first_reply_s:.3f}s"
        text = f"connected={self.connected} error={self.error} first_reply={reply} {self.exception}"
        return text.rstrip()


class ProxyProbe:
    def __init__(self, client: APIClient, flags: int) -> None:
        self.client = client
        self.flags = flags

    async def connect_once(self, target: Target) -> Outcome:
        states: list[tuple[bool, int, float]] = []
        address = mac_to_int(target.mac)
        began = time.monotonic()
        exception = ""
        try:
            await self.client.bluetooth_device_connect(
                address,
                lambda connected, _mtu, error: states.append((connected, error, time.monotonic() - began)),
                timeout=target.timeout,
                disconnect_timeout=20.0,
                feature_flags=self.flags,
                address_type=target.address_type,
            )
        except Exception as err:  # noqa: BLE001 - the repro reports every failure
            exception = f"{type(err).__name__}: {err}"
        if not states:
            return Outcome(False, 0, None, exception)
        connected, error, first_reply = states[0]
        if connected:
            await self.client.bluetooth_device_disconnect(address)
        return Outcome(connected, error, first_reply, exception)

    async def aborted_connect(self, token: str, give_up_after: float) -> Outcome:
        if token == PHANTOM_TOKEN:
            target = Target(fresh_phantom_mac(), RANDOM_ADDRESS_TYPE, give_up_after)
        else:
            target = Target(token, PUBLIC_ADDRESS_TYPE, give_up_after)
        outcome = await self.connect_once(target)
        stamp(f"aborted connect {target.mac}: {outcome.describe()}")
        return outcome

    async def lamp(self, mac: str, label: str) -> int:
        outcome = await self.connect_once(Target(mac, PUBLIC_ADDRESS_TYPE, LAMP_TIMEOUT))
        stamp(f"{label}: lamp {mac} {outcome.describe()}")
        return outcome.error


def claim_proxy_replies_from_home_assistant(client: APIClient) -> None:
    client.subscribe_bluetooth_le_raw_advertisements(lambda _msg: None)


def watch_proxy(client: APIClient) -> None:
    def on_log(msg) -> None:
        line = msg.message.decode(errors="replace")
        if any(key in line for key in LOG_KEYWORDS):
            stamp(f"  log {line}")

    client.subscribe_logs(on_log, log_level=LogLevel.LOG_LEVEL_DEBUG)
    claim_proxy_replies_from_home_assistant(client)
    client.subscribe_bluetooth_connections_free(
        lambda free, limit, allocated: stamp(f"  free slots {free}/{limit} allocated {allocated}")
    )


async def open_probe(args: argparse.Namespace, psk: str | None) -> ProxyProbe:
    client = APIClient(args.host, args.port, None, noise_psk=psk)
    await client.connect(login=True)
    info = await client.device_info()
    flags = info.bluetooth_proxy_feature_flags_compat(client.api_version)
    stamp(f"device {info.name} esphome {info.esphome_version} proxy flags {flags}")
    watch_proxy(client)
    await asyncio.sleep(1)
    return ProxyProbe(client, flags)


async def pile_up(probe: ProxyProbe, args: argparse.Namespace) -> None:
    for token in args.sequence.split(","):
        outcome = await probe.aborted_connect(token.strip(), args.give_up_after)
        if outcome.error == ESP_GATT_NO_RESOURCES:
            stamp("status 128 during pile-up, stopping sequence")
            return


async def run(args: argparse.Namespace, psk: str | None) -> int:
    probe = await open_probe(args, psk)
    await pile_up(probe, args)
    first = await probe.lamp(args.lamp, "right after pile-up")
    stamp(f"waiting {args.retry_wait:.0f}s for Bluedroid to drain queued opens")
    await asyncio.sleep(args.retry_wait)
    retry = await probe.lamp(args.lamp, "after drain")
    await asyncio.sleep(1)
    await probe.client.disconnect()
    stamp(f"RESULT: right after pile-up error={first}, after drain error={retry}")
    return 1 if ESP_GATT_NO_RESOURCES in (first, retry) else 0


def main() -> int:
    psk = os.environ.get("PROXY_NOISE_PSK") or None
    return asyncio.run(run(parse_args(), psk))


if __name__ == "__main__":
    sys.exit(main())