The sensor on the patient’s knee was still connected when the reading stopped changing. The iPad showed 51° for the rest of the physiotherapy session. When the radio finally dropped, the screen switched to “Reconnecting…” and stayed there, with no end and no way out.

Nothing failed in the sense Core Bluetooth reports. The link was up for most of the session. The framework delivered every callback it promised. The app had collapsed two questions into one: is the radio link usable, and is the number on screen current? The second can turn false while the first stays true, and a therapist adjusting a knee brace on a frozen 51° deserves to know which.

The authority over “current” is not the connection state. It is the arrival of a sample the app has validated, within the interval the accessory’s protocol promises.

Readiness is a sequence, not a flag

didConnect establishes a link. A usable stream needs four more facts: the expected service was discovered, the expected characteristics were discovered, the subscription was confirmed in peripheral(_:didUpdateNotificationStateFor:error:), and the first reading decoded and validated. Each step can fail on its own, and each failure means something different to the person holding the iPad.

So the link is a state machine whose phases name those facts:

SwiftGitHub
import CoreBluetooth
import Foundation

struct Reading<Value: Sendable>: Sendable {
    let value: Value
    let receivedAt: ContinuousClock.Instant

    func isFresh(at now: ContinuousClock.Instant, maximumAge: Duration) -> Bool {
        let age = receivedAt.duration(to: now)
        return age >= .zero && age <= maximumAge
    }
}

enum LinkPhase: Sendable {
    case waitingForRadio
    case ready
    case connecting(attempt: UUID, peripheral: UUID)
    case preparing(peripheral: UUID)          // discovery and subscription
    case streaming(peripheral: UUID, last: Reading<Double>?)
    case unavailable(reason: String, last: Reading<Double>?)
}

enum LinkEvent: Sendable {
    case radioPoweredOn
    case radioReset
    case connectRequested(attempt: UUID, peripheral: UUID)
    case connected(peripheral: UUID)
    case subscribed(peripheral: UUID)
    case sample(peripheral: UUID, Reading<Double>)
    case connectDeadlinePassed(attempt: UUID)
    case disconnected(peripheral: UUID)
}

func reduce(_ phase: LinkPhase, _ event: LinkEvent) -> LinkPhase {
    switch (phase, event) {
    case (_, .radioReset):
        return .waitingForRadio
    case (.waitingForRadio, .radioPoweredOn):
        return .ready
    case let (.ready, .connectRequested(attempt, id)),
         let (.unavailable, .connectRequested(attempt, id)):
        return .connecting(attempt: attempt, peripheral: id)
    case let (.connecting(_, expected), .connected(id)) where id == expected:
        return .preparing(peripheral: id)
    case let (.preparing(expected), .subscribed(id)) where id == expected:
        return .streaming(peripheral: id, last: nil)
    case let (.streaming(expected, _), .sample(id, reading)) where id == expected:
        return .streaming(peripheral: id, last: reading)
    case let (.connecting(current, _), .connectDeadlinePassed(attempt)) where current == attempt:
        return .unavailable(reason: "Sensor not found nearby", last: nil)
    case let (.streaming(expected, last), .disconnected(id)) where id == expected:
        return .unavailable(reason: "Sensor disconnected", last: last)
    case let (.preparing(expected), .disconnected(id)) where id == expected:
        return .unavailable(reason: "Sensor disconnected during setup", last: nil)
    default:
        return phase
    }
}

Every event carries the peripheral it is about, and the reducer refuses events for any other. A callback from a cancelled attempt, or from the sensor on the next bed, changes nothing. A connection can be requested only once the radio is powered on. A radio reset invalidates everything, because after .resetting none of the previous peripherals, services, or subscriptions can be trusted.

.unavailable keeps the last reading. That is history, and history is useful: “Last reading 51° at 14:32” is true. “51°” on its own, twenty minutes later, is not.

Current is a time, not a connection

Freshness is computed when the screen renders, from the monotonic instant the reducer recorded when it accepted the sample. ContinuousClock is the right clock: it keeps counting while the device sleeps and ignores the user changing the time.

Choose the maximum age from the accessory’s reporting contract and the jitter you have measured, not from what looks responsive. A sensor that reports at 10 Hz and has not reported for two seconds is stalled, even though the link is up. That is the state the opening session needed: the radio connected, the stream silent, and the screen saying so before the disconnect callback ever arrives.

One accessory design makes this impossible: a sensor that publishes only on change. An unchanged knee angle and a dead stream look identical. If you control the firmware, add a heartbeat. If you do not, the honest interface says “no change since 14:32,” not “51°.”

Give “connect now” a deadline

connect(_:options:) does not time out. A connection request to a peripheral that is out of range stays pending until it appears or the app cancels it. For background reconnection, that is a feature: the system completes the connection when the accessory returns. For a therapist tapping “Connect,” it is the endless “Reconnecting…”.

A foreground attempt therefore carries its own deadline and its own identity:

