ios藍牙框架CoreBluetooth使用

相關基礎知識介紹

藍牙常見名稱和縮寫

  • BLE:(Bluetooth low energy)藍牙4.0設備因為低耗電,也叫BLE
  • peripheral,central:外設和中心設備,發起鏈接的是central(一般是指手機),被鏈接的設備是peripheral(運動手環)
  • service and characteristic:(服務和特征)每個設備會提供服務和特征,類似于服務端的API,但是結構不同.每個設備會有很多服務,每個服務中包含很多字段,這些字段的權限一般分為讀(read),寫(write),通知(notify)幾種,就是我們連接設備后具體需要操作的內容
  • Description:每個characteristic可以對應一個或者多個Description用于描述characteristic的信息或屬性(eg.范圍,計量單位)

藍牙基礎知識

  • CoreBluetooth框架的核心其實是倆東西:peripheral和central,對應他們分別有一組相關的API和類


  • 這兩組api分別對應不同的業務常見:左側叫中心模式,就是以你的app作為中心,連接其他的外設的場景;而右側稱為外設模式,使用手機作為外設連接其他中心設備操作的場景

  • 服務和特征(service and characteristic)

    • 每個設備都會有1個or多個服務
    • 每個服務里都會有1個or多個特征
    • 特征就是具體鍵值對,提供數據的地方
    • 每個特征屬性分為:讀,寫,通知等等
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
};
  • 外設,服務,特征的關系


BLE中心模式流程

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

BLE外設模式流程

  • 1.啟動一個Peripheral管理對象
  • 2.本地peripheral設置服務,特征,描述,權限等等
  • 3.peripheral發送廣告
  • 4.設置處理訂閱,取消訂閱,讀characteristic,寫characteristic的代理方法

藍牙設備的狀態

  • 1.待機狀態(standby):設備沒有傳輸和發送數據,并且沒有連接到任何外設
  • 2.廣播狀態(Advertiser):周期性廣播狀態
  • 3.掃描狀態(Scanner):主動搜索正在廣播的設備
  • 4.發起鏈接狀態(Initiator):主動向掃描設備發起連接
  • 5.主設備(Master):作為主設備連接到其它設備.
  • 6.從設備(Slave):作為從設備鏈接到其它設備

藍牙設備的五種工作狀態

  • 準備(Standby)
  • 廣播(Advertising)
  • 監聽掃描(Scanning)
  • 發起連接(Initiating)
  • 已連接(Connected)

BLE中心模式流程-coding

BLE中心模式流程

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

準備環境

  • 1.Xcode
  • 2.手機
  • 3.外設(手機+LightBlue)

實現步驟

1.導入CB頭文件,建立主設備管理類,設置主設備代理

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

2.掃描外設

  • 掃描的方法防治cMgr成功打開的代理方法中
  • 只有設備成功打開,才能開始掃描,否則會報錯
#pragma mark - CBCentralManagerDelegate
// 中心管理者狀態改變, 在初始化CBCentralManager的時候會打開設備,只有當設備正確打開后才能使用
- (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.開始掃描周圍的外設
            /*
             第一個參數nil就是掃描周圍所有的外設,掃描到外設后會進入
             - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
             */
            [self.cMgr scanForPeripheralsWithServices:nil options:nil];

            break;
        default:
        break;
    }
}
// 掃描到設備會進入到此代理方法
- (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.連接外設

  • 掃描手環,打印結果


  • 根據打印結果
// 掃描到設備會進入到此代理方法
- (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.接下來可以連接設備
    //如果你沒有設備,可以下載一個app叫lightbule的app去模擬一個設備
    //這里自己去設置下連接規則,我設置的是二維碼掃描到的運動手環的設備號
    // 判斷設備號是否掃描到
    if ([peripheral.name isEqualToString:@"OBand-75"]) {
        /*
         一個主設備最多能連7個外設,每個外設最多只能給一個主設備連接,連接成功,失敗,斷開會進入各自的委托
         - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設成功的委托
         - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設連接失敗的委托
         - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//斷開外設的委托
         */
        // 保存外設,否則方法結束就銷毀
        self.per = peripheral;
        [self.cMgr connectPeripheral:self.per options:nil];
    }else
    {
        // 此處Alert提示未掃描到設備,重新掃描
#warning noCode
        NSLog(@"沒掃描到 >>>>>>>>  %s, line = %d", __FUNCTION__, __LINE__);
    }
}
// 外設連接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    NSLog(@">>>連接到名稱為(%@)的設備-成功",peripheral.name);
}
// 外設連接失敗
- (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.掃描外設中的服務和特征

  設備鏈接成功后,就可以掃描設備的服務(services)了,同樣是通過代理,掃描到結果后會觸發某代理方法.
  注意:此時CBCentralManagerDelegate已經不能滿足需求,需要新的CBPeripheralDelegate來搞定.
  該協議中包含了central與peripheral的許多回調方法
  (eg.:獲取services,獲取characteristics,獲取characteristics的值,獲取characteristics的Descriptor以及Descriptor的值,寫數據,讀RSSI,用通知的方式訂閱數據等等).

  • 4.1 獲取外設的services
    • 首先設置外設的代理,并搜尋services
    • 然后在代理方法peripheral:didDiscoverServices:中遍歷services
// 外設連接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    NSLog(@">>>連接到名稱為(%@)的設備-成功",peripheral.name);
    //設置的peripheral代理CBPeripheralDelegate
    //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
    [peripheral setDelegate:self];

    //掃描外設Services,成功后會進入方法:-(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
// 發現外設的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);
        //掃描每個service的Characteristics,掃描到后會進入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
  • 4.2 獲取外設的characteris,獲取Characteristics的值,獲取Characteristics的Descriptor以及Descriptor的值
// 外設發現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 優化,分開寫是為了讓大家看注釋清晰,并不符合編碼規范
    //獲取Characteristic的值,讀到數據會進入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral readValueForCharacteristic:characteristic]; // 外設讀取特征的值
    }

    //搜索Characteristic的Descriptors,讀到數據會進入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外設發現特征的描述
    }
}

// 獲取characteristic的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    //打印出characteristic的UUID和值
    //!注意,value的類型是NSData,具體開發時,會根據外設協議制定的方式去解析數據
    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
    //這個descriptor都是對于characteristic的描述,一般都是字符串,所以這里我們轉換成字符串去解析
    NSLog(@"%s, line = %d, descriptor.UUID:%@ value:%@", __FUNCTION__, __LINE__, descriptor.UUID, descriptor.value);
}
// 發現特征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.寫數據到特征中

// 5.將數據寫入特征(自定義方法,為了看的更清楚,沒別的意思)
- (void)yf_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
    };
     打印出特征的權限(characteristic.properties),可以看到有很多種,這是一個NS_OPTIONS的枚舉,可以是多個值
     常見的又read,write,noitfy,indicate.知道這幾個基本夠用了,前倆是讀寫權限,后倆都是通知,倆不同的通知方式
     */
    NSLog(@"%s, line = %d, characteristic.properties:%d", __FUNCTION__, __LINE__, characteristic.properties);

    // 只有特征的properties中有寫的屬性時候,才寫
    if (characteristic.properties & CBCharacteristicPropertyWrite) {
        // 這句才是正宗的核心代碼
        [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }
}

6.訂閱特征的通知

// 設置通知
- (void)yf_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
    // 設置通知, 數據會進入 peripheral:didUpdateValueForCharacteristic:error:方法
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
// 取消通知
- (void)yf_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
}

7.斷開連接

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

BLE-periphral外設模式流程

之前在基礎知識介紹過BLE應用的兩種流程,如圖:

  • central模式用的都是左邊的類,而peripheral模式用的是右邊的類

peripheral模式的流程

  • 1.引入CoreBluetooth框架,初始化peripheralManager
  • 2.設置peripheralManager中的內容
  • 3.開啟廣播advertising
  • 4.對central的操作進行響應
    • 4.1 讀characteristics請求
    • 4.2 寫characteristics請求
    • 4.4 訂閱和取消訂閱characteristics

具體操作步驟

1.引入CoreBluetooth框架,初始化peripheralManager

#import <CoreBluetooth/CoreBluetooth.h>
@interface XMGBLEPeripheralViewController () <CBPeripheralManagerDelegate>
@property (nonatomic, strong) CBPeripheralManager *pMgr; /**< 外設管理者 */
@end

@implementation XMGBLEPeripheralViewController
// 懶加載
- (CBPeripheralManager *)pMgr
{
    if (!_pMgr) {
        _pMgr = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
    }
    return _pMgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 調用get方法初始化,初始化后CBPeripheralManager狀態改變會調用代理方法peripheralManagerDidUpdateState:
    // 模擬器永遠也不會是CBPeripheralManagerStatePoweredOn狀態
    [self pMgr];
}

2.設置peripheralManager中的內容

  • 創建characteristics及其description,
  • 創建service,把characteristics添加到service中,
  • 再把service添加到peripheralManager中
#pragma mark - CBPeripheralManagerDelegate
// CBPeripheralManager初始化后會觸發的方法
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
    if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
        // 提示設備成功打開
        [SVProgressHUD showSuccessWithStatus:@"xmg設備打開成功~"];
        // 配置各種服務入CBPeripheralManager
        [self yf_setupPMgr];
    }else
    {
        // 提示設備打開失敗
        [SVProgressHUD showErrorWithStatus:@"失敗!"];
    }
}

#pragma mark - 私有方法
- (void)yf_setupPMgr
{
    // 特征描述的UUID
    CBUUID *characteristicUserDescriptionUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
    // 特征的通知UUID
    CBUUID *notifyCharacteristicUUID = [CBUUID UUIDWithString:notiyCharacteristicStrUUID];
    // 特征的讀寫UUID
    CBUUID *readwriteCharacteristicUUID = [CBUUID UUIDWithString:readwriteCharacteristicStrUUID];
    // 特征的只讀UUID
    CBUUID *readCharacteristicUUID = [CBUUID UUIDWithString:readwriteCharacteristicStrUUID];
    CBUUID *ser1UUID = [CBUUID UUIDWithString:Service1StrUUID];
    CBUUID *ser2UUID = [CBUUID UUIDWithString:Service2StrUUID];


    // 初始化一個特征的描述
    CBMutableDescriptor *des1 = [[CBMutableDescriptor alloc] initWithType:characteristicUserDescriptionUUID value:@"xmgDes1"];

    // 可通知的特征
    CBMutableCharacteristic *notifyCharacteristic = [[CBMutableCharacteristic alloc] initWithType:notifyCharacteristicUUID // UUID
                                                                                       properties:CBCharacteristicPropertyNotify // 枚舉:通知
                                                                                            value:nil // 數據先不傳
                                                                                      permissions:CBAttributePermissionsReadable]; // 枚舉:可讀
    // 可讀寫的特征
    CBMutableCharacteristic *readwriteChar = [[CBMutableCharacteristic alloc] initWithType:readwriteCharacteristicUUID
                                                                                properties:CBCharacteristicPropertyRead | CBCharacteristicPropertyWrite
                                                                                     value:nil
                                                                               permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
    [readwriteChar setDescriptors:@[des1]]; // 設置特征的描述

    // 只讀特征
    CBMutableCharacteristic *readChar = [[CBMutableCharacteristic alloc] initWithType:readCharacteristicUUID
                                                                           properties:CBCharacteristicPropertyRead
                                                                                value:nil
                                                                          permissions:CBAttributePermissionsReadable];

    // 初始化服務1
    CBMutableService *ser1 = [[CBMutableService alloc] initWithType:ser1UUID primary:YES];
    // 為服務設置倆特征(通知, 帶描述的讀寫)
    [ser1 setCharacteristics:@[notifyCharacteristic, readwriteChar]];

    // 初始化服務2,并且添加一個只讀特征
    CBMutableService *ser2 = [[CBMutableService alloc] initWithType:ser2UUID primary:YES];
    ser2.characteristics = @[readChar];

    // 添加服務進外設管理者
    // 添加操作會觸發代理方法peripheralManager:didAddService:error:
    [self.pMgr addService:ser1];
    [self.pMgr addService:ser2];
}

3.開啟廣播

// 添加服務進CBPeripheralManager時會觸發的方法
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
{
    // 由于添加了兩次ser,所以方法會調用兩次
    static int i = 0;
    if (!error) {
        i++;
    }

    // 當第二次進入方法時候,代表兩個服務添加完畢,此時要用到2,由于沒有擴展性,所以新增了可變數組,記錄添加的服務數量
    if (i == self.servieces.count) {
        // 廣播內容
        NSDictionary *advertDict = @{CBAdvertisementDataServiceUUIDsKey: [self.servieces valueForKeyPath:@"UUID"],
                                     CBAdvertisementDataLocalNameKey:LocalNameKey};
        // 發出廣播,會觸發peripheralManagerDidStartAdvertising:error:
        [peripheral startAdvertising:advertDict];
    }
}
// 開始廣播觸發的代理
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
{

}

>>>>>>>>分割線>>>>下面是修改的地方

@property (nonatomic, strong) NSMutableArray *servieces; /**< 服務可變數組 */
// 自定義服務
- (NSMutableArray *)servieces
{
    if (!_servieces) {
        _servieces = [NSMutableArray array];
    }
    return _servieces;
}
#pragma mark - 私有方法
- (void)yf_setupPMgr
{
    ...

    // 初始化服務1
    CBMutableService *ser1 = [[CBMutableService alloc] initWithType:ser1UUID primary:YES];
    // 為服務設置倆特征(通知, 帶描述的讀寫)
    [ser1 setCharacteristics:@[notifyCharacteristic, readwriteChar]];
    [self.servieces addObject:ser1];

    // 初始化服務2,并且添加一個只讀特征
    CBMutableService *ser2 = [[CBMutableService alloc] initWithType:ser2UUID primary:YES];
    ser2.characteristics = @[readChar];
    [self.servieces addObject:ser2];

    // 添加服務進外設管理者
    // 添加操作會觸發代理方法peripheralManager:didAddService:error:
    if (self.servieces.count) {
        for (CBMutableService *ser in self.servieces) {
            [self.pMgr addService:ser];
        }
    }
}

4.對central的操作做出響應

  • 4.1 讀characteristics請求
  • 4.2 寫characteristics請求
  • 4.3 訂閱和取消訂閱characteristics
// 外設收到讀的請求,然后讀特征的值賦值給request
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    // 判斷是否可讀
    if (request.characteristic.properties & CBCharacteristicPropertyRead) {
        NSData *data = request.characteristic.value;

        request.value = data;
        // 對請求成功做出響應
        [self.pMgr respondToRequest:request withResult:CBATTErrorSuccess];
    }else
    {
        [self.pMgr respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
    }
}
// 外設收到寫的請求,然后讀request的值,寫給特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests
{
    NSLog(@"%s, line = %d, requests = %@", __FUNCTION__, __LINE__, requests);
    CBATTRequest *request = requests.firstObject;
    if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
        NSData *data = request.value;
        // 此處賦值要轉類型,否則報錯
        CBMutableCharacteristic *mChar = (CBMutableCharacteristic *)request.characteristic;
        mChar.value = data;
        // 對請求成功做出響應
        [self.pMgr respondToRequest:request withResult:CBATTErrorSuccess];
    }else
    {
        [self.pMgr respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
    }
}


// 與CBCentral的交互
// 訂閱特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic
{
    NSLog(@"%s, line = %d, 訂閱了%@的數據", __FUNCTION__, __LINE__, characteristic.UUID);
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0
                                                      target:self
                                                    selector:@selector(yf_sendData:)
                                                    userInfo:characteristic
                                                     repeats:YES];

    self.timer = timer;

    /* 另一種方法 */
//    NSTimer *testTimer = [NSTimer timerWithTimeInterval:2.0
//                                                 target:self
//                                               selector:@selector(yf_sendData:)
//                                               userInfo:characteristic
//                                                repeats:YES];
//    [[NSRunLoop currentRunLoop] addTimer:testTimer forMode:NSDefaultRunLoopMode];

}
// 取消訂閱特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic
{
    NSLog(@"%s, line = %d, 取消訂閱了%@的數據", __FUNCTION__, __LINE__, characteristic.UUID);
    [self.timer invalidate];
    self.timer = nil;
}

- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}

// 計時器每隔兩秒調用的方法
- (BOOL)yf_sendData:(NSTimer *)timer
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yy:MM:dd:HH:mm:ss";

    NSString *now = [dateFormatter stringFromDate:[NSDate date]];
    NSLog(@"now = %@", now);

    // 執行回應central通知數據
    return  [self.pMgr updateValue:[now dataUsingEncoding:NSUTF8StringEncoding]
         forCharacteristic:timer.userInfo
      onSubscribedCentrals:nil];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容