IOS藍牙4.0使用心得

文章出處http://blog.csdn.net/xgcyangguang


之前沒有寫東西的習慣,今天突然來了靈感,想把自己做過的東西記錄下來,一是方便自己今後查閱,同時也分享出來,給其它需要的人一個參考


所做的東西是通過手機/pad與藍牙4.0的設備進行連接,之後設備上按對應的按鍵我們會收到對應的數值。首先需要和做藍牙4.0的同事溝通好通信協議,具體的數據解析部分就不過多贅述了,主要寫一下藍牙接收數據的部分


1.和做藍牙的同事溝通好設備的UUID以及特點,可以把他們寫成宏

#define TRANSFER_SERVICE_UUID           @"0000fff0-0000-1000-8000-00805f9b34fb"
#define TRANSFER_CHARACTERISTIC_UUID    @"0000fff7-0000-1000-8000-00805f9b34fb"

2.在.H文件中導入兩個頭文件,並在接口中實現兩個協議


#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "UUID.h"

//需要實現協議
@interface ViewController () < CBCentralManagerDelegate, CBPeripheralDelegate>
{

}

3.創建兩個藍牙設備屬性,一個相當於主機,一個相當於外設從機
#pragma mark 藍牙設備
@property (strong, nonatomic) CBCentralManager      *centralManager;         //接收
@property (strong, nonatomic) CBPeripheral          *discoveredPeripheral;   //外設

@end

4.開始藍牙配置
#pragma mark 在初始化界面結束後設置自己爲代理
- (void)viewDidLoad {
    [super viewDidLoad];
    
   _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

#pragma mark 此處監控一下中央的狀態值,可以判斷藍牙是否開啓/可用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSMutableString *stringForCentralManagerState = [NSMutableString stringWithString:@"UpdateState:"];
    
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            [stringForCentralManagerState appendString:@"Unkown\n"];
            break;
        case CBCentralManagerStateUnsupported:
            [stringForCentralManagerState appendString:@"Unsupported\n"];
        case CBCentralManagerStateUnauthorized:
            [stringForCentralManagerState appendString:@"Unauthorized\n"];
        case CBCentralManagerStateResetting:
            [stringForCentralManagerState appendString:@"Resetting\n"];
        case CBCentralManagerStatePoweredOff:
            [stringForCentralManagerState appendString:@"PowerOff\n"];
        case CBCentralManagerStatePoweredOn:
            //設備支持BLE並且可用
            [stringForCentralManagerState appendString:@"PoweredOn\n"];
            
            //開始搜索
            [self scan];
            break;
        default:
            [stringForCentralManagerState appendString:@"none\n"];
            break;
    }
    NSLog(@"%@", stringForCentralManagerState);

}

#pragma mark 掃描
- (void)scan
{
    
    //第一個參數如果設置爲nil,會尋找所有service
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]
     options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
     
    
     NSLog(@"Scanning started");
}

#pragma mark 發現設備,連接
//一旦符合要求的設備被發現,就會回調此方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    
    NSLog(@"Discovered %@ at %@", peripheral.name, RSSI);
    
    if (self.discoveredPeripheral != peripheral) {
        
        self.discoveredPeripheral = peripheral;
        
        // 連接
        NSLog(@"Connecting to peripheral %@", peripheral);
        [self.centralManager connectPeripheral:peripheral options:nil];
    }
}

#pragma mark 未能連接的處理方法
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Failed to connect to %@. (%@)", peripheral, [error localizedDescription]);
//    [self cleanup];
}

#pragma mark 當連接上設備
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"Peripheral Connected");
    
    // 已連接上設備,故停止搜索
    [self.centralManager stopScan];
    NSLog(@"Scanning stopped");
    // Make sure we get the discovery callbacks
    peripheral.delegate = self;
    
    // 尋找指定UUID的Service
    [peripheral discoverServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
}

#pragma mark 發現設備上指定Service會回調此處
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error) {
        NSLog(@"Error discovering services: %@", [error localizedDescription]);
        return;
    }
    
    // 尋找指定UUID的Characteristic
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]] forService:service];
    }
}
#pragma mark 找到指定UUID的Characteristic會回調此處
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    if (error) {
        NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
 
        return;
    }
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
            NSLog(@"find the characteristic");
            
            
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            
        }
    }
}


- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        
               NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
        return;
    }
    
    NSLog(@"value --> %@",characteristic.value);
   
#pragma mark 把接收到的數據進行截取
//此處我們就可以拿到value值對其進行數據解析了
    NSData *data = characteristic.value;

 }

#pragma mark 藍牙斷開後自動重連
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

{
    
    NSLog(@"Peripheral Disconnected");
    self.discoveredPeripheral = nil;
    [self scan];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"藍牙連接狀態" message:@"連接已斷開" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:@"關閉", nil];
    [alert show];
   
}


5.藍牙後臺運行
若要實現藍牙4.0在APP進入後臺時仍能工作,傳輸數據,不用寫代碼,只需要修改xxx-info.plist文件即可
所需的背景模式中加入兩項
使用CoreBluetooth應用程序共享數據  和  應用程序進行通信使用CoreBluetooth即可



發佈了28 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章