Recovering BlueZ on Raspberry Pi When a Timeout Is Not Really a Timeout

Most BLE error-handling code assumes something simple:

  1. Connect to the device.
  2. Read a characteristic.
  3. If it fails, catch the exception.
  4. Retry.

That works surprisingly well — until it doesn’t.

While building a Raspberry Pi-based BLE relay for field deployment, I encountered a more difficult failure mode.

The BLE operation did not return an error.

It simply stopped.

The Python coroutine was waiting. BlueZ still appeared to have state associated with the connection. The HCI controller did not necessarily agree with either of them.

And because the collector was launched periodically, another process could eventually start while the previous Bluetooth state was still unhealthy.

This turned a simple BLE timeout into a platform reliability problem.

The System

The system consisted of a Raspberry Pi collecting measurements from multiple BLE sensors and forwarding them to another server.

The Raspberry Pi side used:

  • Python
  • Bleak
  • BlueZ
  • Linux Bluetooth/HCI
  • systemd
  • cron
  • NetworkManager
  • local persistent storage
  • HTTP delivery

The design had to survive real field conditions rather than only a controlled development environment.

That meant handling situations such as:

  • a BLE sensor becoming unavailable,
  • BlueZ becoming stuck,
  • the Bluetooth adapter being powered off,
  • Wi-Fi disappearing,
  • DHCP changing an address,
  • a scheduled task taking longer than expected,
  • or the entire device losing power.

The important lesson was that reliability could not be implemented inside the BLE function alone.

The operating system and hardware controller were part of the application architecture.

The First Attempt: Just Add a Timeout

The obvious first solution was an asynchronous timeout.

Conceptually:

try:
    result = await asyncio.wait_for(
        read_sensor(),
        timeout=BLE_TIMEOUT
    )
except asyncio.TimeoutError:
    handle_timeout()

This protects the application from waiting forever for an ordinary slow BLE operation.

But I discovered an important problem:

canceling the Python operation does not guarantee that the Bluetooth stack has returned to a healthy state.

The application may believe the operation is finished.

BlueZ may still believe a connection exists.

The HCI controller may still contain stale state.

Those three layers can disagree about reality.

Running the same operation again immediately can therefore make the situation worse.

A Timeout Needs Two Boundaries

The next design change was to introduce two different timeout layers.

Layer 1: Operation timeout

The Python BLE operation itself is time-limited.

This handles normal cases such as:

  • a GATT operation taking too long,
  • a sensor not responding,
  • or an asynchronous call failing to complete.

Layer 2: Process timeout

The entire collector process is also bounded externally.

This matters because native services or libraries can sometimes remain stuck even after an asynchronous task has been canceled.

The outer runner does not need to understand the internal Python state.

It only needs to know:

This process should have finished by now.

If it has not, the process can be terminated and recovery can move to another layer.

This distinction turned out to be important.

A timeout inside the application is useful.

A timeout around the application is a reliability boundary.

Not Every Bluetooth Failure Is the Same

Another problem was error classification.

Bluetooth failures from Bleak and BlueZ are not always expressed consistently.

Depending on the version and current state, errors may look like:

  • No Bluetooth adapters found
  • Powered off
  • Operation already in progress

Treating all of these as a generic BLE exception would make recovery unnecessarily destructive.

For example:

Adapter powered off

is not necessarily the same problem as:

BlueZ has a stale connection and will not progress.

So the application converts failures into explicit states.

Examples include:

  • Bluetooth stack stuck
  • Adapter powered off
  • Missing dependency
  • Normal device failure

The shell-level runner can then choose a recovery strategy without needing to interpret Python exceptions.

This is a pattern I have found useful beyond Bluetooth:

Classify errors by the recovery action they require, not only by the API that produced them.

Diagnose Before Recovering

When a timeout occurs, restarting everything immediately is tempting.

But doing that destroys useful evidence.

Before recovery, the system collects diagnostics from three layers.

1. Application layer

What did Bleak think was happening?

2. Operating-system Bluetooth layer

What did bluetoothctl report?

3. Controller layer

What did btmgmt report about the HCI controller?

Each diagnostic command is independently time-limited.

This is important.

A diagnostic tool must never become the next thing that hangs.

And if one diagnostic fails, it should not overwrite the original error.

Diagnostics are best-effort evidence, not a new dependency for recovery.

Recovery Should Escalate Gradually

Once the system can distinguish failure states, recovery can become staged instead of aggressive.

The sequence evolved into something like this:

Step 1 — Let the current collection cycle fail

One sensor failure should not prevent other sensors from being collected.

The collector therefore does not repeatedly attack the same failed sensor.

Each sensor is normally tried once during a collection cycle.

The next scheduled run becomes the retry.

Step 2 — Restart the Bluetooth service

If repeated failures indicate that the Bluetooth stack itself is unhealthy, restart bluetooth.service.

This is more disruptive than retrying the sensor but much less disruptive than rebooting the entire Raspberry Pi.

Step 3 — Reset the HCI controller

If restarting BlueZ does not restore operation, escalate to an hci0 down/up recovery.

At this point the problem is being treated as a controller-level failure rather than an application-level error.

Step 4 — Reboot the host

A host reboot is the final recovery level.

It is only used after repeated recovery failure and only when configuration allows it.

This hierarchy matters.

Restarting the whole machine for every BLE error creates instability.

Waiting forever creates a different kind of instability.

A progressive recovery strategy provides a practical compromise.

Why Immediate Retry Can Be Harmful

This project also changed how I think about retry strategies.

When multiple sensors are involved, an aggressive retry policy can create unfairness.

Imagine six sensors.

Sensor #2 is unhealthy.

If the collector spends several retries on sensor #2 before continuing, sensors #3 through #6 may not be collected on time.

The system therefore uses a simpler rule:

Try each sensor once per collection cycle.

A failed sensor waits until the next scheduled run.

This sacrifices fast recovery for one device, but protects the overall system.

In field systems, total system progress can be more important than aggressively recovering one failing component.

BLE Is Sometimes a Multi-Stage Transaction

Another source of hidden complexity was that a single sensor measurement was not always a single BLE read.

For one class of sensors, temperature and humidity were obtained through GATT.

Battery information arrived separately through advertisements.

The workflow therefore became:

  1. connect,
  2. discover services,
  3. read GATT characteristics,
  4. disconnect,
  5. wait for advertisements,
  6. reject stale packets,
  7. select matching packets,
  8. assemble the final measurement.

The first advertisement after disconnection could contain stale information.

RSSI availability also varied depending on the Bleak backend.

So RSSI remained best-effort rather than becoming a required measurement field.

This is a good reminder that vendor BLE devices often expose a logical measurement across multiple transport mechanisms.

Reliability Extends Beyond Bluetooth

Once I started treating failures as stateful platform problems, the same design philosophy spread through the rest of the system.

Collected measurements were written to durable queue files.

A queue item was deleted only after confirmed HTTP success.

Temporary files and atomic rename were used where appropriate to avoid partially written data becoming visible.

If the network failed, data collection could continue.

If DHCP changed the server address, the system could eventually rediscover it using the server’s MAC address rather than assuming that an IP address was permanent identity.

Software updates were staged, verified, backed up and made reversible.

The important architectural idea was separation:

Acquiring data and delivering data are different responsibilities.

A network outage should not automatically become a measurement outage.

What I Learned

Several lessons from this system are now part of how I approach legacy and field-deployed embedded systems.

1. A timeout must bound the whole failure domain

Canceling an asynchronous operation is not enough if an underlying native service can remain stuck.

2. Recovery strategy is a useful error taxonomy

“Bluetooth error” is too vague.

“Restart service,” “reset controller,” and “wait for next cycle” are actionable states.

3. Capture evidence before destroying the failure state

Logs are most valuable at the moment the system is unhealthy.

4. Recovery should escalate

Retry.

Then restart the service.

Then reset the controller.

Then reboot.

Do not jump immediately to the most disruptive action.

5. Fairness matters in multi-device systems

One broken sensor should not monopolize the entire collection process.

6. The operating system is part of an embedded application

cron, systemd, shell scripts, locks, NetworkManager, BlueZ and persistent files are not deployment details.

They are part of the system architecture.

The Bigger Lesson

The most interesting part of this problem was not Bluetooth itself.

It was realizing that:

the application, operating system and hardware controller could hold different versions of the truth at the same time.

Once that became clear, the solution stopped being:

“How do I retry this BLE API?”

and became:

“How do I create explicit failure boundaries between these layers and recover them safely?”

That is the kind of problem I enjoy working on.

Old systems, unreliable hardware, undocumented behavior, strange platform failures and software that has to keep working outside a laboratory are often more interesting than building something new from a clean specification.