1、开启蓝牙:
_manager= [[CBCentralManager alloc] initWithDelegate:self queue:nil];
2、蓝牙扫描:
if (_manager.state == CBManagerStatePoweredOn) {
[selfcancelScanf];
[_manager scanForPeripheralsWithServices:nil options:nil];
}
3、通过回调获取蓝牙设备,并过滤所需设备:
- (void) centralManager:(CBCentralManager*)central didDiscoverPeripheral:(CBPeripheral*)peripheral advertisementData:(NSDictionaryid> *)advertisementData RSSI:(NSNumber*)RSSI {
//忽略没有名字的外设
if(peripheral.name.length==0|| ![peripheral.namehasPrefix:@"SDN"]) {
return;
}
}
4、连接蓝牙设备:
[_manager connectPeripheral:peripheral options:nil];
5、等待设备连接成功回调后,获取设备服务:
- (void) centralManager:(CBCentralManager*)central didConnectPeripheral:(CBPeripheral*)peripheral {
_currentPeripheral = peripheral;
_currentPeripheral.delegate = self;
[_currentPeripheral discoverServices:nil];
}
6、等待获取设备服务成功回调后,获取设备服务特征:
- (void)peripheral:(CBPeripheral*)peripheral didDiscoverServices:(nullableNSError*)error {
//LLLog(@"发现服务:%@",peripheral.services);
//NSLog(@" 当前线程 %@",[NSThread currentThread]);
for(CBService*serviceinperipheral.services) {
//读取每个服务的所有特征
[peripheraldiscoverCharacteristics:nil forService:service];
}
}
7、等待获取设备服务特征成功回调后,可以进行通讯:
- (void)peripheral:(CBPeripheral*)peripheral didDiscoverCharacteristicsForService:(CBService*)service error:(nullableNSError*)error {
//LLLog(@"发现服务%@的特征%@",service,service.characteristics);
//NSLog(@" 当前线程 %@",[NSThread currentThread]);
if([service.UUID.UUIDStringisEqualToString:@"FFE0"]) {
for (CBCharacteristic *c in service.characteristics) {
if([c.UUID.UUIDStringisEqualToString:@"FFE1"]) {
_currentCharacteristic = c;
[_currentPeripheral setNotifyValue:YES forCharacteristic:c];
LLLog(@"%@ 连接成功", peripheral.name);
if([self.delegaterespondsToSelector:@selector(connectCallBack:)])
{
[self.delegate connectCallBack:peripheralConnectStateSuccess];
break;
}
}
}
}
}