我正在使用蓝牙技术4.0开发邻近感应应用程序。我能够发现设备。但是我无法与他们配对。我也不能调用[peripheral readRssi]
方法。我想实现的方式是,如果中央扫描说10个设备,并且在找到许多设备后,它应该停止扫描,然后将设备配对,然后不断读取RSSI值。
我的代码。
- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
BOOL (^test)(id obj, NSUInteger idx, BOOL *stop);
test = ^ (id obj, NSUInteger idx, BOOL *stop) {
if([[[obj peripheral] name] compare:peripheral.name] == NSOrderedSame)
return YES;
return NO;
};
PeripheralCell* cell;
NSUInteger t=[peripherals indexOfObjectPassingTest:test];
if(t!= NSNotFound)
{
cell=[peripherals objectAtIndex:t];
cell.peripheral=peripheral;
cell.rssi=RSSI;
//NSLog(@"%@",RSSI);
[scanResultTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:t inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
else{
cell=[[PeripheralCell alloc] init];
[peripherals addObject: cell];
[myPeripheral addObject: peripheral];
cell.peripheral=peripheral;
cell.rssi=RSSI;
NSLog(@"UUID===%@",[peripheral UUID]);
[scanResultTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[peripherals count]-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
if([myPeripheral count]==3)
{
[manager stopScan];
for(CBPeripheral *p in myPeripheral)
{
[manager connectPeripheral:p options:nil]; //this calls didConnectPeripheral but gets disconnected after some time
[p readRssi]; //this does not work even after connecting
}
}
}
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
//self.cBReady = false;
switch (central.state) {
case CBCentralManagerStatePoweredOff:
NSLog(@"CoreBluetooth BLE hardware is powered off");
break;
case CBCentralManagerStatePoweredOn:
NSLog(@"CoreBluetooth BLE hardware is powered on and ready");
//self.cBReady = true;
break;
case CBCentralManagerStateResetting:
NSLog(@"CoreBluetooth BLE hardware is resetting");
break;
case CBCentralManagerStateUnauthorized:
NSLog(@"CoreBluetooth BLE state is unauthorized");
break;
case CBCentralManagerStateUnknown:
NSLog(@"CoreBluetooth BLE state is unknown");
break;
case CBCentralManagerStateUnsupported:
NSLog(@"CoreBluetooth BLE hardware is unsupported on this platform");
break;
default:
break;
}
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@"connected peripheral");
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;
{
NSLog(@"peripheral disconnected");
}
- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"updated rssi");
}
我如何配对设备...
在大量搜索和跟踪和错误之后,我发现我的代码是正确的。我只需要从iPad的设置中删除设备。
goto Settings > General > Bluetooth > Devices.
通过单击附件指示器选择设备。在下一个屏幕中,只需单击"忘记此设备"。
再次运行应用程序解决了我的问题。