iOS 블 루 투 스 개발 블 루 투 스 연결 및 데이터 읽 기와 쓰기

블 루 투 스 개발 을 하기 전에 먼저 개념 을 알 아 보 는 것 이 좋다.
서비스(services):블 루 투 스 외부 에 설 치 된 대외 방송 은 반드시 하나의 서비스 가 있 고 여러 가지 서비스 가 있 을 수 있 습 니 다.서비스 아래 에는 일부 특징 이 포함 되 어 있 고 서 비 스 는 하나의 모듈 의 창 으로 이해 할 수 있 습 니 다.
특징(characteristic):서비스 아래 에 존재 하 는 것 은 하나의 서비스 아래 에 도 여러 가지 특징 이 존재 할 수 있다.특징 은 구체 적 으로 기능 을 실현 하 는 창 으로 이해 할 수 있다.일반적인 특징 은 모두 value,즉 특징 값 이 있 는데 특징 은 외부 와 상호작용 하 는 최소 단위 이다.
UUID:블 루 투 스 의 유일한 식별 자(하드웨어 에 서 는 분명 그런 뜻 이 아 닐 것 입 니 다.하지만 이렇게 이해 하면 개발 에 편리 합 니 다)로 이해 할 수 있 습 니 다.서로 다른 서비스 와 특징 을 구분 하거나 서비스 와 특징 에 이름 을 짓 기 위해 저 희 는 UUID 로 서비스 와 특징 을 대표 합 니 다.
블 루 투 스 연결 은 크게 다음 과 같은 몇 가지 절차 로 나 눌 수 있다.
1.중앙 관리자 인 스 턴 스 를 만들어 블 루 투 스 관 리 를 한다.
2.주변 장치 검색
3.주변 장치 연결
4.주변 장치 의 서 비 스 를 받는다
5.서비스의 특징 획득
6.외부 장치 에서 데이터 읽 기
7.외부 장치 에 데이터 전송
알림
일단 시스템 의 BLE 프레임 을 가 져 오 겠 습 니 다.
#import
반드시 두 가지 협 의 를 준수 해 야 한다.

/**센터 관리자*/
@property (nonatomic, strong) CBCentralManager *cMgr;
/*연 결 된 외부 장치*/
@property (nonatomic, strong) CBPeripheral *peripheral;
1.중앙 관리자 인 스 턴 스 를 만들어 블 루 투 스 관 리 를 한다.

-(CBCentralManager *)cmgr
{
  if (!_cmgr) {
    _cMgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  }
  return _cMgr;
}
 
//                             
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
  switch (central.state) {
    case 0:
      NSLog(@"CBCentralManagerStateUnknown");
      break;
    case 1:
      NSLog(@"CBCentralManagerStateResetting");
      break;
    case 2:
      NSLog(@"CBCentralManagerStateUnsupported");//     
      break;
    case 3:
      NSLog(@"CBCentralManagerStateUnauthorized");
      break;
    case 4:
    {
      NSLog(@"CBCentralManagerStatePoweredOff");//     
    }
      break;
    case 5:
    {
      NSLog(@"CBCentralManagerStatePoweredOn");//     
       //                   
      //     
      [self.cMgr scanForPeripheralsWithServices:nil //           
                       options:nil]; // dict,  
      //       ,              
      // - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //    
    }
      break;
    default:
      break;
  }
}
2.주변 장치 검색(예 를 들 어 제 주변 에 있 는 팔찌 를 사 용 했 습 니 다)

//           
- (void)centralManager:(CBCentralManager *)central //      
 didDiscoverPeripheral:(CBPeripheral *)peripheral //   
   advertisementData:(NSDictionary *)advertisementData //        
         RSSI:(NSNumber *)RSSI //            
{
  //NSLog(@"%s, line = %d, cetral = %@,peripheral = %@, advertisementData = %@, RSSI = %@", __FUNCTION__, __LINE__, central, peripheral, advertisementData, RSSI);
  
  /*
   peripheral = <CBPeripheral: 0x166668f0 identifier = C69010E7-EB75-E078-FFB4-421B4B951341, Name = "OBand-75", state = disconnected>, advertisementData = {
   kCBAdvDataChannel = 38;
   kCBAdvDataIsConnectable = 1;
   kCBAdvDataLocalName = OBand;
   kCBAdvDataManufacturerData = <4c69616e 0e060678 a5043853 75>;
   kCBAdvDataServiceUUIDs =   (
   FEE7
   );
   kCBAdvDataTxPowerLevel = 0;
   }, RSSI = -55
         ,                OBand-75
   
   */
  
  //              
  // 1.    (40     , 80    )
  // 2.     (         OBand)
  //            : OBand          35
  //     ,    RSSI    - 
  
  if ([peripheral.name hasPrefix:@"OBand"]) {
    //         advertisementData(         )       
    
    //       ,         ,                ,
    //         1     ,       1       
    
    //        ,        = vc
    self.peripheral = peripheral;
    //            
    [self.cMgr connectPeripheral:self.peripheral options:nil];
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
  }
}
3.주변 장치 연결

//            
- (void)centralManager:(CBCentralManager *)central //      
 didConnectPeripheral:(CBPeripheral *)peripheral //   
{
  NSLog(@"%s, line = %d, %@=    ", __FUNCTION__, __LINE__, peripheral.name);
  //       ,            
  
  //        
  self.peripheral.delegate = self;
  
  //       , nil     
  //              - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
  [self.peripheral discoverServices:nil];
}
//       
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
  NSLog(@"%s, line = %d, %@=    ", __FUNCTION__, __LINE__, peripheral.name);
}
 
//     
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
  NSLog(@"%s, line = %d, %@=    ", __FUNCTION__, __LINE__, peripheral.name);
}
4.주변 장치 의 서비스 획득&5.서비스의 특징 획득

//                     (          ,            UUID        ,    ,              )
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
  NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
  
  for (CBCharacteristic *cha in service.characteristics) {
    //NSLog(@"%s, line = %d, char = %@", __FUNCTION__, __LINE__, cha);
    
  }
}
5.외부 장치 에서 데이터 읽 기

//      value       (                   ,                   )        
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
  NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
  if (characteristic == @"      UUID           ") {
  //characteristic.value       
  }
}
6.외부 장치 에 데 이 터 를 보 내기(즉,블 루 투 스 에 데 이 터 를 기록 하 는 것)
이 방법 은 button 의 응답 에 넣 을 수도 있 고 특징 을 찾 을 때 기록 할 수도 있 습 니 다.업무 수요 가 어떻게 사용 되 는 지 구체 적 으로 볼 수 있 습 니 다.

[self.peripherale writeValue:_batteryData forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
//               ;              ;                    

//                   
- (void)yf_peripheral:(CBPeripheral *)peripheral didWriteData:(NSData *)data forCharacteristic:(nonnull CBCharacteristic *)characteristic
{
  /*
   typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
   CBCharacteristicPropertyBroadcast                       = 0x01,
   CBCharacteristicPropertyRead                          = 0x02,
   CBCharacteristicPropertyWriteWithoutResponse                  = 0x04,
   CBCharacteristicPropertyWrite                         = 0x08,
   CBCharacteristicPropertyNotify                         = 0x10,
   CBCharacteristicPropertyIndicate                        = 0x20,
   CBCharacteristicPropertyAuthenticatedSignedWrites               = 0x40,
   CBCharacteristicPropertyExtendedProperties                   = 0x80,
   CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)    = 0x100,
   CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x200
   };
   
           (characteristic.properties),        ,    NS_OPTIONS   ,      
       read,write,noitfy,indicate.          ,       ,      ,        
   */
//  NSLog(@"%s, line = %d, char.pro = %d", __FUNCTION__, __LINE__, characteristic.properties);
  //          NS_OPTIONS,              ,        = ,      &
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기