iOS藍牙開發總結

1.創建藍牙管理中心
    @property(strong, nonatomic)    CBCentralManager        *activeCentralManager;

   _activeCentralManager = [[CBCentralManager alloc] initWithDelegate:(id<CBCentralManagerDelegate>)self queue:dispatch_get_main_queue()];

2.掃描外圍設備(scan)
    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
          CBCentralManagerScanOptionAllowDuplicatesKey 的做用是:若是是同一設備會屢次掃描。
    [_activeCentralManager scanForPeripheralsWithServices:nil options:options];
3.鏈接外設(connect)
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI 
{
    if ([_activeCentralManager isEqual:central]) {
                [self connect:peripheral];
        }

}       

- (void)connectDevice:(id)device{
    if (![peripheral services]){
        // 鏈接設備
        //    connectPeripheral方法鏈接成功後,會調用centralManager:didConnectPeripheral:
        [_activeCentralManager connectPeripheral:peripheral options:nil];
    }
    else{
        //鏈接失敗
    }
}
4.掃描外設中的服務和特徵(discover)
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    if ([_activeCentralManager isEqual:central]) {
        if (peripheral != nil){
            NSLog(@"鏈接成功");
            // 若是當前設備是已鏈接設備開始掃描服務
            NSArray *serviceArray = [self getServiceArray];
            [peripheral setDelegate:(id<CBPeripheralDelegate>)self];
            [peripheral discoverServices:serviceArray]; //執行完成此語句後 會執行discoverServices:的回調方法didDiscoverServices: 
                 //serviceArray中能夠包含指定的廣播 好比:18F5 
            //[peripheral discoverServices:nil]; //當穿入nil時  默認掃描全部廣播
        }
    }
}
5.與外設進行數據交互(進行特徵值更新)
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
}//此方法能夠獲取到你想要的外設數據(存放在characteristic.value中)
if (characteristic != nil) {
                [_activePeripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];//寫入數據 
                return YES;
}
此處需注意 發送數據時writeValue: forCharacteristic: type:中的type應設置爲響應模式發送 (CBCharacteristicWriteWithResponse)若是設置爲非響應的模式(CBCharacteristicWriteWithoutResponse)有可能會致使藍牙數據發送失敗,沒法操控藍牙設備。atom

相關文章
相關標籤/搜索