Skip to content

Commit

Permalink
Make sure to do our BLE callbacks on the right dispatch queue.
Browse files Browse the repository at this point in the history
We were calling back into the Matter core while running on the BLE queue.

#20230
  • Loading branch information
bzbarsky-apple committed Jul 1, 2022
1 parent 6fd06ea commit 181c742
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/platform/Darwin/BleConnectionDelegateImpl.mm
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ - (id)initWithDiscriminator:(uint16_t)deviceDiscriminator

dispatch_source_set_event_handler(_timer, ^{
[self stop];
_onConnectionError(_appState, BLE_ERROR_APP_CLOSED_CONNECTION);
[self dispatchConnectionError:BLE_ERROR_APP_CLOSED_CONNECTION];
});
dispatch_source_set_timer(
_timer, dispatch_walltime(nullptr, kScanningTimeoutInSeconds * NSEC_PER_SEC), DISPATCH_TIME_FOREVER, 5 * NSEC_PER_SEC);
Expand All @@ -117,6 +117,21 @@ - (id)initWithDiscriminator:(uint16_t)deviceDiscriminator
return self;
}

// All our callback dispatch must happen on _chipWorkQueue
- (void)dispatchConnectionError:(CHIP_ERROR)error
{
dispatch_async(_chipWorkQueue, ^{
self.onConnectionError(self.appState, error);
});
}

- (void)dispatchConnectionComplete:(CBPeripheral *)peripheral
{
dispatch_async(_chipWorkQueue, ^{
self.onConnectionComplete(self.appState, (__bridge void *) peripheral);
});
}

// Start CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
Expand All @@ -129,7 +144,7 @@ - (void)centralManagerDidUpdateState:(CBCentralManager *)central
case CBManagerStatePoweredOff:
ChipLogDetail(Ble, "CBManagerState: OFF");
[self stop];
_onConnectionError(_appState, BLE_ERROR_APP_CLOSED_CONNECTION);
[self dispatchConnectionError:BLE_ERROR_APP_CLOSED_CONNECTION];
break;
case CBManagerStateUnauthorized:
ChipLogDetail(Ble, "CBManagerState: Unauthorized");
Expand Down Expand Up @@ -216,7 +231,7 @@ - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)err

if (!self.found || error != nil) {
ChipLogError(Ble, "Service not found on the device.");
_onConnectionError(_appState, CHIP_ERROR_INCORRECT_STATE);
[self dispatchConnectionError:CHIP_ERROR_INCORRECT_STATE];
}
}

Expand All @@ -228,7 +243,7 @@ - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForServi
}

// XXX error ?
_onConnectionComplete(_appState, (__bridge void *) peripheral);
[self dispatchConnectionComplete:peripheral];
}

- (void)peripheral:(CBPeripheral *)peripheral
Expand Down

0 comments on commit 181c742

Please sign in to comment.