CoreBlueTooth框架初步應(yīng)用

首先導(dǎo)入庫#import<CoreBluetooth/CoreBluetooth.h>

遵循代理:<CBCentralManagerDelegate,CBPeripheralDelegate>

聲明變量:

@property(nonatomic,strong)CBCentralManager*bluetoothManager;

@property(nonatomic,strong)CBPeripheralManager*manager;

1、創(chuàng)建中心設(shè)備并設(shè)置代理:

self.bluetoothManager=[[CBCentralManageralloc]initWithDelegate:self queue:dispatch_get_main_queue()];

self.manager=[[CBPeripheralManageralloc]initWithDelegate:self queue:nil];

CBCentralManagerDelegate代理必須執(zhí)行方法是查看中心設(shè)備狀態(tài)是否打開藍(lán)牙:

-(void)centralManagerDidUpdateState:(CBCentralManager

*)central{

switch (central.state) {

case CBCentralManagerStateUnknown:

break;

case CBCentralManagerStateResetting:

break;

case CBCentralManagerStateUnsupported:

break;

case CBCentralManagerStateUnauthorized:

break;

case CBCentralManagerStatePoweredOff:

break;

case CBCentralManagerStatePoweredOn:

break;

default:

break;

}

}

2、開始掃描外部設(shè)備:

[self.bluetoothManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO }];

第一個參數(shù)那里表示掃描帶有相關(guān)服務(wù)的外部設(shè)備,例如填寫

@[[CBUUID UUIDWithString:@"需要連接的外部設(shè)備的服務(wù)的UUID"]],即表示帶有需要連接的外部設(shè)備的服務(wù)的UUID的外部設(shè)備,nil表示掃描全部設(shè)備;

@{ CBCentralManagerScanOptionAllowDuplicatesKey : @NO }

NO表示不會讓中心設(shè)備不斷地監(jiān)聽外部設(shè)備的消息,YES就是能不斷地監(jiān)聽外部設(shè)備消息。

3、一旦掃描到外部設(shè)備,就會進(jìn)入?yún)f(xié)議中:

-(void)centralManager:(CBCentralManager *)centraldidDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{

//找到的設(shè)備必須持有它,否則CBCentralManager中也不會保存peripheral,那么CBPeripheralDelegate中的方法也不會被調(diào)用!

在這里可以根據(jù)我們所知道的硬件設(shè)備條件來篩選所需要的設(shè)備,將其他打開藍(lán)牙的設(shè)備排除在外。

例如:搜找硬件盒子名字為JL的設(shè)備:

@property (nonatomic, strong) NSMutableArray *peripherals;

@property(nonatomic, strong) NSMutableArray *peripheralsNameArray;

初始化數(shù)組略

if (! [self.peripherals containsObject:peripheral]) {

[self.peripherals addObject:peripheral];

}

NSArray *tempPeripherals = [self.peripheralscopy];

for (CBPeripheral *per intempPeripherals) {

if (! [self.peripheralsNameArraycontainsObject:per.name]){

if ([[per.name substringToIndex:2]isEqualToString:@"JL"]) {

[self.peripheralsNameArrayaddObject:per.name];

}else {

[self.peripherals removeObject:per];

}

}

}

}

選擇某一搜索到的特定設(shè)備進(jìn)行連接

LGAlertView *alert= [LGAlertView alertViewWithTitle:@"請選擇您的設(shè)備"

message:@"" style:LGAlertViewStyleActionSheet buttonTitles:self.peripheralsNameArray

cancelButtonTitle:@"取消"destructiveButtonTitle:nil actionHandler:^(LGAlertView *alertView, NSString*title, NSUInteger index) {

CBPeripheral *per;

per = index

self.deviceName = index

[self.bluetoothManagerconnectPeripheral:per options:nil];

此時是中心設(shè)備和外部設(shè)備的連接,連接成功或者失敗會進(jìn)入不同的方法。

} cancelHandler:^(LGAlertView*alertView) {

[self.bluetoothManagerstopScan];

} destructiveHandler:nil];

}

4、中心設(shè)備與外部設(shè)備連接狀態(tài)調(diào)用的方法:

-(void)centralManager:(CBCentralManager *)centraldidConnectPeripheral:(CBPeripheral *)peripheral(中心設(shè)備和外部設(shè)備的連接成功){

[central stopScan];

//設(shè)置的peripheral委托CBPeripheralDelegate

[peripheral setDelegate:self];

//掃描外設(shè)Services,成功后會進(jìn)入方法:

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError*)error;

