Skip to content

Commit 7412708

Browse files
Review comments / tidyup
Add assertChipStackLockedByCurrentThread() to CB delegate methods. Use assign instead of unsafe_unretained for non-retainable types. Add comment to BLE Base UUID.
1 parent 50e3e11 commit 7412708

File tree

4 files changed

+80
-27
lines changed

4 files changed

+80
-27
lines changed

src/darwin/Framework/CHIP/MTRCommissionableBrowser.mm

+3-1
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,11 @@
2626
#include <controller/CHIPDeviceController.h>
2727
#include <lib/dnssd/platform/Dnssd.h>
2828
#include <platform/CHIPDeviceLayer.h>
29+
#include <platform/Darwin/BleUtils.h>
2930

3031
using namespace chip::Dnssd;
3132
using namespace chip::DeviceLayer;
33+
using namespace chip::DeviceLayer::Internal;
3234

3335
#if CONFIG_NETWORK_LAYER_BLE
3436
#include <platform/Darwin/BleScannerDelegate.h>
@@ -305,7 +307,7 @@ void OnBleScanAdd(BLE_CONNECTION_OBJECT connObj, const ChipBLEDeviceIdentificati
305307
result.discriminator = @(info.GetDeviceDiscriminator());
306308
result.commissioningMode = YES;
307309
result.params = chip::MakeOptional(chip::Controller::SetUpCodePairerParameters(connObj, false /* connected */));
308-
result.peripheral = (__bridge CBPeripheral *) connObj; // avoid params holding a dangling pointer
310+
result.peripheral = CBPeripheralFromBleConnObject(connObj); // avoid params holding a dangling pointer
309311

310312
MATTER_LOG_METRIC(kMetricBLEDevicesAdded, ++mBLEDevicesAdded);
311313

src/platform/Darwin/BleConnectionDelegateImpl.mm

+31-26
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,13 @@ @interface BleConnection : NSObject <CBCentralManagerDelegate, CBPeripheralDeleg
6464
@property (nonatomic, readonly, nullable) dispatch_source_t timer;
6565
@property (nonatomic, readonly) BleConnectionMode currentMode;
6666
@property (strong, nonatomic) NSMutableDictionary<CBPeripheral *, NSDictionary *> * cachedPeripherals;
67-
@property (unsafe_unretained, nonatomic) bool found;
68-
@property (unsafe_unretained, nonatomic) chip::SetupDiscriminator deviceDiscriminator;
69-
@property (unsafe_unretained, nonatomic) void * appState;
70-
@property (unsafe_unretained, nonatomic) BleConnectionDelegate::OnConnectionCompleteFunct onConnectionComplete;
71-
@property (unsafe_unretained, nonatomic) BleConnectionDelegate::OnConnectionErrorFunct onConnectionError;
72-
@property (unsafe_unretained, nonatomic) chip::DeviceLayer::BleScannerDelegate * scannerDelegate;
73-
@property (unsafe_unretained, nonatomic) chip::Ble::BleLayer * mBleLayer;
67+
@property (assign, nonatomic) bool found;
68+
@property (assign, nonatomic) chip::SetupDiscriminator deviceDiscriminator;
69+
@property (assign, nonatomic) void * appState;
70+
@property (assign, nonatomic) BleConnectionDelegate::OnConnectionCompleteFunct onConnectionComplete;
71+
@property (assign, nonatomic) BleConnectionDelegate::OnConnectionErrorFunct onConnectionError;
72+
@property (assign, nonatomic) chip::DeviceLayer::BleScannerDelegate * scannerDelegate;
73+
@property (assign, nonatomic) chip::Ble::BleLayer * mBleLayer;
7474

7575
- (instancetype)initWithDelegate:(chip::DeviceLayer::BleScannerDelegate *)delegate prewarm:(bool)prewarm;
7676
- (instancetype)initWithDiscriminator:(const chip::SetupDiscriminator &)deviceDiscriminator;
@@ -129,7 +129,7 @@ - (void)removePeripheralsFromCache;
129129
ChipLogProgress(Ble, "ConnectionDelegate NewConnection with conn obj: %p", connObj);
130130
CBPeripheral * peripheral = CBPeripheralFromBleConnObject(connObj);
131131

132-
// The BLE_CONNECTION_OBJECT represent a CBPeripheral object. In order for it to be valid the central
132+
// The BLE_CONNECTION_OBJECT represents a CBPeripheral object. In order for it to be valid the central
133133
// manager needs to still be running.
134134
if (!ble || [ble isConnecting]) {
135135
if (OnConnectionError) {
@@ -308,6 +308,7 @@ - (void)dispatchConnectionComplete:(CBPeripheral *)peripheral
308308

309309
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
310310
{
311+
assertChipStackLockedByCurrentThread();
311312
MATTER_LOG_METRIC(kMetricBLECentralManagerState, static_cast<uint32_t>(central.state));
312313

313314
switch (central.state) {
@@ -340,6 +341,8 @@ - (void)centralManager:(CBCentralManager *)central
340341
advertisementData:(NSDictionary *)advertisementData
341342
RSSI:(NSNumber *)RSSI
342343
{
344+
assertChipStackLockedByCurrentThread();
345+
343346
NSData * serviceData = advertisementData[CBAdvertisementDataServiceDataKey][_chipServiceUUID];
344347
if (!serviceData) {
345348
return;
@@ -405,8 +408,10 @@ - (BOOL)checkDiscriminator:(uint16_t)discriminator
405408

406409
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
407410
{
411+
assertChipStackLockedByCurrentThread();
408412
MATTER_LOG_METRIC_END(kMetricBLEConnectPeripheral);
409413
MATTER_LOG_METRIC_BEGIN(kMetricBLEDiscoveredServices);
414+
410415
[peripheral setDelegate:self];
411416
[peripheral discoverServices:nil];
412417
[self stopScanning];
@@ -418,6 +423,8 @@ - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPerip
418423

419424
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
420425
{
426+
assertChipStackLockedByCurrentThread();
427+
421428
if (nil != error) {
422429
ChipLogError(Ble, "BLE:Error finding Chip Service in the device: [%s]", [error.localizedDescription UTF8String]);
423430
}
@@ -442,6 +449,7 @@ - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)err
442449

443450
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
444451
{
452+
assertChipStackLockedByCurrentThread();
445453
MATTER_LOG_METRIC_END(kMetricBLEDiscoveredCharacteristics, CHIP_ERROR(chip::ChipError::Range::kOS, static_cast<uint32_t>(error.code)));
446454

447455
if (nil != error) {
@@ -457,6 +465,8 @@ - (void)peripheral:(CBPeripheral *)peripheral
457465
didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
458466
error:(NSError *)error
459467
{
468+
assertChipStackLockedByCurrentThread();
469+
460470
if (nil == error) {
461471
ChipBleUUID svcId = BleUUIDFromCBUUD(characteristic.service.UUID);
462472
ChipBleUUID charId = BleUUIDFromCBUUD(characteristic.UUID);
@@ -473,6 +483,8 @@ - (void)peripheral:(CBPeripheral *)peripheral
473483
didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
474484
error:(NSError *)error
475485
{
486+
assertChipStackLockedByCurrentThread();
487+
476488
bool isNotifying = characteristic.isNotifying;
477489

478490
if (nil == error) {
@@ -503,6 +515,8 @@ - (void)peripheral:(CBPeripheral *)peripheral
503515
didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
504516
error:(NSError *)error
505517
{
518+
assertChipStackLockedByCurrentThread();
519+
506520
if (nil == error) {
507521
ChipBleUUID svcId = BleUUIDFromCBUUD(characteristic.service.UUID);
508522
ChipBleUUID charId = BleUUIDFromCBUUD(characteristic.UUID);
@@ -550,28 +564,19 @@ - (void)stop
550564
[self stopScanning];
551565
[self removePeripheralsFromCache];
552566

553-
if (!_centralManager && !_peripheral) {
554-
return;
567+
if (_peripheral) {
568+
// Close all BLE connections before we release CB objects
569+
_mBleLayer->CloseAllBleConnections();
570+
_peripheral = nil;
555571
}
556572

557-
// Properly closing the underlying ble connections needs to happens
558-
// on the chip work queue. At the same time the SDK is trying to
559-
// properly unsubscribe and shutdown the connection, so if we nullify
560-
// the centralManager and the peripheral members too early it won't be
561-
// able to reach those.
562-
// This is why closing connections happens as 2 async steps.
563-
{
564-
if (_peripheral) {
565-
// Close all BLE connections before we release CB objects
566-
_mBleLayer->CloseAllBleConnections();
567-
}
568-
573+
if (_centralManager) {
569574
_centralManager.delegate = nil;
570575
_centralManager = nil;
571-
_peripheral = nil;
572-
if (chip::DeviceLayer::Internal::ble == self) {
573-
chip::DeviceLayer::Internal::ble = nil;
574-
}
576+
}
577+
578+
if (chip::DeviceLayer::Internal::ble == self) {
579+
chip::DeviceLayer::Internal::ble = nil;
575580
}
576581
}
577582

src/platform/Darwin/BlePeripheral.h

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
*
3+
* Copyright (c) 2025 Project CHIP Authors
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
#pragma once
19+
20+
#if !__has_feature(objc_arc)
21+
#error This file must be compiled in ObjC++ mode with ARC.
22+
#endif
23+
24+
#include <ble/Ble.h>
25+
26+
#import <CoreBluetooth/CoreBluetooth.h>
27+
28+
namespace chip {
29+
namespace DeviceLayer {
30+
namespace Internal {
31+
32+
// Holds a CBPeripheral and the associated CBCentralManager
33+
struct BlePeripheral
34+
{
35+
CBPeripheral * const peripheral;
36+
CBCentralManager * const centralManager;
37+
38+
BlePeripheral(CBPeripheral * aPeripheral, CBCentralManager * aCentralManager) :
39+
peripheral(aPeripheral), centralManager(aCentralManager)
40+
{}
41+
};
42+
43+
} // namespace Internal
44+
} // namespace DeviceLayer
45+
} // namespace chip

src/platform/Darwin/BleUtils.mm

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ ChipBleUUID BleUUIDFromCBUUD(CBUUID * uuid)
3535
// CBUUID handles the expansion to 128 bit automatically internally,
3636
// but doesn't expose the expanded UUID in the `data` property, so
3737
// we have to re-implement the expansion here.
38+
// The Base UUID 00000000-0000-1000-8000-00805F9B34FB is defined in the BLE spec.
3839
constexpr ChipBleUUID baseUuid = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB } };
3940
NSData * uuidData = uuid.data;
4041
switch (uuidData.length) {

0 commit comments

Comments
 (0)