所做的東西是通過手機(jī)/pad與藍(lán)牙4.0的設(shè)備進(jìn)行連接,之后設(shè)備上按對(duì)應(yīng)的按鍵我們會(huì)收到對(duì)應(yīng)的數(shù)值。首先需要和做藍(lán)牙4.0的同事溝通好通信協(xié)議,具體的數(shù)據(jù)解析部分就不過多贅述了,主要寫一下藍(lán)牙接收數(shù)據(jù)的部分
1.和做藍(lán)牙的同事溝通好設(shè)備的UUID以及特點(diǎn),可以把他們寫成宏
#define TRANSFER_SERVICE_UUID @"0000fff0-0000-1000-8000-00805f9b34fb"
#define TRANSFER_CHARACTERISTIC_UUID @"0000fff7-0000-1000-8000-00805f9b34fb"
2.在.H文件中導(dǎo)入兩個(gè)頭文件,并在接口中實(shí)現(xiàn)兩個(gè)協(xié)議
#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "UUID.h"
//需要實(shí)現(xiàn)協(xié)議
@interface ViewController () < CBCentralManagerDelegate, CBPeripheralDelegate>
{
}
3.創(chuàng)建兩個(gè)藍(lán)牙設(shè)備屬性,一個(gè)相當(dāng)于主機(jī),一個(gè)相當(dāng)于外設(shè)從機(jī)
#pragma mark 藍(lán)牙設(shè)備
@property (strong, nonatomic) CBCentralManager *centralManager; //接收
@property (strong, nonatomic) CBPeripheral *discoveredPeripheral; //外設(shè)
@end
4.開始藍(lán)牙配置
#pragma mark 在初始化界面結(jié)束后設(shè)置自己為代理
- (void)viewDidLoad {
[super viewDidLoad];
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
#pragma mark 此處監(jiān)控一下中央的狀態(tài)值,可以判斷藍(lán)牙是否開啟/可用
- (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:
//設(shè)備支持BLE并且可用
[stringForCentralManagerState appendString:@"PoweredOn\n"];
//開始搜索
[self scan];
break;
default:
[stringForCentralManagerState appendString:@"none\n"];
break;
}
NSLog(@"%@", stringForCentralManagerState);
}
#pragma mark 掃描
- (void)scan
{
//第一個(gè)參數(shù)如果設(shè)置為nil,會(huì)尋找所有service
[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]
options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
NSLog(@"Scanning started");
}
#pragma mark 發(fā)現(xiàn)設(shè)備,連接
//一旦符合要求的設(shè)備被發(fā)現(xiàn),就會(huì)回調(diào)此方法
- (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 當(dāng)連接上設(shè)備
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@"Peripheral Connected");
// 已連接上設(shè)備,故停止搜索
[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 發(fā)現(xiàn)設(shè)備上指定Service會(huì)回調(diào)此處
- (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會(huì)回調(diào)此處
- (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 把接收到的數(shù)據(jù)進(jìn)行截取
//此處我們就可以拿到value值對(duì)其進(jìn)行數(shù)據(jù)解析了
NSData *data = characteristic.value;
}
#pragma mark 藍(lán)牙斷開后自動(dòng)重連
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"Peripheral Disconnected");
self.discoveredPeripheral = nil;
[self scan];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"藍(lán)牙連接狀態(tài)" message:@"連接已斷開" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:@"關(guān)閉", nil];
[alert show];
}
5.藍(lán)牙后臺(tái)運(yùn)行
若要實(shí)現(xiàn)藍(lán)牙4.0在APP進(jìn)入后臺(tái)時(shí)仍能工作,傳輸數(shù)據(jù),不用寫代碼,只需要修改xxx-info.plist文件即可
在所需的背景模式中加入兩項(xiàng)
使用CoreBluetooth應(yīng)用程序共享數(shù)據(jù) 和 應(yīng)用程序進(jìn)行通信使用CoreBluetooth即可