SwiftGitHub
@MainActor
final class SensorLink: NSObject {
    private(set) var phase: LinkPhase = .waitingForRadio
    private var central: CBCentralManager!
    private var pending: CBPeripheral?
    private var deadline: Task<Void, Never>?

    override init() {
        super.init()
        central = CBCentralManager(delegate: self, queue: .main)
    }

    func connect(_ peripheral: CBPeripheral, within limit: Duration) {
        let attempt = UUID()
        send(.connectRequested(attempt: attempt, peripheral: peripheral.identifier))
        guard case .connecting(let current, _) = phase, current == attempt else {
            return                           // refused, or an attempt is already running
        }
        pending = peripheral                 // Core Bluetooth does not retain it for you
        central.connect(peripheral)

        deadline?.cancel()
        deadline = Task { [weak self] in
            try? await Task.sleep(for: limit)
            guard !Task.isCancelled, let self else { return }
            self.send(.connectDeadlinePassed(attempt: attempt))
            if case .unavailable = self.phase, let pending = self.pending {
                self.central.cancelPeripheralConnection(pending)
                self.pending = nil
            }
        }
    }

    fileprivate func send(_ event: LinkEvent) {
        phase = reduce(phase, event)
    }
}

extension SensorLink: CBCentralManagerDelegate {
    nonisolated func centralManagerDidUpdateState(_ central: CBCentralManager) {
        let state = central.state
        MainActor.assumeIsolated {
            send(state == .poweredOn ? .radioPoweredOn : .radioReset)
        }
    }

    nonisolated func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        let id = peripheral.identifier
        MainActor.assumeIsolated {
            deadline?.cancel()
            send(.connected(peripheral: id))
        }
    }
}

The guard compares the attempt in the phase with the one just requested. Checking only for .connecting would accept a second tap while the first attempt is still running: the reducer keeps the old attempt, the new deadline never matches it, and the screen is back to an endless “Reconnecting…”. The deadline carries the attempt ID, so a timer from an earlier attempt cannot fail a newer one. The delegate callbacks identify the peripheral, so they go through the same reducer and the same refusal rules. The manager runs on the main queue here because the workload is a few samples a second; assumeIsolated states that fact to the compiler and traps if it is ever false. Measure decoding and delivery before moving to a dedicated queue, and when you do, publish domain values to the interface, never Core Bluetooth objects.

Cancelling a connection that later completes still produces terminal callbacks. If the user retries the same peripheral immediately, those callbacks arrive for the old attempt, and the reducer is what keeps them from reviving it.

Reconnect to the accessory you registered

A peripheral identifier is stable for a given accessory on a given device, which makes it the right key for “the sensor this patient was paired with.” Retrieve it with retrievePeripherals(withIdentifiers:) first. A scan, or retrieveConnectedPeripherals(withServices:), returns every accessory that advertises the service, and in a clinic with three identical sensors, the first match is a coin toss with a patient’s data.

Before accepting readings, verify the accessory’s identity against the registration: a serial number characteristic, an authenticated pairing, or AccessorySetupKit, which lets the person choose the accessory once and gives the app only that one. Hold strong references to pending and connected peripherals; Core Bluetooth releases a CBPeripheral the app does not retain, and a connection attempt silently disappears with it.

Pace writes, and know what an acknowledgment proves

For .withoutResponse writes, the payload limit comes from maximumWriteValueLength(for: .withoutResponse), and the pace from canSendWriteWithoutResponse: write while it is true, and resume in peripheralIsReady(toSendWriteWithoutResponse:). Writing faster than that drops data without an error.

For a command with consequences, such as “start calibration,” .withResponse means the peripheral’s GATT server accepted the write. It does not mean the firmware applied the command. If the product needs that proof, the accessory protocol needs an application-level acknowledgment, ideally one that echoes a command ID.

Restoration and the cases worth a device

On iOS, a restore identifier lets the system relaunch the app for Bluetooth events. Recreate the manager with the same identifier at launch, read the peripherals the system hands back in centralManager(_:willRestoreState:), and rebuild subscriptions and link phase from what the framework reports, not from what the app believed before it was terminated. A force-quit by the user disables restoration; test it as its own case. On macOS, test sleep and wake.

Test the reducer with recorded event sequences, including the ugly ones: a disconnect during discovery, a sample from the wrong peripheral, a deadline that fires after a late connect. Then take the hardware for a walk: out of range during a session, a deadline that expires, a restored subscription, and a reconnection with two same-model sensors on the table.

What to ask of your own code

  • Where does the interface decide that a reading is current, and does it use time or connection state?
  • Can a callback from a previous attempt or another peripheral change the link?
  • Does every foreground connection have a deadline and a way out?
  • How does the app know the accessory is the registered one, not merely the first that advertises the service?
  • What does the screen say when the radio is connected and the stream is silent?

The therapist does not need to know about GATT. They need the screen to say “Last reading at 14:32” the moment it stops being now. Everything else in this edition exists to make that sentence true.

References

If this edition sharpened your next review, you can buy me a coffee.