[peripheral discoverServices:nil];

}

- (void)centralManager:(CBCentralManager *)central

didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullableNSError

*)error;(中心設(shè)備和外部設(shè)備的連接斷開)

- (void)centralManager:(CBCentralManager *)central

didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error ;(中心設(shè)備和外部設(shè)備的連接,連接失?。?/p>

5、掃描外設(shè)服務(wù)后緊接著會進(jìn)入服務(wù)的代理方法中:

- (void)peripheral:(CBPeripheral *)peripheraldidDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{

for (CBService *service inperipheral.services) {

//掃描每個service的Characteristics,掃描到后會進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral

didDiscoverCharacteristicsForService:(CBService *)service error:(NSError

*)error;

[peripheral discoverCharacteristics:nilforService:service];

}

}

- (void)peripheral:(CBPeripheral *)peripheraldidDiscoverCharacteristicsForService:(CBService *)service error:(NSError*)error{

//獲取Characteristic的值,讀到數(shù)據(jù)會進(jìn)入方法:-(void)peripheral:(CBPeripheral

*)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic

error:(NSError *)error;

for (CBCharacteristic*characteristic in service.characteristics){

[peripheralreadValueForCharacteristic:characteristic];

}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic*)characteristic error:(NSError *)error {

//打印出characteristic的UUID和值

//!注意,value的類型是NSData,具體開發(fā)時,會根據(jù)外設(shè)協(xié)議制定的方式去解析數(shù)據(jù)

NSLog(@"characteristicuuid:%@value:%@",characteristic.UUID,characteristic.value);

}

6、根據(jù)拿到的數(shù)據(jù)就可以進(jìn)行寫操作:

//寫數(shù)據(jù)

- (void)writeCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic*)characteristic value:(NSData *)value {

//打印出characteristic的權(quán)限,可以看到有很多種,這是一個NS_OPTIONS,就是可以同時用于好幾個值,常見的有read,write,notify,indicate,知道這幾個基本就夠用了,前連個是讀寫權(quán)限,后兩個都是通知,兩種不同的通知方式。

/*

typedef NS_OPTIONS(NSUInteger,CBCharacteristicProperties) {

CBCharacteristicPropertyBroadcast= 0x01,

CBCharacteristicPropertyRead= 0x02,

CBCharacteristicPropertyWriteWithoutResponse= 0x04,

CBCharacteristicPropertyWrite= 0x08,

CBCharacteristicPropertyNotify= 0x10,

CBCharacteristicPropertyIndicate= 0x20,

CBCharacteristicPropertyAuthenticatedSignedWrites= 0x40,

CBCharacteristicPropertyExtendedProperties= 0x80,

CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA,6_0)= 0x100,

CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA,6_0)= 0x200

};

*/

//只有characteristic.propertieswrite的權(quán)限才可以寫

if(characteristic.properties& CBCharacteristicPropertyWrite){

//最好一個type參數(shù)可以為CBCharacteristicWriteWithResponsetype:CBCharacteristicWriteWithResponse,區(qū)別是是否會有反饋

[peripheral writeValue:valueforCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];

}

}

7、根據(jù)下面方法判斷寫入成功與否:

- (void)peripheral:(CBPeripheral *)peripheraldidWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError*)error;

8、搜索CharacteristicDescriptors,讀到數(shù)據(jù)會進(jìn)入方法:

-(void)peripheral:(CBPeripheral *)peripheraldidDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristicerror:(NSError *)error{

for (CBCharacteristic*characteristic in service.characteristics){

[peripheraldiscoverDescriptorsForCharacteristic:characteristic];

}

}

//搜索到Characteristic的Descriptors

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic*)characteristic error:(NSError *)error

//獲取到Descriptors的值

- (void)peripheral:(CBPeripheral *)peripheraldidUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {

//打印出DescriptorsUUID和value

//這個descriptor都是對于characteristic的描述,一般都是字符串,所以這里我們轉(zhuǎn)換成字符串去解析

NSLog(@"characteristicuuid:%@value:%@",[NSStringstringWithFormat:@"%@",descriptor.UUID],descriptor.value);

}

9、停止并斷開連接設(shè)備:

- (void)disconnectPeripheral:(CBCentralManager *)centralManagerperipheral:(CBPeripheral *)peripheral {

//停止掃描

[centralManager stopScan];

//斷開連接

[centralManagercancelPeripheralConnection:peripheral];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容