fix(ble): reliably expose and update BLE battery level (BAS)#10622
Draft
jamesarich wants to merge 2 commits into
Draft
fix(ble): reliably expose and update BLE battery level (BAS)#10622jamesarich wants to merge 2 commits into
jamesarich wants to merge 2 commits into
Conversation
The Battery Service (0x180F / 0x2A19) is now wired up per the Bluetooth BAS spec: the Battery Level characteristic always holds a valid 0-100 value and is pushed on change. - NimBLE: seed an initial level at setup and cache the value on every update so a READ returns the current level even while disconnected; only notify when a client is connected. - Power: mirror the battery level to the Battery Service from readPowerStatus() on change, so it updates independent of GPS/position events (previously the only push path was MeshService). Also fixes two regressions the above would otherwise introduce: - NimBLE use-after-free: BLEDevice::deinit(true) frees the GATT objects but left the global BatteryCharacteristic dangling. Several AdminModule paths (e.g. serial-config entry) deinit BLE while config.bluetooth.enabled stays true, so the periodic push would deref freed memory. Null the pointer in deinit(). - NRF52: guard blebas.write() on the nrf52Bluetooth instance so the new periodic push can't call it before the Battery Service is begun in setup(). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2 tasks
thebentern
approved these changes
Jun 3, 2026
Contributor
There was a problem hiding this comment.
Pull request overview
This PR improves BLE Battery Service (BAS, 0x180F / 0x2A19) behavior so the Battery Level characteristic is always readable with a valid value and updates are pushed to connected subscribers, driven by the power subsystem rather than only by phone/GPS/UI refresh paths.
Changes:
- Mirror battery percentage updates from
Power::readPowerStatus()intoupdateBatteryLevel()on change. - ESP32 (NimBLE): seed the BAS characteristic during service setup; cache the characteristic value on every update; notify only when connected; clear the global characteristic pointer on deinit to avoid UAF.
- nRF52: guard BAS writes so periodic updates don’t run before the Bluetooth instance is initialized.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| src/Power.cpp | Pushes battery % changes into the platform BLE updateBatteryLevel() hook from the power read loop. |
| src/platform/nrf52/NRF52Bluetooth.cpp | Prevents BAS writes before the nRF52 Bluetooth stack/service is initialized. |
| src/nimble/NimbleBluetooth.cpp | Seeds and updates the BAS Battery Level characteristic correctly; clears dangling pointers on deinit. |
Comment on lines
+967
to
+975
| // Mirror battery level to the BLE Battery Service (0x2A19), pushing only on change. | ||
| if (hasBattery == OptTrue) { | ||
| static int lastBleBatteryPercent = -1; | ||
| int pct = powerStatus2.getBatteryChargePercent(); | ||
| if (pct != lastBleBatteryPercent) { | ||
| lastBleBatteryPercent = pct; | ||
| updateBatteryLevel(pct); | ||
| } | ||
| } |
Comment on lines
+869
to
+873
| if (!config.bluetooth.enabled || !BatteryCharacteristic) | ||
| return; | ||
|
|
||
| // Cache the value so a READ works without a subscriber; notify only when connected. | ||
| BatteryCharacteristic->setValue(&level, 1); |
Comment on lines
355
to
+359
| /// Given a level between 0-100, update the BLE attribute | ||
| void updateBatteryLevel(uint8_t level) | ||
| { | ||
| blebas.write(level); | ||
| if (nrf52Bluetooth) // skip until the Battery Service has been begun in setup() | ||
| blebas.write(level); |
Comment on lines
+860
to
+862
| // Seed an initial 0-100 level so an early read of 0x2A19 returns a valid value. | ||
| uint8_t initialLevel = (powerStatus && powerStatus->getHasBattery()) ? powerStatus->getBatteryChargePercent() : 0; | ||
| BatteryCharacteristic->setValue(&initialLevel, 1); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Wires up the BLE Battery Service (
0x180F/ Battery Level0x2A19) to behave per the Bluetooth BAS 1.1 spec: the Battery Level characteristic always holds a valid0–100value and is pushed to subscribers on change. This is what drives the OS-level battery indicator (Android/iOS/Windows "connected device" battery readout); the Meshtastic app's own battery display continues to use Device Metrics telemetry over the mesh service and is unaffected.What was wrong
updateBatteryLevel()only ever calledsetValue()while connected, and the characteristic was never seeded. A BAS client reading0x2A19right after connecting got an undefined/empty value — a READ-must-always-return-valid violation.updateBatteryLevel()wasMeshService::refreshLocalMeshNode()(phone connect / GPS / position / menu). A GPS-less device with a phone connected emitted almost no0x2A19notifications, so the level went stale.Changes
notify()when a client is connected.Power::readPowerStatus()on change, so it refreshes independent of GPS/position events.Regressions fixed (introduced by the periodic push, caught in self-review)
BLEDevice::deinit(true)frees the GATT objects but left the globalBatteryCharacteristicdangling. SeveralAdminModulepaths (e.g. serial-config entry) deinit BLE whileconfig.bluetooth.enabledstaystrue, so the new periodic push would dereference freed memory. Now nulled indeinit().blebas.write()on thenrf52Bluetoothinstance so the periodic push can't call it before the Battery Service is begun insetup().Notes / out of scope
updateBatteryLevelis a stub) — separate, larger task.0x2BED, Critical/Energy/Health Status, etc.) are not implemented; only the mandatory Battery Level characteristic, which is what clients consume.Testing
trunk fmtclean on all three files.heltec-v3) and an NRF52 target (e.g.rak4631) to confirm; ideally verify the OS-level battery readout on a phone.🤖 Generated with Claude Code