標籤:
原文連結:http://m.blog.csdn.net/article/details?plg_nld=1&id=51014318&plg_auth=1&plg_uin=1&plg_usr=1&plg_vkey=1&plg_nld=1&plg_d
文章出處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即可
CoreBluetooth——IOS藍芽4.0使用心得