(轉)iOS藍牙調用的通常流程

文章轉自:http://www.cnblogs.com/ctaodream/archive/2013/07/03/3169962.htmlhtml

1、服務端(也叫周邊設備吧。。腦殘的翻譯)ide

1.實現類必須遵照協議 CBPeripheralManagerDelegateatom

2.須要的主要類有:spa

@property(strong,nonatomic) CBPeripheralManager *peripheraManager;翻譯

@property(strong,nonatomic) CBMutableCharacteristic *customerCharacteristic;3d

 @property (strong,nonatomic) CBMutableService *customerService;代理

3.調用流程代碼中有註釋code

//
//  ViewController.m
//  BlueToothDemo
//
//  Created by PSH_Chen_Tao on 7/3/13.
//  Copyright (c) 2013 wolfman. All rights reserved.
//
 
#import "ViewController.h"
static NSString *const kCharacteristicUUID = @"CCE62C0F-1098-4CD0-ADFA-C8FC7EA2EE90";
 
static NSString *const kServiceUUID = @"50BD367B-6B17-4E81-B6E9-F62016F26E7B";
@interface ViewController ()
 
@end
 
@implementation ViewController
 
 
@synthesize peripheraManager;
@synthesize customerCharacteristic;
@synthesize customerService;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //初始化後會直接調用代理的  - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
     
    peripheraManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
  //  [peripheraManager startAdvertising:nil];
     
}
 
-(void)setUp{
    CBUUID *characteristicUUID = [CBUUID UUIDWithString:kCharacteristicUUID];
    customerCharacteristic = [[CBMutableCharacteristic alloc]initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
    CBUUID *serviceUUID = [CBUUID UUIDWithString:kServiceUUID];
    customerService = [[CBMutableService alloc]initWithType:serviceUUID primary:YES];
    [customerService setCharacteristics:@[characteristicUUID]];
    //添加後就會調用代理的- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
    [peripheraManager addService:customerService];
     
}
 
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
#pragma  mark -- CBPeripheralManagerDelegate
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    switch (peripheral.state) {
            //在這裏判斷藍牙設別的狀態  當開啓了則可調用  setUp方法(自定義)
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@"powered on");
            [self setUp];
            break;
            case CBPeripheralManagerStatePoweredOff:
            NSLog(@"powered off");
            break;
             
        default:
            break;
    }
}
 
 
 
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
    if (error == nil) {
        //添加服務後能夠在此向外界發出通告 調用完這個方法後會調用代理的
        //(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
        [peripheraManager startAdvertising:@{CBAdvertisementDataLocalNameKey : @"Service",CBAdvertisementDataServiceUUIDsKey : [CBUUID UUIDWithString:kServiceUUID]}];
    }
     
}
 
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
    NSLog(@"in peripheralManagerDidStartAdvertisiong:error");
}
@end
View Code

2、客戶端(也叫中心設備吧)htm

1.實現類要遵照協議<CBCentralManagerDelegate,CBPeripheralDelegate>對象

2.主要用到的類有 

@property(strong,nonatomic)CBCentralManager *centralManager;

@property(strong,nonatomic)NSMutableData *mutableData;

@property(strong,nonatomic)CBPeripheral *peripheral;

 3.通常的流程

//
//  ViewController.m
//  BlueToothClient
//
//  Created by PSH_Chen_Tao on 7/3/13.
//  Copyright (c) 2013 wolfman. All rights reserved.
//

#import "ViewController.h"
static NSString *const kCharacteristicUUID = @"CCE62C0F-1098-4CD0-ADFA-C8FC7EA2EE90";

static NSString *const kServiceUUID = @"50BD367B-6B17-4E81-B6E9-F62016F26E7B";
@interface ViewController ()

@end

@implementation ViewController

@synthesize centralManager;
@synthesize mutableData;
@synthesize peripheral;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //初始化後會調用代理CBCentralManagerDelegate 的 - (void)centralManagerDidUpdateState:(CBCentralManager *)central
    centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
   
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma  mark -- CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
            //判斷狀態開始掃瞄周圍設備 第一個參數爲空則會掃瞄全部的可鏈接設備  你能夠
            //指定一個CBUUID對象 從而只掃瞄註冊用指定服務的設備
            //scanForPeripheralsWithServices方法調用完後會調用代理CBCentralManagerDelegate的
            //- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI方法
        case CBCentralManagerStatePoweredOn:
            [centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : YES}];
            
            
            break;
            
        default:
            break;
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if (peripheral) {
        self.peripheral = peripheral;
        //發現設備後便可鏈接該設備 調用完該方法後會調用代理CBCentralManagerDelegate的- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral表示鏈接上了設別
        //若是不能鏈接會調用 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
        [centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey : YES}];
    }
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    NSLog(@"has connected");
    [mutableData setLength:0];
    self.peripheral.delegate = self;
    //此時設備已經鏈接上了  你要作的就是找到該設備上的指定服務 調用完該方法後會調用代理CBPeripheralDelegate(如今開始調用另外一個代理的方法了)的
    //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    [self.peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];
    
}


- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    //此時鏈接發生錯誤
    NSLog(@"connected periphheral failed");
}


#pragma mark -- CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    if (error==nil) {
        //在這個方法中咱們要查找到咱們須要的服務  而後調用discoverCharacteristics方法查找咱們須要的特性
        //該discoverCharacteristics方法調用完後會調用代理CBPeripheralDelegate的
        //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        for (CBService *service in peripheral.services) {
            if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
                [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error==nil) {
        //在這個方法中咱們要找到咱們所需的服務的特性 而後調用setNotifyValue方法告知咱們要監測這個服務特性的狀態變化
        //當setNotifyValue方法調用後調用代理CBPeripheralDelegate的- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        for (CBCharacteristic *characteristic in service.characteristics) {
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
                
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if (error==nil) {
        //調用下面的方法後 會調用到代理的- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        [peripheral readValueForCharacteristic:characteristic];
    }
}


- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
}

@end
View Code
相關文章
相關標籤/搜索