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
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM