Skip to content

GATTBatteryMonitor keeps CoreBluetooth connections open to unmatched BLE peripherals exposing Battery Service (0x180F) #1534

Done

Description

@m3y54m

OS

macOS: 27.2.1 (Build 26B131), Apple Silicon (arm64)

LinearMouse

v0.13.0

Describe the bug

Summary

When at least one Bluetooth/BLE pointer device is active (!targets.isEmpty), GATTBatteryMonitor periodically attaches to every system-connected BLE peripheral exposing the standard GATT Battery Service (0x180F) in order to read Device Information (0x180A) and match it against known input devices.

However, once identity discovery completes and a peripheral does not match any target input device (matchedTarget(...) == nil), GATTBatteryMonitor never calls cancelPeripheralConnection(_:) on that peripheral. As a result, LinearMouse retains an active CoreBluetooth central connection reference in bluetoothd indefinitely, keeping unrelated third-party BLE peripherals connected to macOS even after the application that originally connected to them disconnects or quits.

Symptoms

Suppose a user has LinearMouse running with a Bluetooth mouse paired/active, and uses another macOS application (e.g., a BLE client, sensor app, or development utility) to briefly connect to any non-HID BLE peripheral that exposes Battery Service (0x180F)—such as a BLE sensor, wearable, or development board:

  1. If the session overlaps BatteryDeviceMonitor's 60-second refresh timer (BatteryDeviceMonitor.swift:92-95), GATTBatteryMonitor.attachConnectedPeripherals() calls central.connect(peripheral) on that peripheral.
  2. When the other application disconnects (or exits completely), bluetoothd does not tear down the physical BLE ACL link because com.lujjjh.LinearMouse still holds an active CBCentralManager connection reference to the peripheral.
  3. Most single-link BLE peripherals stop advertising while connected and accept only one central connection at a time:
    • Subsequent BLE scans on macOS can no longer discover the peripheral.
    • Other central devices (such as a phone or another host) cannot connect to the peripheral at all.
  4. The peripheral remains stuck connected to the Mac until Bluetooth is toggled off/on in System Settings, LinearMouse quits, or Bluetooth permission for LinearMouse is revoked.

Root Cause

  1. Unconditional connect(_:) during candidate probing (LinearMouse/Device/VendorSpecific/GATTBatteryMonitor.swift:105-118):
    attachConnectedPeripherals() retrieves all system-connected peripherals offering 0x180F, inserts each into peers, and calls central.connect(peripheral) to inspect 0x180A (0x2A25 Serial Number / 0x2A50 PnP ID).
  2. Unmatched peers are never retired after discovery completes (GATTBatteryMonitor.swift:276-304):
    In publish():
    let identities = peers.values.map(\.identity)
    let complete = peers.values.allSatisfy { !$0.identityServicesPending && $0.identityReads.isEmpty }
    let values = peers.values
        .compactMap { peer -> Value? in
            peer.targetID = GATTBatteryIdentity.matchedTarget(
                for: peer.identity,
                peers: identities,
                targets: targets,
                discoveryComplete: complete
            )
            guard let id = peer.targetID else {
                return nil
            }
            // Only subscribe after matching a connected input device.
    While this avoids subscribing to 0x2A19 on unmatched devices, when complete == true and peer.targetID == nil, peer stays in peers with its CBPeripheral connection open forever—retire(peer.peripheral.identifier, cancel: true) is never called.
  3. updateTargets(_:) also skips unmatched peers (GATTBatteryMonitor.swift:56-59):
    for (id, peer) in peers where peer.targetID.map({ !validIDs.contains($0) }) == true {
        retire(id, cancel: true)
    }
    Because peer.targetID is nil, peer.targetID.map(...) evaluates to nil rather than true, so unmatched peripherals are never retired on subsequent refreshes either—only when stop() runs.

Suggested Fix

  1. Cancel the connection as soon as identity discovery completes without a match:
    Once complete == true (all pending 0x180A service/characteristic reads have finished), retire every peer whose matchedTarget(...) is nil with cancel: true (central.cancelPeripheralConnection(peer.peripheral)), being careful not to trigger re-entrant publish() churn while iterating.
  2. Avoid re-probing a rejected peripheral every 60 seconds while another app is still using it:
    Currently, centralManager(_:didDisconnectPeripheral:error:) (GATTBatteryMonitor.swift:143) unconditionally calls attempted.remove(peripheral.identifier). When LinearMouse cancels its own connection to an unmatched peripheral while another app still holds the link, CoreBluetooth delivers didDisconnectPeripheral to LinearMouse's CBCentralManager, while retrieveConnectedPeripherals(withServices: [0x180F]) continues to list that peripheral on the next 60-second tick.
    • Keep rejected UUIDs (and optionally their GATTBatteryIdentity) recorded for as long as the UUID continues to appear in retrieveConnectedPeripherals(withServices: [Self.batteryService]), pruning entries from attempted / rejectedIdentities in attachConnectedPeripherals() only once the peripheral is no longer connected to the system (and clearing them in stop(), on Bluetooth power-off, or when targets != self.targets).
  3. Preserve matchedTarget ambiguity protection (GATTBatteryState.swift:45-47, GATTBatteryTests.swift:103-115):
    If rejectedIdentities: [UUID: GATTBatteryIdentity] is kept for currently system-connected peripherals whose CBPeripheral connection was already canceled, passing Array(peers.values.map(\.identity)) + Array(rejectedIdentities.values) into GATTBatteryIdentity.matchedTarget(...) preserves the existing ambiguity check (testPnPFallbackRequiresCompletedAndUnambiguousDiscovery) without holding open CBPeripheral connections to non-target devices.

To reproduce

Environment:

  • macOS: 27.2.1 (Build 26B131), Apple Silicon (arm64)
  • LinearMouse: 0.13.0 (also present on main)
  • Relevant setup:
    • Bluetooth access granted to LinearMouse (System Settings → Privacy & Security → Bluetooth)
    • Menu bar icon / battery monitoring active (BatteryDeviceMonitor 60 s refresh timer running)
    • At least one Bluetooth / BLE pointer device connected (e.g., Logitech MX Master 3S over BLE, making GATTBatteryMonitor targets non-empty)
    • An unrelated single-link BLE peripheral exposing standard GATT Battery Service (0x180F) connected transiently by another macOS app
  1. Run LinearMouse on macOS with Bluetooth access granted and at least one Bluetooth/BLE mouse active.
  2. From any BLE utility or script, connect to an unrelated BLE peripheral that exposes Battery Service (0x180F) and perform service discovery so 0x180F is known to bluetoothd.
  3. Keep the connection open across one tick of BatteryDeviceMonitor's 60-second timer (up to 60 s), then disconnect from the peripheral and quit the BLE utility.
  4. Check system_profiler SPBluetoothDataType (or scan for the peripheral from another device).

Expected behavior

Expected: bluetoothd closes the unused BLE link immediately after the application disconnects, and the peripheral resumes advertising.

Actual: The peripheral stays listed under Connected in system_profiler SPBluetoothDataType because com.lujjjh.LinearMouse still holds a CoreBluetooth connection to it.

Anything else?

No response

Activity

  1. added
    bug
    on Nov 28, 2026
  2. added a commit that references this issue on Dec 2, 2026
    056a66a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions