基于iOS的藍(lán)牙開發(fā)

導(dǎo)語:

最近幾天在做一個(gè)關(guān)于藍(lán)牙與血壓計(jì)和血氧儀交互方面的東西,剛開始使用的是babybluetooth(但封裝的內(nèi)容我不會(huì)使用,于是就自己寫了一個(gè)工具類)。在此帶來一些關(guān)于藍(lán)牙開發(fā)的分享。

1.藍(lán)牙基礎(chǔ)知識(shí)

CoreBluetooth框架的核心是peripheral(外設(shè))和central(中心),發(fā)起連接的是 central,被連接的設(shè)備為 peripheral。在移動(dòng)端開發(fā)中,我們通常使用的是中心模式。

2.中心模式的流程

  1. 建立中心
  2. 掃描外設(shè)(discover)
  3. 連接外設(shè)(connect)
  4. 掃描外設(shè)中的服務(wù)和特征(discover)
- 4.1 獲取外設(shè)的 services
- 4.2 獲取外設(shè)的 Characteristics,獲取Characteristics的值,獲 Characteristics的 Descriptor 和 Descriptor 的值
  1. 與外設(shè)做數(shù)據(jù)交互(explore and interact)
  2. 訂閱 Characteristic 的通知
  3. 斷開連接(disconnect)

3.具體實(shí)現(xiàn)代碼

創(chuàng)建中心管理者

#import <CoreBluetooth/CoreBluetooth.h>
typedef NS_ENUM(NSInteger,BDBlueToothType){
    BDBlueToothType_Oximeter = 1,//血氧儀
    BDBlueToothType_Hamnatodynamometer //血壓計(jì)
};
//藍(lán)牙搜索到的設(shè)備數(shù)組
typedef void(^PeripheralBlock)(NSMutableArray *);
//讀到的數(shù)據(jù)
typedef void(^ReadValueBlock)(NSString *);
@interface BDBlueToothHelper : NSObject<CBCentralManagerDelegate, CBPeripheralDelegate>
//外設(shè)
@property(nonatomic, strong) CBPeripheral* myPeripheral;
//中心管理工具
@property (nonatomic, strong) CBCentralManager* myCentralManager;

初始化開始掃描

self.myCentralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil];
必須實(shí)現(xiàn)的代理方法
//查看藍(lán)牙服務(wù)
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            BDLog(@"藍(lán)牙已打開, 請(qǐng)掃描外設(shè)!");
            //搜索外設(shè)
            [self.myCentralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerOptionShowPowerAlertKey:@YES}];
            break;
        case CBCentralManagerStatePoweredOff:
            BDLog(@"藍(lán)牙關(guān)閉...");
            break;
        default:
            break;
    }
}

#pragma mark 搜索到設(shè)備之后會(huì)調(diào)用代理方法
- (void)centralManager:(CBCentralManager *)central // 中心管理者
 didDiscoverPeripheral:(CBPeripheral *)peripheral // 外設(shè)
     advertisementData:(NSDictionary *)advertisementData // 外設(shè)攜帶的數(shù)據(jù)
                  RSSI:(NSNumber *)RSSI{ // 外設(shè)發(fā)出的藍(lán)牙信號(hào)強(qiáng)度
    BDLog(@"已發(fā)現(xiàn) peripheral: %@ rssi: %@, name: %@ advertisementData: %@", peripheral, RSSI, peripheral.name, advertisementData);
    //這里可以做一些過濾操作
    if ([_myPeripherals containsObject:peripheral]) {
        
    }else
    {
        //找到的設(shè)備必須持有它,否則CBCentralManager中也不會(huì)保存peripheral
        [_myPeripherals addObject:peripheral];
    }
   //將搜索的設(shè)備回調(diào)給控制器的tableview使用,刷新表格
    if (self.perlists) {
        self.perlists(_myPeripherals);
    }
    
}

建立連接

//self.myPeripheral在cell點(diǎn)擊時(shí)的賦值
[self.myCentralManager connectPeripheral:self.myPeripheral options:nil];

一個(gè)主設(shè)備最多能連7個(gè)外設(shè),每個(gè)外設(shè)最多只能給一個(gè)主設(shè)備連接,連接成功、失敗、斷開都會(huì)進(jìn)入到相應(yīng)的代理

#pragma mark 連接外設(shè)成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    BDLog(@"成功外設(shè)連接");
    //設(shè)置外設(shè)的代理
    [self.myPeripheral setDelegate:self];
    //外設(shè)發(fā)現(xiàn)服務(wù),傳nil代表不過濾
    // 這里會(huì)觸發(fā)外設(shè)的代理方法 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    [self.myPeripheral discoverServices:nil];
}

#pragma mark 掉線時(shí)調(diào)用 丟失連接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"藍(lán)牙連接已斷開" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"關(guān)閉", nil];
    [alert show];
    [self closeConnect];
    BDLog(@"丟失連接");
}

#pragma mark 連接外設(shè)失敗
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    BDLog(@"連接外設(shè)失敗%@", error);
}

掃描服務(wù)和特征

#pragma mark 發(fā)現(xiàn)服務(wù)
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    BDLog(@"發(fā)現(xiàn)服務(wù)!");
    for(CBService* s in peripheral.services){
        NSLog(@"%d :服務(wù) UUID: %@(%@)", i, s.UUID.data, s.UUID);
        //掃描每個(gè)service的Characteristics,掃描到后會(huì)進(jìn)入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        [peripheral discoverCharacteristics:nil forService:s];
        [self.nServices addObject:s];
    }
}

