我似乎无法从OSX连接到BLE外设。我可以扫描得很好,但连接永远不会发生。我正在保存CBPeripheral*
对象的本地副本 - 实际上,我可以查询它并且连接状态是CBPeripheralStateConnecting
,如果我取消连接,它将更改回CBPeripheralStateDisconnected
。但它实际上从未连接 - 状态不会更改为CBPeripheralStateConnected
,并且我的连接回调都不会被调用。
我可以使用LightBlue OSX应用程序连接,扫描服务和读取特征,所以我知道我的加密狗很好。我的代码基于别人的代码,我知道代码对他有用。我的代码也适用于iOS,但不适用于我的MacBook。我继续前进并升级到El Capitan,但这没有帮助。
我尝试了各种各样的事情:将已发现的外围对象保存在一个数组中,保存我正在连接到的属性中的外围设备,将调用发送到connectPeripheral
到主线程......没有运气。代码的相关部分如下,my entire BLE code is in a gist。
- (id) init {
if (self = [super init]) {
_peripherals = [NSMutableArray new];
_connecting = nil;
eventlock = [[NSLock alloc] init];
events = [[NSMutableArray alloc] init];
central = [[CBCentralManager alloc] initWithDelegate:self
queue:dispatch_get_main_queue()];
}
return self;
}
- (void) addPeripheral:(CBPeripheral *)peripheral {
if (![self.peripherals containsObject:peripheral]) {
NSLog(@"saving peripheral");
[self.peripherals addObject:peripheral];
}
}
- (void) connectPeripheral:(CBPeripheral *)peripheral {
if (![self.peripherals containsObject:peripheral]) {
NSLog(@"error: connect to invalid peripheral");
return;
}
__weak cbcentral *this = self;
NSLog(@"dispatch connect peripheral");
self.connecting = peripheral;
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"connect peripheral");
//this.connecting = peripheral;
[central connectPeripheral:this.connecting
options:nil];
});
}
#pragma mark CBCentralManagerDelegate
- (void) centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI {
NSLog(@"did discover peripheral");
[self addPeripheral:peripheral];
NSArray* event = [[NSArray alloc] initWithObjects:@"centralManager_didDiscoverPeripheral_advertisementData_RSSI_",
central,
peripheral,
advertisementData,
RSSI,
nil];
[self queueEvent:event];
}
- (void) centralManager:(CBCentralManager *)central
didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"did connect peripheral");
[self addPeripheral:peripheral];
NSArray* event = [[NSArray alloc] initWithObjects:@"centralManager_didConnectPeripheral_",
central,
peripheral,
nil];
[self queueEvent:event];
}