feat(ble): 使用Zephyr BAS服务替换自定义电池服务实现
- 在prj.conf中启用CONFIG_BT_BAS、CONFIG_BT_DIS和CONFIG_BT_DIS_PNP配置项 - 移除自定义的电池服务实现代码 - 改用zephyr/bluetooth/services/bas.h提供的标准BAS服务API - 简化电池状态事件处理逻辑,直接调用bt_bas_set_battery_level设置电池级别 - 移除手动GATT通知实现,依赖系统BAS服务自动处理通知功能
This commit is contained in:
3
prj.conf
3
prj.conf
@@ -59,6 +59,9 @@ CONFIG_BT_HIDS_ATTR_MAX=40
|
||||
CONFIG_BT_HIDS_INPUT_REP_MAX=4
|
||||
CONFIG_BT_HIDS_OUTPUT_REP_MAX=3
|
||||
CONFIG_BT_HIDS_FEATURE_REP_MAX=0
|
||||
CONFIG_BT_BAS=y
|
||||
CONFIG_BT_DIS=y
|
||||
CONFIG_BT_DIS_PNP=y
|
||||
|
||||
CONFIG_USB_DEVICE_STACK_NEXT=y
|
||||
CONFIG_USBD_HID_SUPPORT=y
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
#include <errno.h>
|
||||
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/bluetooth/gatt.h>
|
||||
#include <zephyr/bluetooth/services/bas.h>
|
||||
|
||||
#include <app_event_manager.h>
|
||||
|
||||
@@ -13,50 +10,13 @@
|
||||
#include <zephyr/logging/log.h>
|
||||
LOG_MODULE_REGISTER(MODULE, LOG_LEVEL_INF);
|
||||
|
||||
static bool notify_enabled;
|
||||
static uint8_t battery_level = 100U;
|
||||
|
||||
static void bas_ccc_cfg_changed(const struct bt_gatt_attr *attr, uint16_t value)
|
||||
{
|
||||
ARG_UNUSED(attr);
|
||||
notify_enabled = (value == BT_GATT_CCC_NOTIFY);
|
||||
}
|
||||
|
||||
static ssize_t read_battery_level(struct bt_conn *conn,
|
||||
const struct bt_gatt_attr *attr,
|
||||
void *buf,
|
||||
uint16_t len,
|
||||
uint16_t offset)
|
||||
{
|
||||
const uint8_t *value = attr->user_data;
|
||||
|
||||
return bt_gatt_attr_read(conn, attr, buf, len, offset, value, sizeof(*value));
|
||||
}
|
||||
|
||||
BT_GATT_SERVICE_DEFINE(ble_battery_svc,
|
||||
BT_GATT_PRIMARY_SERVICE(BT_UUID_BAS),
|
||||
BT_GATT_CHARACTERISTIC(BT_UUID_BAS_BATTERY_LEVEL,
|
||||
BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
|
||||
BT_GATT_PERM_READ_ENCRYPT,
|
||||
read_battery_level, NULL, &battery_level),
|
||||
BT_GATT_CCC(bas_ccc_cfg_changed,
|
||||
BT_GATT_PERM_READ_ENCRYPT | BT_GATT_PERM_WRITE_ENCRYPT),
|
||||
);
|
||||
|
||||
static bool handle_battery_status_event(const struct battery_status_event *event)
|
||||
{
|
||||
battery_level = battery_status_event_get_soc(event);
|
||||
uint8_t battery_level = battery_status_event_get_soc(event);
|
||||
int err = bt_bas_set_battery_level(battery_level);
|
||||
|
||||
if (!notify_enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int err = bt_gatt_notify(NULL, &ble_battery_svc.attrs[1], &battery_level, sizeof(battery_level));
|
||||
|
||||
if (err == -ENOTCONN) {
|
||||
LOG_WRN("BAS notify skipped: peer disconnecting");
|
||||
} else if (err) {
|
||||
LOG_ERR("BAS notify failed: %d", err);
|
||||
if (err) {
|
||||
LOG_ERR("bt_bas_set_battery_level failed: %d", err);
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
Reference in New Issue
Block a user