進(jìn)擊藍(lán)牙之 CoreBluetooth 的代碼演示

前言

在之前兩篇文章中匣掸,簡(jiǎn)單的講述了在iOS中使用藍(lán)牙所需要的一些必備條件霸琴,也講述了現(xiàn)在主流的藍(lán)牙開發(fā)庫(kù)CoreBluetooth的一些基礎(chǔ)使用與必備常識(shí)。在這一章朽基,我將代碼附上供即將開發(fā)藍(lán)牙的小伙伴做一個(gè)參考布隔。

藍(lán)牙開發(fā)流程

  • 1.建立中心角色
  • 2.掃描外設(shè)(Discover Peripheral)
  • 3.連接外設(shè)(Connect Peripheral)
  • 4.掃描外設(shè)中的服務(wù)和特征(Discover Services And Characteristics)
  • 4.1 獲取外設(shè)的services
  • 4.2 獲取外設(shè)的Characteristics,獲取characteristics的值,,獲取Characteristics的Descriptor和Descriptor的值
  • 5.利用特征與外設(shè)做數(shù)據(jù)交互(Explore And Interact)
  • 6.訂閱Characteristic的通知
  • 7.斷開連接(Disconnect)

實(shí)現(xiàn)步驟

1.導(dǎo)入CB頭文件,建立主設(shè)備管理類,設(shè)置主設(shè)備代理

#import <CoreBluetooth/CoreBluetooth.h>
@interface ZQBLEController () <CBCentralManagerDelegate>
@property (nonatomic, strong) CBCentralManager *cMgr; /**< 中心管理設(shè)備 */
@end
@implementation ZQBLEController
#pragma mark - 懶加載
// 1.建立中心管理者
- (CBCentralManager *)cMgr
{
    if (!_cMgr) {
        NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
        /*
         設(shè)置主設(shè)備的代理,CBCentralManagerDelegate
         必須實(shí)現(xiàn)的:
         - (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主設(shè)備狀態(tài)改變調(diào)用,在初始化CBCentralManager的適合會(huì)打開設(shè)備稼虎,只有當(dāng)設(shè)備正確打開后才能使用
         其他選擇實(shí)現(xiàn)的委托中比較重要的:
         - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外設(shè)
         - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)成功
         - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設(shè)連接失敗
         - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//斷開外設(shè)
         */
        _cMgr = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; // 線程不傳默認(rèn)是主線程
    }
    return _cMgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"BLE";
    self.view.backgroundColor = [UIColor orangeColor];
    // 初始化
    [self cMgr];
    // 不能在此處掃描,因?yàn)闋顟B(tài)還沒(méi)變?yōu)榇蜷_
    //[self.cMgr scanForPeripheralsWithServices:nil options:nil];
}

2.掃描外設(shè)

  • 掃描的方法防治cMgr成功打開的代理方法中
  • 只有設(shè)備成功打開,才能開始掃描,否則會(huì)報(bào)錯(cuò)
#pragma mark - CBCentralManagerDelegate
// 中心管理者狀態(tài)改變, 在初始化CBCentralManager的時(shí)候會(huì)打開設(shè)備衅檀,只有當(dāng)設(shè)備正確打開后才能使用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@">>>CBCentralManagerStatePoweredOn");
            // 2.開始掃描周圍的外設(shè)
            /*
             第一個(gè)參數(shù)nil就是掃描周圍所有的外設(shè),掃描到外設(shè)后會(huì)進(jìn)入
             - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
             */
            [self.cMgr scanForPeripheralsWithServices:nil options:nil];

            break;
        default:
        break;
    }
}
// 掃描到設(shè)備會(huì)進(jìn)入到此代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);
    // 接下來(lái)連接設(shè)備

3.連接外設(shè)

  • 掃描手環(huán),打印結(jié)果
  • 根據(jù)打印結(jié)果
// 掃描到設(shè)備會(huì)進(jìn)入到此代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);

    // 3.接下來(lái)可以連接設(shè)備
    //如果你沒(méi)有設(shè)備霎俩,可以下載一個(gè)app叫l(wèi)ightbule的app去模擬一個(gè)設(shè)備
    //這里自己去設(shè)置下連接規(guī)則哀军,我設(shè)置的是二維碼掃描到的運(yùn)動(dòng)手環(huán)的設(shè)備號(hào)
    // 判斷設(shè)備號(hào)是否掃描到
    if ([peripheral.name isEqualToString:@"OBand-75"]) {
        /*
         一個(gè)主設(shè)備最多能連7個(gè)外設(shè)沉眶,每個(gè)外設(shè)最多只能給一個(gè)主設(shè)備連接,連接成功,失敗杉适,斷開會(huì)進(jìn)入各自的委托
         - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)成功的委托
         - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設(shè)連接失敗的委托
         - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//斷開外設(shè)的委托
         */
        // 保存外設(shè),否則方法結(jié)束就銷毀
        self.per = peripheral;
        [self.cMgr connectPeripheral:self.per options:nil];
    }else
    {
        // 此處Alert提示未掃描到設(shè)備,重新掃描
#warning noCode
        NSLog(@"沒(méi)掃描到 >>>>>>>>  %s, line = %d", __FUNCTION__, __LINE__);
    }
}
// 外設(shè)連接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    NSLog(@">>>連接到名稱為(%@)的設(shè)備-成功",peripheral.name);
}
// 外設(shè)連接失敗
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}
// 斷開連接(丟失連接)
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}

