iOS藍芽開發

prger發表於2019-05-08

藍芽基礎知識

藍芽庫

當前iOS中的藍芽開發使用的都是系統自帶的藍芽庫<CoreBluetooth/CoreBluetooth.h>

藍芽裝置版本要求

藍芽裝置必須是4.0或者以上

CoreBluetooth框架的核心

CoreBluetooth框架中的核心是peripheral和central, 它們分別表示外設和中心,裝置上可以認為手機就是中心, 藍芽裝置就是外設

服務和特徵

藍芽裝置它有若干個服務service,每個服務裡面有包含若干個特徵characteristic,特徵就是提供資料的地方

外設, 服務, 特徵間的關係

iOS藍芽開發

CoreBluetooth框架的架構

iOS藍芽開發

連線藍芽的具體實現

實現流程

1.建立中心角色
2.掃描外設
3.連線外設
4.獲取外設中的服務和特徵
5.與外設做互動

實現步驟

1.匯入CoreBluetooth標頭檔案,新增代理,建立中心角色

#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (strong, nonatomic) CBCentralManager *centralManager;               //藍芽管理者
@property(strong,nonatomic)CBPeripheral *peripheral;                      //儲存匹配成功的外設

-(void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化,最後一個執行緒引數可以為nil,預設是main執行緒
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
複製程式碼

2.掃描外設

/*
    1.初始化成功會自動呼叫
    2.必須實現的代理,返回centralManager的狀態
    3.只有在狀態為CBManagerStatePoweredOn的情況下才可以開始掃描外設
*/
-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
        case CBManagerStateUnknown:
            NSLog(@">>>未知");
            break;
        case CBManagerStateResetting:
            NSLog(@">>>重置");
            break;
        case CBManagerStateUnsupported:
            NSLog(@">>>裝置不支援");
            break;
        case CBManagerStateUnauthorized:
            NSLog(@">>>裝置未授權");
            break;
        case CBManagerStatePoweredOff:
        {
            NSLog(@">>>裝置關閉");
            self.bleStatusBlock(NO);
        }
            break;
        case CBManagerStatePoweredOn:
        {
            NSLog(@">>>裝置開啟");
             //開始掃描外設, 然後會進入didDiscoverPeripheral方法
            /*
                1. 兩個引數為nil表示預設掃描所有可見的藍芽裝置
                2. 第一個引數用來設定掃描有指定服務的外設
                3. 第二個引數用來設定是否重複掃描已經發現的裝置
                
                NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
                
                Bool值為Yes,表示重複掃描, 反之表示不會重複掃描
                
            */
            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
        }
            break;
            
        default:
            break;
    }
}
複製程式碼

連線外設

//掃描到的裝置可以在這個方法裡面列印
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI {
    NSLog(@">>>advertisementData :%@  name :%@ ",advertisementData,peripheral.name);
    
    //有些產品是根據Mac地址來進行配對, 在這裡我們就可以拿到,具體什麼規則, 根據各個藍芽裝置來定
    NSData *data = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"];
    //解析
    //.....
    if(自己的判斷) {
        //找到的裝置必須持有它,否則CBCentralManager中也不會儲存peripheral,那麼CBPeripheralDelegate中的方法也不會被呼叫!!
        self.peripheral = peripheral;
        
        //停止掃描
        [self.centralManager stopScan];
        
        //連線外設
        [_centralManager connectPeripheral:peripheral options:nil];
    }
}

//連線到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@">>>連線到名稱為(%@)的裝置-成功",peripheral.name);
}

//連線到Peripherals-失敗
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>連線到名稱為(%@)的裝置-失敗,原因:%@",[peripheral name],[error localizedDescription]);
}

//Peripherals斷開連線
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>外設連線斷開連線 %@: %@\n", [peripheral name], [error localizedDescription]);
}
複製程式碼

獲取外設中的服務和特徵


 //連線外設成功
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    NSLog(@">>>連線到名稱為(%@)的裝置-成功",peripheral.name);
    peripheral.delegate=self;//這個方法呼叫發現服務協議
    [peripheral discoverServices:nil];
}

//掃描到服務
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    NSLog(@">>>掃描到服務:%@",peripheral.services);
    if (error) {
        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    
    for (CBService *service in [peripheral services]){
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

//掃描到特徵
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    
    if (error) {
        NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        
        NSLog(@">>>服務:%@ 的 特徵: %@",service.UUID,characteristic.UUID);
        
        //篩選你需要的UUID,進行連線
        if ([characteristic.UUID isEqual:yourUUID) {
        
            訂閱,實時接收
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
}
複製程式碼

讀取資料

//獲取指定特性的資料
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    //接收藍芽發來的資料
     NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);
}
複製程式碼

寫入資料


//寫入資料
-(void)writeData {
    [self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}

//寫入資料的回撥
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    if (error) {
         NSLog(@"error Discovered characteristics for %@ with error: %@", characteristic.UUID, [error localizedDescription]);
        return;
    }
    NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);
}
複製程式碼

斷開連線

- (void)disConnect{
    [self.centralManager cancelPeripheralConnection:self.peripheral];
}
複製程式碼

相關文章