iOS 藍牙鏈接工具類

基礎知識瞭解git

  • peripheral 外設,被鏈接的設備爲perilheral
  • central 發起鏈接的時central
  • service and characteristic 服務和特徵 每一個設備都會提供服務和特徵,相似於服務端的api,可是因爲結構不一樣,每一個外設會有不少的服務,每一個服務中又包含不少字段,這些字段的權限通常分爲 讀read,寫write,通知notiy幾種,就是咱們鏈接設備後具體須要操做的內容。
  • Description 每一個characteristic能夠對應一個或多個Description用戶描述characteristic的信息或屬性
  • Characteristic 一個characteristic包括一個單一變量和0-n個用來描述characteristic變量的descriptor,characteristic能夠被認爲是一個類型,類 似於類。
  • Descriptor Descriptor用來描述characteristic變量的屬性。例如,一個descriptor能夠規定一個可讀的描述,或者一個characteristic變量可接受的 範圍,或者一個characteristic變量特定的測量單位。
  • Service service是characteristic的集合

BLE中的開發要使用CoreBluetooth框架 CoreBluetooth框架的核心實際上是兩個東西,peripheral和central, 能夠理解成外設和中心。對應他們分別有一組相關的API和類藍牙設備的幾種狀態:github

  • 準備(standby)
  • 廣播(advertising)
  • 監聽掃描(Scanning
  • 發起鏈接(Initiating)
  • 已鏈接(Connected)

做爲中心模式流程:api

  • 創建中心角色bash

  • 掃描外設(discover)框架

  • 鏈接外設(connect)工具

  • 掃描外設中的服務和特徵(discover)ui

    • 獲取外設的services
    • 獲取外設的Characteristics,獲取Characteristics的值,獲取Characteristics的Descriptor和Descriptor的值
  • 與外設作數據交互(explore and interact)spa

  • 訂閱Characteristic的通知代理

  • 斷開鏈接(disconnect)code

做爲外設模式流程:

  • 啓動一個Peripheral管理對象
  • 本地Peripheral設置服務,特性,描述,權限等等
  • Peripheral發送廣告
  • 設置處理訂閱、取消訂閱、讀characteristic、寫characteristic的委託方法

具體實施以下

  • 首先導入工具類, 設置代理
[BLEManager.shareInstance setDelegate:self];
複製代碼
  • 搜索設備
#pragma mark- 開始搜索
- (void)beginScan{
    [self.cbCM scanForPeripheralsWithServices:nil options:nil];
}
複製代碼
  • 鏈接設備
#pragma mark- 鏈接設備
- (void)connect:(CBPeripheral *)peripheral{
    [self.cbCM stopScan];
    [self.cbCM connectPeripheral:peripheral options:nil];
}
複製代碼
  • 判斷是否鏈接成功
#pragma mark- 鏈接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    connectPeripheral = peripheral;
    peripheral.delegate = self;
    [peripheral discoverServices:nil];
    if ([self.delegate respondsToSelector:@selector(didConnectPeripheral:)]) {
        [self.delegate didConnectPeripheral:peripheral];
    }
}
#pragma mark- 鏈接失敗
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    if ([self.delegate respondsToSelector:@selector(didFailToConnectPeripheral:error:)]) {
        [self.delegate didFailToConnectPeripheral:peripheral error:error];
    }
}
複製代碼
  • 設置服務和特徵
//發現服務
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    for (CBService *s in peripheral.services) {
        if ([s.UUID.UUIDString isEqualToString:self->serviceUUIDString]) {
            //這裏能夠經過service的UUID屬性來辨識你要的服務
            [peripheral discoverCharacteristics:nil forService:s];
        }
    }
}
//設置特徵屬性值
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:self->notify]]){
            // 訂閱, 實時接收
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:self->write]]){
            self.writeCharacteristic = characteristic;
        }
    }
}
複製代碼
  • 發送數據
#pragma mark- 發送數據
- (void)write:(NSData *)data withResponse:(BOOL)withResponse{
    if(!_writeCharacteristic){
        NSLog(@"writeCharacteristic is nil!");
        return;
    }
    [connectPeripheral writeValue:data forCharacteristic:self.writeCharacteristic type:withResponse ? CBCharacteristicWriteWithResponse : CBCharacteristicWriteWithoutResponse];
}
複製代碼
  • 接收回調數據
#pragma mark- 藍牙數據接收
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:self->serviceUUIDString]]) {
        NSData *data = characteristic.value;
        if (data) {
            if ([self.delegate respondsToSelector:@selector(bleGattServiceDataReceived:)]) {
                [self.delegate bleGattServiceDataReceived:data];
            }
        }
    }
}

複製代碼
  • 實時監測藍牙狀態
#pragma mark- 藍牙狀態的改變
- (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)central {
    switch (central.state) {
        case CBManagerStateUnknown:
            //未知狀態
            break;
        case CBManagerStateResetting:
            //藍牙重置中
            break;
        case CBManagerStateUnsupported:
            //藍牙不支持
            break;
        case CBManagerStateUnauthorized:
            //沒有權限
            break;
        case CBManagerStatePoweredOff:
            //藍牙爲開啓
            break;
        case CBManagerStatePoweredOn:
            //藍牙已開啓
            break;
        default:
            break;
    }
}
複製代碼

藍牙鏈接操做基本流程即爲上文所述, 如需詳細代碼解析, 請查看demo 代碼地址:代碼傳送門

相關文章
相關標籤/搜索