You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32 BLE(Arduino框架):如何正确触发Service Changed指示?

问题解答

1. 通过Service Changed特征通知智能手机的正确方式

要让iOS设备刷新GATT服务缓存,需在动态添加新服务完成后,手动触发Service Changed特征的Indication,具体操作如下:

核心步骤

  • 确保BLE设备已加载Generic Attribute Service(UUID:0x1801),ESP32官方BLE库默认包含该服务,若手动移除过需重新创建。
  • 获取Service Changed特征(UUID:0x2A05)实例,该特征仅支持Indication(而非Notification),需提前配置CCCD描述符允许Indication。
  • 动态添加完新服务后,调用特征的indicate()方法,传入表示GATT变更范围的参数:通常用起始句柄0x0000和结束句柄0xFFFF,告知iOS全量GATT结构已变更,需重新扫描。

代码示例(Arduino ESP32官方BLE库)

// 全局变量
BLEServer* pServer = nullptr;
BLECharacteristic* pServiceChangedChar = nullptr;

void setup() {
  BLEDevice::init("ESP32_BLE_Device");
  pServer = BLEDevice::createServer();

  // 获取或创建Generic Attribute Service
  BLEService* pGattService = pServer->getServiceByUUID(BLEUUID((uint16_t)0x1801));
  if (!pGattService) {
    pGattService = pServer->createService(BLEUUID((uint16_t)0x1801));
  }

  // 创建/获取Service Changed特征并配置权限
  pServiceChangedChar = pGattService->getCharacteristic(BLEUUID((uint16_t)0x2A05));
  if (!pServiceChangedChar) {
    pServiceChangedChar = pGattService->createCharacteristic(
      BLEUUID((uint16_t)0x2A05),
      BLECharacteristic::PROPERTY_INDICATE
    );
    pServiceChangedChar->addDescriptor(new BLE2902()); // 开启Indication权限
  }

  pGattService->start();
  // 初始化其他默认服务...
}

// 动态添加自定义服务并触发缓存刷新
void addRuntimeService() {
  // 创建并启动新服务
  BLEService* pRuntimeService = pServer->createService(BLEUUID("你的自定义服务UUID"));
  // 添加特征逻辑...
  pRuntimeService->start();

  // 发送Service Changed Indication
  if (pServiceChangedChar) {
    uint8_t data[4] = {0x00, 0x00, 0xFF, 0xFF}; // 起始+结束句柄,小端模式
    pServiceChangedChar->setValue(data, 4);
    pServiceChangedChar->indicate();
  }
}

注意:需确保发送动作在设备与iOS手机已连接状态下执行,否则不会触发缓存刷新。

2. 该操作是否应由BLE库自动完成?

ESP32 Arduino官方BLE库不会自动触发Service Changed Indication。原因如下:

  • 动态添加服务属于开发者自定义业务逻辑,库无法预判GATT结构变更的时机;
  • BLE规范仅要求设备在GATT变更时发送该通知,但未强制库自动实现,需开发者根据业务场景手动调用。

内容的提问来源于stack exchange,提问作者Antonello Barbone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:13:10