"corebluetooth: how to design code for many characteristics (30 - 40)?" Code Answer


breaking out logic into several self contained classes is always good design. you should definitely try to group your code according to services or other categories. even though the peripheral has only a single delegate, you can easily implement the dispatcher pattern where you register the various service implementations and selection keys (practically the service objects) and dispatch the call to the designated service handler. if the service classes implement the cpperipheraldelegate protocol, then this design will allow you to test/reuse each service separately if you need to with minimal changes in the code.

in pseudo obj-c code the dispatcher peripheral delegate would look like as follows:

// the ivar/property serving as the registry
nsmutabledictionary *registeredhandlers = [[nsmutabledictionary alloc] init];

- (void)peripheral:(cbperipheral *)peripheral diddiscoverservices:(nserror *)error {
  // for each service create an instance of its handler class and
  // add them to the registered handlers
  for (cbservice *service : peripheral.services) {
    if (!registeredhandlers[service]) { // don't reinitialize if not needed
      extendedcbperipheraldelegate *servicehandler = [self instantiatehandlerforservice:service];
      [registeredhandlers setobject:servicehandler forkey:service];
      [servicehandler discovercharacteristics]; // make this functionality self contained for the service

in service or characteristic related callbacks the dispatching should be implemented. an example:

- (void)peripheral:(cbperipheral *)peripheral diddiscovercharacteristicsforservice:(cbservice *)service error:(nserror *)error {
  extendedcbperipheraldelegate *servicehandler = registeredhandlers[service];
  [servicehandler peripheral:peripheral diddiscovercharacteristicsforservice:service error:error];

- (void)peripheral:(cbperipheral *)peripheral didwritevalueforcharacteristic:(cbcharacteristic *)characteristic error:(nserror *)error {
  extendedcbperipheraldelegate *servicehandler = registeredhandlers[characteristic.service];
  [servicehandler peripheral:peripheral didwritevalueforcharacteristic:characteristic error:error];

if the central manager is powered off, then the best solution is to drop the whole peripheral delegate. don't bother with reinitialization, rather plan for disposal. of course, if needed, you can notify the service handlers of the imminent destruction.

By Scam on July 14 2022

Answers related to “corebluetooth: how to design code for many characteristics (30 - 40)?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.