h2zero / NimBLE-Arduino

A fork of the NimBLE library structured for compilation with Arduino, for use with ESP32, nRF5x.
https://h2zero.github.io/NimBLE-Arduino/
Apache License 2.0
667 stars 138 forks source link

Is it possible to advertise multiple 128bit services with data? #644

Closed daniel-v closed 3 weeks ago

daniel-v commented 4 months ago

I've been trying to advertise multiple services with a couple of bytes of data each.

This is the code:

#include <NimBLEDevice.h>

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID1        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define SERVICE_UUID2        "525bb0f4-7856-47d8-8f92-7f209aa3fb2e"

static NimBLEUUID serviceID1(SERVICE_UUID1);
static NimBLEUUID serviceID2(SERVICE_UUID2);
static NimBLEAdvertising *pAdvert = nullptr;
static uint32_t count = 0;

void setup() {
  Serial.begin(115200);
  Serial.println("Starting BLE work!");  

  NimBLEDevice::init("SmartPot");  
  pAdvert = NimBLEDevice::getAdvertising();
}

void loop() {

  pAdvert->stop();
  pAdvert->setAdvertisementType(BLE_GAP_CONN_MODE_NON);
  pAdvert->setServiceData(serviceID1, std::string((char*)&count, sizeof(count)));  
  pAdvert->setServiceData(serviceID2, std::string("bleh"));

  pAdvert->start();    
  Serial.printf("Advertising count = %d\n", count);
  count++;
  delay(5000);
}

I expected both services to be advertised but it seems like only the 2nd one is being adverted. (I checked with nRF Connect app). Is it possible that only a single service can be adverted?

h2zero commented 4 months ago

The second call to setservicedata will overwrite the first. There is no provision in that call to handle multiples and with 2 128bit uuids there is not enough room in the advertisement packet.

You'll need to create 2 instances of NimBLEAdvertisementData, one for the advertisement and one for the scan response and put each service data into one or the other of those then set the advertisement and scan data. The iBeacon example shows how to do this.