4.掃描外設(shè)中的服務(wù)和特征

 設(shè)備鏈接成功后,就可以掃描設(shè)備的服務(wù)(services)了,同樣是通過(guò)代理,掃描到結(jié)果后會(huì)觸發(fā)某代理方法.
  注意:此時(shí)CBCentralManagerDelegate已經(jīng)不能滿足需求,需要新的CBPeripheralDelegate來(lái)搞定.
  該協(xié)議中包含了central與peripheral的許多回調(diào)方法
  (eg.:獲取services,獲取characteristics,獲取characteristics的值,獲取characteristics的Descriptor以及Descriptor的值,寫數(shù)據(jù),讀RSSI,用通知的方式訂閱數(shù)據(jù)等等).
  • 4.1 獲取外設(shè)的services
    • 首先設(shè)置外設(shè)的代理,并搜尋services
    • 然后在代理方法peripheral:didDiscoverServices:中遍歷services
// 外設(shè)連接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    NSLog(@">>>連接到名稱為(%@)的設(shè)備-成功",peripheral.name);
    //設(shè)置的peripheral代理CBPeripheralDelegate
    //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
    [peripheral setDelegate:self];

    //掃描外設(shè)Services谎倔,成功后會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    [peripheral discoverServices:nil];
    /*
     Discovers the specified services of the peripheral.
     An array of CBUUID objects that you are interested in. Here, each CBUUID object represents a UUID that identifies the type of service you want to discover.
     */
}

#pragma mark - CBPeripheralDelegate
// 發(fā)現(xiàn)外設(shè)的service
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error)
    {
        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }

    for (CBService *service in peripheral.services) {
        NSLog(@"service.UUID = %@", service.UUID);
        //掃描每個(gè)service的Characteristics,掃描到后會(huì)進(jìn)入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
  • 4.2 獲取外設(shè)的characteris,獲取Characteristics的值,獲取Characteristics的Descriptor以及Descriptor的值
// 外設(shè)發(fā)現(xiàn)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:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
    }

#warning noCodeFor 優(yōu)化,分開寫是為了讓大家看注釋清晰,并不符合編碼規(guī)范

    //獲取Characteristic的值猿推,讀到數(shù)據(jù)會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral readValueForCharacteristic:characteristic]; // 外設(shè)讀取特征的值
    }

    //搜索Characteristic的Descriptors片习,讀到數(shù)據(jù)會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外設(shè)發(fā)現(xiàn)特征的描述
    }
}

// 獲取characteristic的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    //打印出characteristic的UUID和值
    //!注意,value的類型是NSData蹬叭,具體開發(fā)時(shí)藕咏,會(huì)根據(jù)外設(shè)協(xié)議制定的方式去解析數(shù)據(jù)
    NSLog(@"%s, line = %d, characteristic.UUID:%@  value:%@", __FUNCTION__, __LINE__, characteristic.UUID, characteristic.value);
}

// 獲取Characteristics的 descriptor的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
{
    //打印出DescriptorsUUID 和value
    //這個(gè)descriptor都是對(duì)于characteristic的描述,一般都是字符串秽五,所以這里我們轉(zhuǎn)換成字符串去解析
    NSLog(@"%s, line = %d, descriptor.UUID:%@ value:%@", __FUNCTION__, __LINE__, descriptor.UUID, descriptor.value);
}

// 發(fā)現(xiàn)特征Characteristics的描述Descriptor
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    for (CBDescriptor *descriptor in characteristic.descriptors) {
        NSLog(@"descriptor.UUID:%@",descriptor.UUID);
    }
}

5.寫數(shù)據(jù)到特征中

  • 自定義方法,為了看的更清楚,沒(méi)別的意思
  • 需要注意的是特征的屬性是否支持寫數(shù)據(jù)
- (void)zq_peripheral:(CBPeripheral *)peripheral writeData:(NSData *)data forCharacteristic:(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
    };
     打印出特征的權(quán)限(characteristic.properties),可以看到有很多種,這是一個(gè)NS_OPTIONS的枚舉,可以是多個(gè)值
     常見的又read,write,noitfy,indicate.知道這幾個(gè)基本夠用了,前倆是讀寫權(quán)限,后倆都是通知,倆不同的通知方式
     */
     NSLog(@"%s, line = %d, char.pro = %lu", __FUNCTION__, __LINE__, (unsigned long)characteristic.properties);
     
    // 此時(shí)由于枚舉屬性是NS_OPTIONS,所以一個(gè)枚舉可能對(duì)應(yīng)多個(gè)類型,所以判斷不能用 = ,而應(yīng)該用包含&
    if (characteristic.properties & CBCharacteristicPropertyWrite) {
        // 核心代碼在這里
        [peripheral writeValue:data // 寫入的數(shù)據(jù)
             forCharacteristic:characteristic // 寫給哪個(gè)特征
                          type:CBCharacteristicWriteWithResponse];// 通過(guò)此響應(yīng)記錄是否成功寫入
    }

}

6.訂閱特征的通知

  • 實(shí)際核心代碼是一個(gè)方法
  • 一般這兩個(gè)方法要根據(jù)產(chǎn)品需求來(lái)確定寫在何處

// 設(shè)置通知
- (void)zq_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
    // 外設(shè)為特征訂閱通知 數(shù)據(jù)會(huì)進(jìn)入 peripheral:didUpdateValueForCharacteristic:error:方法
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
// 取消通知
- (void)zq_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
    // 外設(shè)取消訂閱通知 數(shù)據(jù)會(huì)進(jìn)入 peripheral:didUpdateValueForCharacteristic:error:方法
    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
}

7.斷開連接

// 7.斷開連接
- (void)zq_cMgr:(CBCentralManager *)cMgr stopScanAndDisConnectWithPeripheral:(CBPeripheral *)peripheral
{
    // 停止掃描
    [cMgr stopScan];
    // 斷開連接
    [cMgr cancelPeripheralConnection:peripheral];
}

優(yōu)秀的第三方藍(lán)牙庫(kù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末孽查,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子坦喘,更是在濱河造成了極大的恐慌卦碾,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,496評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件起宽,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡济榨,警方通過(guò)查閱死者的電腦和手機(jī)坯沪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,187評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)擒滑,“玉大人腐晾,你說(shuō)我怎么就攤上這事∝ひ唬” “怎么了藻糖?”我有些...
    開封第一講書人閱讀 157,091評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)库车。 經(jīng)常有香客問(wèn)我巨柒,道長(zhǎng),這世上最難降的妖魔是什么柠衍? 我笑而不...
    開封第一講書人閱讀 56,458評(píng)論 1 283
  • 正文 為了忘掉前任洋满,我火速辦了婚禮,結(jié)果婚禮上珍坊,老公的妹妹穿的比我還像新娘牺勾。我一直安慰自己,他們只是感情好阵漏,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,542評(píng)論 6 385
  • 文/花漫 我一把揭開白布驻民。 她就那樣靜靜地躺著翻具,像睡著了一般。 火紅的嫁衣襯著肌膚如雪回还。 梳的紋絲不亂的頭發(fā)上裆泳,一...
    開封第一講書人閱讀 49,802評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音懦趋,去河邊找鬼晾虑。 笑死,一個(gè)胖子當(dāng)著我的面吹牛仅叫,可吹牛的內(nèi)容都是我干的帜篇。 我是一名探鬼主播,決...
    沈念sama閱讀 38,945評(píng)論 3 407
  • 文/蒼蘭香墨 我猛地睜開眼诫咱,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼笙隙!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起坎缭,我...
    開封第一講書人閱讀 37,709評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤竟痰,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后掏呼,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體坏快,經(jīng)...
    沈念sama閱讀 44,158評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,502評(píng)論 2 327
  • 正文 我和宋清朗相戀三年憎夷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了莽鸿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,637評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡拾给,死狀恐怖祥得,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蒋得,我是刑警寧澤级及,帶...
    沈念sama閱讀 34,300評(píng)論 4 329
  • 正文 年R本政府宣布,位于F島的核電站额衙,受9級(jí)特大地震影響饮焦,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜窍侧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,911評(píng)論 3 313
  • 文/蒙蒙 一追驴、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧疏之,春花似錦殿雪、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,744評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)爸业。三九已至,卻和暖如春亏镰,著一層夾襖步出監(jiān)牢的瞬間扯旷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,982評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工索抓, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留钧忽,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,344評(píng)論 2 360
  • 正文 我出身青樓逼肯,卻偏偏與公主長(zhǎng)得像耸黑,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子篮幢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,500評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容