#pragma mark 發(fā)現(xiàn)外設(shè)服務(wù)里的特征的時(shí)候調(diào)用的代理方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    for(CBCharacteristic* c in service.characteristics){
        BDLog(@"特征 UUID: %@ (%@)", c.UUID.data, c.UUID);
        
        if (self.toothType == BDBlueToothType_Oximeter) {//血氧儀
            if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]]){
                self.writeCharacteristic = c;
                
                BDLog(@"找到WRITE : %@", c);
            }else if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF4"]]){
                self.readCharacteristic = c;
                
                [self.myPeripheral setNotifyValue:YES forCharacteristic:c];
                [self.myPeripheral readValueForCharacteristic:c];
                NSLog(@"找到READ : %@", c);
            }
        }else if (self.toothType == BDBlueToothType_Hamnatodynamometer){//血壓計(jì)
            if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFE1"]]) {
                BDLog(@"血壓計(jì) %zd - %@",c.properties,c.descriptors);
                self.readCharacteristic = c;
                self.writeCharacteristic = c;
                [self.myPeripheral setNotifyValue:YES forCharacteristic:c];
                [self.myPeripheral readValueForCharacteristic:c];
            }
        }
        
    }
}

與外設(shè)進(jìn)行數(shù)據(jù)交互

#pragma mark 獲取外設(shè)發(fā)來的數(shù)據(jù),不論是read和notify,獲取數(shù)據(jù)都從這個(gè)方法中讀取
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    [peripheral readRSSI];
    
    NSData* data = characteristic.value;
    
    if (!data.length) {
        return;
    }
    
    NSString* value = [self hexadecimalString:data];
    
    if (self.toothType == BDBlueToothType_Oximeter) { //血氧儀
        
        if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF4"]]){
            if (value.length) {
                self.readValue(value);
            }
//            BDLog(@"characteristic : %@, data : %@, value : %@", characteristic, data, value);
        }

    }else if (self.toothType == BDBlueToothType_Hamnatodynamometer){ //血壓計(jì)
        
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFE1"]]) {
            if (value.length) {
                self.readValue(value);
            }
//            BDLog(@"characteristic : %@, data : %@, value : %@", characteristic, data, value);
        }
    }
}

//中心讀取外設(shè)實(shí)時(shí)數(shù)據(jù)
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if(error){
        BDLog(@"Error changing notification state: %@", error.localizedDescription);
    }
    
    if(characteristic.isNotifying){
        [peripheral readValueForCharacteristic:characteristic];
    }else{
        BDLog(@"Notification stopped on %@. Disconnting", characteristic);
        [self.myCentralManager cancelPeripheralConnection:self.myPeripheral];
    }
}

//向peripheral中寫入數(shù)據(jù)
- (void)writeToPeripheral:(NSString *)data{
    if(!_writeCharacteristic){
        BDLog(@"writeCharacteristic is nil!");
        return;
    }
    NSData* value = [self dataWithHexstring:data];
    
    [_myPeripheral writeValue:value forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

//向peripheral中寫入數(shù)據(jù)后的回調(diào)函數(shù)
- (void)peripheral:(CBPeripheral*)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if (error) {
        BDLog(@"error %@",error);
    }
    BDLog(@"write value success : %@", characteristic);
}

用到的私有方法

//將傳入的NSData類型轉(zhuǎn)換成NSString并返回
- (NSString*)hexadecimalString:(NSData *)data{
    NSString* result;
    const unsigned char* dataBuffer = (const unsigned char*)[data bytes];
    if(!dataBuffer){
        return nil;
    }
    NSUInteger dataLength = [data length];
    NSMutableString* hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
    for(int i = 0; i < dataLength; i++){
        [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
    }
    result = [NSString stringWithString:hexString];
    return result;
}

//將傳入的NSString類型轉(zhuǎn)換成NSData并返回
- (NSData*)dataWithHexstring:(NSString *)hexstring{
    NSMutableData* data = [NSMutableData data];
    int idx;
    for(idx = 0; idx + 2 <= hexstring.length; idx += 2){
        NSRange range = NSMakeRange(idx, 2);
        NSString* hexStr = [hexstring substringWithRange:range];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}

相關(guān)的藍(lán)牙文檔

屏幕快照 2017-07-24 上午11.43.21.png

參考文檔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 這里我們具體說明一下中心模式的應(yīng)用場景。主設(shè)備(手機(jī)去掃描連接外設(shè),發(fā)現(xiàn)外設(shè)服務(wù)和屬性,操作服務(wù)和屬性的應(yīng)用。一般...
    丶逝水流年閱讀 2,402評(píng)論 3 4
  • iOS連接外設(shè)的代碼實(shí)現(xiàn)流程 1. 建立中心角色 2. 掃描外設(shè)(discover) 3. 連接外設(shè)(connec...
    UILabelkell閱讀 2,533評(píng)論 2 4
  • 本文主要以藍(lán)牙4.0做介紹,因?yàn)楝F(xiàn)在iOS能用的藍(lán)牙也就是只僅僅4.0的設(shè)備 用的庫就是core bluetoot...
    暮雨飛煙閱讀 910評(píng)論 0 2
  • 1.smarty的增刪改差 2.Smarty緩存 提高網(wǎng)站的運(yùn)行效率,減輕數(shù)據(jù)庫的壓力,針對(duì)的數(shù)據(jù)是非實(shí)時(shí)更新數(shù)據(jù)...
    AnthonyHu閱讀 106評(píng)論 0 0
  • 2016年啦,只是希望通過這篇文章一直延續(xù)時(shí)不時(shí)來簡書寫點(diǎn)小隨筆、日記的開端,希望這個(gè)空間能一直被經(jīng)營下去。...
    惟度閱讀 588評(píng)論 1 2

友情鏈接更多精彩內(nèi)容