你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發基礎 >> iOS藍牙開發(三):App作為外設被連接的實現

iOS藍牙開發(三):App作為外設被連接的實現

編輯:IOS開發基礎

在上一節說了app作為central連接peripheral的情況,這一節介紹如何使用app發布一個peripheral,給其他的central連接。

CoreBluetoothFramework.jpeg

還是這張圖,central模式用的都是左邊的類,而peripheral模式用的是右邊的類

peripheral模式的流程

1. 打開peripheralManager,設置peripheralManager的委托

2. 創建characteristics,characteristics的description 創建service,把characteristics添加到service中,再把service添加到peripheralManager中

3. 開啟廣播advertising

4. 對central的操作進行響應

    - 4.1 讀characteristics請求

    - 4.2 寫characteristics請求

    - 4.4 訂閱和取消訂閱characteristics

##准備環境

  1. Xcode

  2. 開發證書和手機(藍牙程序需要使用使用真機調試,使用模擬器也可以調試,但是方法很蛋疼,我會放在最後說),如果不行可以使用osx程序調試

  3. 藍牙外設

##實現步驟

1.打開peripheralManager,設置peripheralManager的委托

設置當前ViewController實現CBPeripheralManagerDelegate委托

@interface BePeripheralViewController : UIViewController

初始化peripheralManager

/*
和CBCentralManager類似,藍牙設備打開需要一定時間,打開成功後會進入委托方法
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral;
模擬器永遠也不會得CBPeripheralManagerStatePoweredOn狀態
*/
peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];

2.創建characteristics,characteristics的description ,創建service,把characteristics添加到service中,再把service添加到peripheralManager中。

在委托方法 - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral中,當peripheral成功打開後,才可以配置service和characteristics。 這裡創建的service和chara對象是CBMutableCharacteristic和CBMutableService。他們的區別就像NSArray和NSMutableArray區別類似。 我們先創建characteristics和description,description是characteristics的描述,描述分很多種, 這裡不細說了,常用的就是CBUUIDCharacteristicUserDescriptionString。

//peripheralManager狀態改變
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    switch (peripheral.state) {
            //在這裡判斷藍牙設別的狀態  當開啟了則可調用  setUp方法(自定義)
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@"powered on");
            [info setText:[NSString stringWithFormat:@"設備名%@已經打開,可以使用center進行連接",LocalNameKey]];
            [self setUp];
            break;
        case CBPeripheralManagerStatePoweredOff:
            NSLog(@"powered off");
            [info setText:@"powered off"];
            break;

        default:
            break;
    }
}

//配置bluetooch的
 -(void)setUp{

        //characteristics字段描述
        CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];

        /*
         可以通知的Characteristic
         properties:CBCharacteristicPropertyNotify
         permissions CBAttributePermissionsReadable
         */
        CBMutableCharacteristic *notiyCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:notiyCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];

        /*
         可讀寫的characteristics
         properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead
         permissions CBAttributePermissionsReadable | CBAttributePermissionsWriteable
         */
        CBMutableCharacteristic *readwriteCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readwriteCharacteristicUUID] properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
        //設置description
        CBMutableDescriptor *readwriteCharacteristicDescription1 = [[CBMutableDescriptor alloc]initWithType: CBUUIDCharacteristicUserDescriptionStringUUID value:@"name"];
        [readwriteCharacteristic setDescriptors:@[readwriteCharacteristicDescription1]];

        
        /*
         只讀的Characteristic
         properties:CBCharacteristicPropertyRead
         permissions CBAttributePermissionsReadable
         */
        CBMutableCharacteristic *readCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readCharacteristicUUID] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];

        
        //service1初始化並加入兩個characteristics
        CBMutableService *service1 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID1] primary:YES];
        [service1 setCharacteristics:@[notiyCharacteristic,readwriteCharacteristic]];

        //service2初始化並加入一個characteristics
        CBMutableService *service2 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID2] primary:YES];
        [service2 setCharacteristics:@[readCharacteristic]];

        //添加後就會調用代理的- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
        [peripheralManager addService:service1];
        [peripheralManager addService:service2];
 }

3.開啟廣播advertising

//perihpheral添加了service
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
    if (error == nil) {
        serviceNum++;
    }

    //因為我們添加了2個服務,所以想兩次都添加完成後才去發送廣播
    if (serviceNum==2) {
        //添加服務後可以在此向外界發出通告 調用完這個方法後會調用代理的
        //(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
        [peripheralManager startAdvertising:@{
                                              CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:ServiceUUID1],[CBUUID UUIDWithString:ServiceUUID2]],
                                              CBAdvertisementDataLocalNameKey : LocalNameKey
                                             }
         ];
    }
}

//peripheral開始發送advertising
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
    NSLog(@"in peripheralManagerDidStartAdvertisiong");
}

4. 對central的操作進行響應

- 4.1 讀characteristics請求

- 4.2 寫characteristics請求

- 4.3 訂閱和取消訂閱characteristics

//訂閱characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
    NSLog(@"訂閱了 %@的數據",characteristic.UUID);
    //每秒執行一次給主設備發送一個當前時間的秒數
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendData:) userInfo:characteristic  repeats:YES];
}

//取消訂閱characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{
    NSLog(@"取消訂閱 %@的數據",characteristic.UUID);
    //取消回應
    [timer invalidate];
}

//發送數據,發送當前時間的秒數
-(BOOL)sendData:(NSTimer *)t {
    CBMutableCharacteristic *characteristic = t.userInfo;
    NSDateFormatter *dft = [[NSDateFormatter alloc]init];
    [dft setDateFormat:@"ss"];
    NSLog(@"%@",[dft stringFromDate:[NSDate date]]);

    //執行回應Central通知數據
    return  [peripheralManager updateValue:[[dft stringFromDate:[NSDate date]] dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:(CBMutableCharacteristic *)characteristic onSubscribedCentrals:nil];
}


//讀characteristics請求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{
    NSLog(@"didReceiveReadRequest");
    //判斷是否有讀數據的權限
    if (request.characteristic.properties & CBCharacteristicPropertyRead) {
        NSData *data = request.characteristic.value;
        [request setValue:data];
        //對請求作出成功響應
        [peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
    }else{
        [peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
    }
}


//寫characteristics請求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{
    NSLog(@"didReceiveWriteRequests");
    CBATTRequest *request = requests[0];

    //判斷是否有寫數據的權限
    if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
        //需要轉換成CBMutableCharacteristic對象才能進行寫值
        CBMutableCharacteristic *c =(CBMutableCharacteristic *)request.characteristic;
        c.value = request.value;
        [peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
    }else{
        [peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
    }
}

代碼下載:我博客中大部分示例代碼都上傳到了github,地址是:https://github.com/coolnameismy/demo,點擊跳轉代碼下載地址

本文代碼存放目錄是BleDemo

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved