低功耗
著称,因此通常被称为BLE(bluetooth low energy)// 1. 建立中心管家,而且设置代理 self.cmgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
// 2. 在代理方法中扫描外部设备 /** * scanForPeripheralsWithServices :若是传入指定的数组,那么就只会扫描数组中对应ID的设备 * 若是传入nil,那么就是扫描全部能够发现的设备 * 扫描完外部设备就会通知CBCentralManager的代理 */ - (void)centralManagerDidUpdateState:(CBCentralManager *)central { if ([central state] == CBCentralManagerStatePoweredOn) { [self.cmgr scanForPeripheralsWithServices:nil options:nil]; } }
/** * 发现外部设备,每发现一个就会调用这个方法 * 因此可使用一个数组来存储每次扫描完成的数组 */ - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI { // 有可能会致使重复添加扫描到的外设 // 因此须要先判断数组中是否包含这个外设 if(![self.peripherals containsObject:peripheral]){ [self.peripherals addObject:peripheral]; } }
/** * 模拟开始链接方法 */ - (void)start { // 3. 链接外设 for (CBPeripheral *ppl in self.peripherals) { // 扫描外设的服务 // 这个操做应该交给外设的代理方法来作 // 设置代理 ppl.delegate = self; [self.cmgr connectPeripheral:ppl options:nil]; } }
服务和特征的关系数组
每一个蓝牙4.0的设备都是经过服务和特征来展现本身的,一个设备必然包含一个或多个服务,每一个服务下面又包含若干个特征。
代理
/** * 链接外设成功调用 */ - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { // 查找外设服务 [peripheral discoverServices:nil]; }
/** * 发现服务就会调用代理方法 * * @param peripheral 外设 */ - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { // 扫描到设备的全部服务 NSArray *services = peripheral.services; // 根据服务再次扫描每一个服务对应的特征 for (CBService *ses in services) { [peripheral discoverCharacteristics:nil forService:ses]; } }
/** * 发现服务对应的特征 */ - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { // 服务对应的特征 NSArray *ctcs = service.characteristics; // 遍历全部的特征 for (CBCharacteristic *character in ctcs) { // 根据特征的惟一标示过滤 if ([character.UUID.UUIDString isEqualToString:@"XMG"]) { NSLog(@"能够吃饭了"); } } }
/** * 断开链接 */ - (void)stop { // 断开全部链接上的外设 for (CBPeripheral *per in self.peripherals) { [self.cmgr cancelPeripheralConnection:per]; } }