[蓝牙]iOS蓝牙调用的一般流程

一、服务端(也叫周边设备吧。。脑残的翻译)

1.实现类必须遵守协议 CBPeripheralManagerDelegate

2.需要的主要类有:

@property ( strong , nonatomic ) CBPeripheralManager *peripheraManager;

@property(strong,nonatomic) CBMutableCharacteristic *customerCharacteristic;

 @property (strong,nonatomic) CBMutableService *customerService;

3.调用流程代码中有注释

//
//  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

二、客户端(也叫中心设备吧)

1.实现类要遵守协议 <CBCentralManagerDelegate,CBPeripheralDelegate>

2.主要用到的类有 

@property ( strong , nonatomic ) CBCentralManager *centralManager;

@property ( strong , nonatomic ) NSMutableData *mutableData;

@property ( strong , nonatomic ) CBPeripheral *peripheral;

 3.一般的流程

  1 //
  2 // ViewController.m
  3 // BlueToothClient
  4 //
  5 // Created by PSH_Chen_Tao on 7/3/13.
  6 // Copyright (c) 2013 wolfman. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 static NSString *const kCharacteristicUUID = @"CCE62C0F-1098-4CD0-ADFA-C8FC7EA2EE90";
 11 
 12 static NSString *const kServiceUUID = @"50BD367B-6B17-4E81-B6E9-F62016F26E7B";
 13 @interface ViewController ()
 14 
 15 @end
 16 
 17 @implementation ViewController
 18 
 19 @synthesize centralManager;
 20 @synthesize mutableData;
 21 @synthesize peripheral;
 22 
 23 - (void)viewDidLoad
 24 {
 25     [super viewDidLoad];
 26     // Do any additional setup after loading the view, typically from a nib.
 27     //初始化后会调用代理CBCentralManagerDelegate 的 - (void)centralManagerDidUpdateState:(CBCentralManager *)central
 28     centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
 29    
 30 }
 31 
 32 - (void)didReceiveMemoryWarning
 33 {
 34     [super didReceiveMemoryWarning];
 35     // Dispose of any resources that can be recreated.
 36 }
 37 
 38 #pragma  mark -- CBCentralManagerDelegate
 39 - (void)centralManagerDidUpdateState:(CBCentralManager *)central{
 40     switch (central.state) {
 41             //判断状态开始扫瞄周围设备 第一个参数为空则会扫瞄所有的可连接设备 你可以
 42             //指定一个CBUUID对象 从而只扫瞄注册用指定服务的设备
 43             //scanForPeripheralsWithServices方法调用完后会调用代理CBCentralManagerDelegate的
 44             //- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI方法
 45         case CBCentralManagerStatePoweredOn:
 46             [centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : YES}];
 47             
 48             
 49             break;
 50             
 51         default:
 52             break;
 53     }
 54 }
 55 
 56 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
 57     if (peripheral) {
 58         self.peripheral = peripheral;
 59         //发现设备后即可连接该设备 调用完该方法后会调用代理CBCentralManagerDelegate的- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral表示连接上了设别
 60         //如果不能连接会调用 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
 61         [centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey : YES}];
 62     }
 63 }
 64 
 65 - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
 66     NSLog(@"has connected");
 67     [mutableData setLength:0];
 68     self.peripheral.delegate = self;
 69     //此时设备已经连接上了 你要做的就是找到该设备上的指定服务 调用完该方法后会调用代理CBPeripheralDelegate(现在开始调用另一个代理的方法了)的
 70     //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
 71     [self.peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];
 72     
 73 }
 74 
 75 
 76 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
 77     //此时连接发生错误
 78     NSLog(@"connected periphheral failed");
 79 }
 80 
 81 
 82 #pragma mark -- CBPeripheralDelegate
 83 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
 84     if (error==nil) {
 85         //在这个方法中我们要查找到我们需要的服务 然后调用discoverCharacteristics方法查找我们需要的特性
 86         //该discoverCharacteristics方法调用完后会调用代理CBPeripheralDelegate的
 87         //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
 88         for (CBService *service in peripheral.services) {
 89             if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
 90                 [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
 91             }
 92         }
 93     }
 94 }
 95 
 96 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
 97     if (error==nil) {
 98         //在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
 99         //当setNotifyValue方法调用后调用代理CBPeripheralDelegate的- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
100         for (CBCharacteristic *characteristic in service.characteristics) {
101             if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
102                 
103                 [peripheral setNotifyValue:YES forCharacteristic:characteristic];
104             }
105         }
106     }
107 }
108 
109 - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
110     if (error==nil) {
111         //调用下面的方法后 会调用到代理的- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
112         [peripheral readValueForCharacteristic:characteristic];
113     }
114 }
115 
116 
117 - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
118     
119 }
120 
121 @end

你可能感兴趣的:([蓝牙]iOS蓝牙调用的一般流程)