2021-10-13 16:08:35 -04:00
|
|
|
#include "components/ble/BatteryInformationService.h"
|
2021-11-05 18:55:34 -04:00
|
|
|
#include <nrf_log.h>
|
2020-10-02 15:16:48 -04:00
|
|
|
#include "components/battery/BatteryController.h"
|
2020-09-27 14:02:47 -04:00
|
|
|
|
|
|
|
using namespace Pinetime::Controllers;
|
|
|
|
|
|
|
|
constexpr ble_uuid16_t BatteryInformationService::batteryInformationServiceUuid;
|
|
|
|
constexpr ble_uuid16_t BatteryInformationService::batteryLevelUuid;
|
|
|
|
|
2021-04-18 13:28:14 -04:00
|
|
|
int BatteryInformationServiceCallback(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt* ctxt, void* arg) {
|
2020-09-27 14:02:47 -04:00
|
|
|
auto* batteryInformationService = static_cast<BatteryInformationService*>(arg);
|
|
|
|
return batteryInformationService->OnBatteryServiceRequested(conn_handle, attr_handle, ctxt);
|
|
|
|
}
|
|
|
|
|
2021-04-18 13:28:14 -04:00
|
|
|
BatteryInformationService::BatteryInformationService(Controllers::Battery& batteryController)
|
|
|
|
: batteryController {batteryController},
|
2021-07-24 11:40:06 -04:00
|
|
|
characteristicDefinition {{.uuid = &batteryLevelUuid.u,
|
2021-04-18 13:28:14 -04:00
|
|
|
.access_cb = BatteryInformationServiceCallback,
|
|
|
|
.arg = this,
|
2021-10-30 14:02:39 -04:00
|
|
|
.flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_READ_ENC | BLE_GATT_CHR_F_READ_AUTHEN | BLE_GATT_CHR_F_NOTIFY,
|
2021-04-18 13:28:14 -04:00
|
|
|
.val_handle = &batteryLevelHandle},
|
|
|
|
{0}},
|
|
|
|
serviceDefinition {
|
|
|
|
{/* Device Information Service */
|
|
|
|
.type = BLE_GATT_SVC_TYPE_PRIMARY,
|
2021-07-24 11:40:06 -04:00
|
|
|
.uuid = &batteryInformationServiceUuid.u,
|
2021-04-18 13:28:14 -04:00
|
|
|
.characteristics = characteristicDefinition},
|
|
|
|
{0},
|
|
|
|
} {
|
2020-09-27 14:02:47 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
void BatteryInformationService::Init() {
|
|
|
|
int res = 0;
|
|
|
|
res = ble_gatts_count_cfg(serviceDefinition);
|
|
|
|
ASSERT(res == 0);
|
|
|
|
|
|
|
|
res = ble_gatts_add_svcs(serviceDefinition);
|
|
|
|
ASSERT(res == 0);
|
|
|
|
}
|
|
|
|
|
2021-04-18 13:28:14 -04:00
|
|
|
int BatteryInformationService::OnBatteryServiceRequested(uint16_t connectionHandle,
|
|
|
|
uint16_t attributeHandle,
|
|
|
|
ble_gatt_access_ctxt* context) {
|
|
|
|
if (attributeHandle == batteryLevelHandle) {
|
2020-09-27 14:02:47 -04:00
|
|
|
NRF_LOG_INFO("BATTERY : handle = %d", batteryLevelHandle);
|
2021-10-01 23:22:12 -04:00
|
|
|
uint8_t batteryValue = batteryController.PercentRemaining();
|
2020-09-27 14:02:47 -04:00
|
|
|
int res = os_mbuf_append(context->om, &batteryValue, 1);
|
|
|
|
return (res == 0) ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
|
|
|
|
}
|
|
|
|
return 0;
|
2021-07-11 10:55:06 -04:00
|
|
|
}
|
|
|
|
void BatteryInformationService::NotifyBatteryLevel(uint16_t connectionHandle, uint8_t level) {
|
|
|
|
auto* om = ble_hs_mbuf_from_flat(&level, 1);
|
|
|
|
ble_gattc_notify_custom(connectionHandle, batteryLevelHandle, om);
|
|
|
|
}
|