CoreBluetooth 是基于藍(lán)牙 ble 技術(shù)實(shí)現(xiàn)的,現(xiàn)在的智能手環(huán)手表都使用了低功耗藍(lán)牙技術(shù)。
CoreBluetooth 場(chǎng)景中藍(lán)牙對(duì)象分為兩種:
- 中心設(shè)備(CBCentralManager * cbcManager): 中心設(shè)備負(fù)責(zé)掃描接收廣播,連接外設(shè)設(shè)備,向外設(shè)設(shè)備進(jìn)行讀寫(xiě)操作。
- 外設(shè)設(shè)備(CBPeripheral * peripheral): 向外發(fā)送廣播,向中心設(shè)備讀寫(xiě)操作。
注意: <u>一個(gè)設(shè)備既可以是中心設(shè)備,又可以是外設(shè)設(shè)備,但是不能同時(shí)是中心設(shè)備和外設(shè)設(shè)備,同一時(shí)間,只能扮演一種角色。</u>
基礎(chǔ)知識(shí)介紹:
CBPeripheral
// -------------------- CBPeripheral 屬性 --------------------
// 外設(shè)狀態(tài)
typedef NS_ENUM(NSInteger, CBPeripheralState) {
CBPeripheralStateDisconnected = 0, // 沒(méi)有連接
CBPeripheralStateConnecting, // 正在連接
CBPeripheralStateConnected, // 已經(jīng)連接
CBPeripheralStateDisconnecting NS_AVAILABLE(10_13, 9_0),
} NS_AVAILABLE(10_9, 7_0);
@interface CBPeripheral : CBPeer
@property(weak, nonatomic, nullable) id<CBPeripheralDelegate> delegate;
@property(retain, readonly, nullable) NSString *name; // 外設(shè)名字
@property(retain, readonly, nullable) NSNumber *RSSI; // 信號(hào)強(qiáng)度
@property(readonly) CBPeripheralState state; // 外設(shè)狀態(tài)
@property(retain, readonly, nullable) NSArray<CBService *> *services; // 外設(shè)包含的服務(wù)(每個(gè)服務(wù)里面可能包含多個(gè)特征)
@property(readonly) BOOL canSendWriteWithoutResponse; // 判斷讀寫(xiě)性
// -------------------- CBPeripheral 常用方法 --------------------
// 查找外設(shè)包含的服務(wù),serviceUUIDs 為 nil 則查找該外設(shè)包含的所有服務(wù),執(zhí)行該方法會(huì)觸發(fā)代理方法
- (void)discoverServices:(nullable NSArray<CBUUID *> *)serviceUUIDs;
// 掃描特征的描述,執(zhí)行該方法會(huì)觸發(fā)代理方法
- (void)discoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic;
// 掃描服務(wù)里包含的服務(wù),執(zhí)行該方法會(huì)出發(fā)代理方法
- (void)discoverIncludedServices:(nullable NSArray<CBUUID *> *)includedServiceUUIDs forService:(CBService *)service;
// 掃描服務(wù)包含的特征,執(zhí)行該方法會(huì)出發(fā)代理方法
- (void)discoverCharacteristics:(nullable NSArray<CBUUID *> *)characteristicUUIDs forService:(CBService *)service;
// 讀取某特征的數(shù)據(jù)
- (void)readValueForCharacteristic:(CBCharacteristic *)characteristic;
// 讀取描述的值
- (void)readValueForDescriptor:(CBDescriptor *)descriptor;(CBCharacteristicWriteType)type;
// 通過(guò)特征寫(xiě)入數(shù)據(jù)
- (void)writeValue:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic type:
// 通過(guò)描述寫(xiě)入數(shù)據(jù)
- (void)writeValue:(NSData *)data forDescriptor:(CBDescriptor *)descriptor;
// 設(shè)置通知
- (void)setNotifyValue:(BOOL)enabled forCharacteristic:(CBCharacteristic *)characteristic;
// -------------------- 代理方法 --------------------
// 掃描外設(shè)服務(wù)觸發(fā)該代理,如果找打服務(wù),可以在這里調(diào)用 discoverCharacteristics 方法查找該服務(wù)的特征
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error;
// 掃描服務(wù)包含的服務(wù)(服務(wù)里面可能會(huì)包含服務(wù))
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(NSError *)error;
// 查找服務(wù)的特征,一個(gè)服務(wù)可能有多個(gè)特征,一個(gè)特征可能有多個(gè)屬性,CBCharacteristic 是一個(gè)枚舉值
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(nonnull CBService *)service error:(nullable NSError *)error;
// 接收通知代理
-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error;
// 讀取 Characteristic 中的值,調(diào)用 readValueForCharacteristic 方法會(huì)觸發(fā)該代理,需要在該代理方法里面獲取具體的數(shù)據(jù)
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error;
// 向 CBCharacteristic 寫(xiě)入數(shù)據(jù)的回調(diào)
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error;
CBCentralManager
// 中心設(shè)備的狀態(tài),創(chuàng)建中心設(shè)備的時(shí)候,會(huì)觸發(fā)代理,在代理里面判斷中心設(shè)備狀態(tài),在狀態(tài)為 CBManagerStatePoweredOn 的時(shí)候可以開(kāi)始掃描廣播
typedef NS_ENUM(NSInteger, CBCentralManagerState) {
CBCentralManagerStateUnknown = CBManagerStateUnknown, // 未知
CBCentralManagerStateResetting = CBManagerStateResetting, // 正在重置
CBCentralManagerStateUnsupported = CBManagerStateUnsupported, // 不支持
CBCentralManagerStateUnauthorized = CBManagerStateUnauthorized, // 未認(rèn)證
CBCentralManagerStatePoweredOff = CBManagerStatePoweredOff, // 沒(méi)有打開(kāi)藍(lán)牙
CBCentralManagerStatePoweredOn = CBManagerStatePoweredOn, // 藍(lán)牙以打開(kāi),可以掃描廣播
} NS_DEPRECATED(10_7, 10_13, 5_0, 10_0, "Use CBManagerState instead");
@interface CBCentralManager : CBManager
@property(nonatomic, weak, nullable) id<CBCentralManagerDelegate> delegate;
@property(nonatomic, assign, readonly) BOOL isScanning ; // 判斷藍(lán)牙是否正在掃描廣播
// 藍(lán)牙中心設(shè)備初始化方法,需要指定 delegate 并實(shí)現(xiàn)代理方法
- (instancetype)initWithDelegate:(nullable id<CBCentralManagerDelegate>)delegate
queue:(nullable dispatch_queue_t)queue;
// -------------------- 常用方法 --------------------
// 通過(guò)服務(wù) ID 來(lái)掃描外設(shè)
- (void)scanForPeripheralsWithServices:(nullable NSArray<CBUUID *> *)serviceUUIDs options:(nullable NSDictionary<NSString *, id> *)options;
// 連接外設(shè)
- (void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary<NSString *, id> *)options;
// 取消連接
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral;
// 停止掃描
- (void)stopScan;
// 通過(guò) ID 數(shù)組查找外設(shè)
- (NSArray<CBPeripheral *> *)retrievePeripheralsWithIdentifiers:(NSArray<NSUUID *> *)identifiers NS_AVAILABLE(10_9, 7_0);
// 通過(guò) 服務(wù)的 UUID 數(shù)組查找外設(shè)
- (NSArray<CBPeripheral *>*)retrieveConnectedPeripheralsWithServices:(NSArray<CBUUID *> *)serviceUUIDs NS_AVAILABLE(10_9, 7_0);
// @protocol CBCentralManagerDelegate <NSObject> 代理方法
// 中心設(shè)備開(kāi)始掃描之后,每發(fā)現(xiàn)一個(gè)外設(shè)就會(huì)調(diào)用一次該方法,同一設(shè)備可能會(huì)被發(fā)現(xiàn)多次,掃描頻率基本固定,外設(shè)發(fā)送的廣播不一定每一個(gè)都能接收到,如果使用該方法獲取廣播數(shù)據(jù)的時(shí)候需要注意
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI;
// 中心設(shè)備連接上外設(shè)之后調(diào)用
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;
// 連接失敗調(diào)用
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
// 斷開(kāi)連接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
// 中心設(shè)備狀態(tài)改變的時(shí)候調(diào)用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
// 中心設(shè)備狀態(tài)重置的時(shí)候調(diào)用
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *, id> *)dict;
連接過(guò)程
外設(shè)設(shè)備向外廣播
中心設(shè)備接收廣播(廣播包含了廣播內(nèi)容和外設(shè)的名字,信號(hào)強(qiáng)度等屬性(iOS 的 CoreBluetooth 框架不能從廣播里面獲取到外設(shè) MAC 地址,所以不能使用 MAC 地址來(lái)區(qū)分外設(shè))
掃描
連接
掃描外設(shè)所包含的服務(wù) Services
掃描每一個(gè)服務(wù)所包含的特征 Characteristics
判斷特征的屬性 CBCharacteristicProperties(根據(jù)需求保存對(duì)應(yīng)屬性的 Characteristics,后面讀/寫(xiě)的時(shí)候只能往可讀/可寫(xiě)屬性的特征里面寫(xiě), CBCharacteristicProperties 是一個(gè)枚舉)
注意: <u>一個(gè)特征可能同時(shí)擁有多個(gè)屬性,比如屬性值為 0x02 & 0x08 則該特性可讀可寫(xiě)</u>
typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
CBCharacteristicPropertyBroadcast= 0x01, // 廣播屬性
CBCharacteristicPropertyRead= 0x02, // 可讀屬性
CBCharacteristicPropertyWriteWithoutResponse= 0x04, // 無(wú)響應(yīng)的寫(xiě)
CBCharacteristicPropertyWrite= 0x08, // 寫(xiě)
CBCharacteristicPropertyNotify= 0x10, // 通知
CBCharacteristicPropertyIndicate= 0x20,
CBCharacteristicPropertyAuthenticatedSignedWrites= 0x40,
CBCharacteristicPropertyExtendedProperties= 0x80,
CBCharacteristicPropertyNotifyEncryptionRequired= 0x100,
CBCharacteristicPropertyIndicateEncryptionRequired= 0x200
};
實(shí)際使用
CBCentralManager 中心設(shè)備方法使用
@interface XIXCBCenterManager : CBCentralManagerDelegate
@property (strong, nonatomic) CBCentralManager * cbcManager;
...
-(void)propertyInit{
...
// 創(chuàng)建 cbcManager 對(duì)象,創(chuàng)建之后會(huì)調(diào)用代理返回中心設(shè)備狀態(tài)
self.cbcManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
#pragma mark - CoreBlueToothDelegate
// 藍(lán)牙狀態(tài)代理,藍(lán)牙創(chuàng)建之后會(huì)調(diào)用一次
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state) {
case CBManagerStatePoweredOn: // 藍(lán)牙狀態(tài)可用
NSLog(@"藍(lán)牙已打開(kāi),可用,開(kāi)始掃描");
// 藍(lán)牙狀態(tài)可用的時(shí)候,開(kāi)啟掃描可用的藍(lán)牙外設(shè)
[self.cbcManager scanForPeripheralsWithServices:nil options:nil];
[MBProgressHUD ShowMBToView:self.view withMessage:@"正在掃描設(shè)備..."];
break;
case CBManagerStateUnsupported:
[MBProgressHUD showError:@"藍(lán)牙不可用"];
break;
default:{
[MBProgressHUD hideHUDForView:self.view];
UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:nil message:@"請(qǐng)先開(kāi)啟藍(lán)牙功能" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction * settingAction = [UIAlertAction actionWithTitle:@"去設(shè)置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}];
[alertVC addAction:cancelAction];
[alertVC addAction:settingAction];
[self presentViewController:alertVC animated:YES completion:nil];
}
break;
}
}
/**
掃描到藍(lán)牙外設(shè)后調(diào)用,每掃描到一個(gè)設(shè)備信息返回一次,判斷返回的該藍(lán)牙是否是已經(jīng)被添加過(guò)的,如果被添加過(guò),則替換數(shù)組中的該設(shè)備,如果沒(méi)有添加過(guò)則添加到數(shù)組
@param central central
@param peripheral 掃描到的藍(lán)牙外設(shè)
@param advertisementData 藍(lán)牙外設(shè)的額外數(shù)據(jù)
@param RSSI 信號(hào)強(qiáng)度
*/
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI{
if (peripheral.name.length <= 0) return;
// 獲取外設(shè)廣播包含的數(shù)據(jù)
NSData * adverData = advertisementData[@"kCBAdvDataManufacturerData"] ;
if(adverData != nil){
AdvertiseMentModel * advModel = [self.connect getAdvertisementData:adverData];
// 如果掃描到的外設(shè)已存在,則替換,如果不存在則添加,刷新列表
if (advModel) {
PeripheralModel * peripheralModel;
if (![self.perArray containsObject:peripheral]) {
[self.perArray addObject:peripheral];
peripheralModel = [[PeripheralModel alloc] initWithPeripheral:peripheral];
[self.deviceArray addObject:peripheralModel];
}
NSInteger index = [self.perArray indexOfObject:peripheral];
peripheralModel = self.deviceArray[index];
peripheralModel.advertisementModel = advModel;
[self.tableView reloadData];
}
}
}
// 使用列表展示外設(shè),點(diǎn)擊 Cell 的時(shí)候,獲取外設(shè)對(duì)象并連接
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
self.selectedPeriphalModel = self.resultList[indexPath.row];
NSDictionary * dic = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey];
[self.cbcManager connectPeripheral:self.selectedPeriphalModel.periphal options:dic];
[MBProgressHUD ShowMBToView:self.view withMessage:@"正在連接設(shè)備..."];
// 設(shè)置 10s 的連接超時(shí)時(shí)間,連接超時(shí)則調(diào)用 [self.cbcManager cancelPeripheralConnection:self.selectedPeriphalModel.periphal]; 取消連接
[self performSelector:@selector(connectTimeOut) withObject:nil afterDelay:10.0f];
}
// 連接成功調(diào)用代理
/**
連接外設(shè)成功后調(diào)用
@param central central
@param peripheral 連接成功的設(shè)備
*/
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
// 沒(méi)有超時(shí)則需要取消延遲 調(diào)用方法 同時(shí)停止掃描
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(connectTimeOut) object:nil];
[self.cbcManager stopScan]; // 停止掃描
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
/**
連接失敗調(diào)用
@param central central
@param peripheral 連接的設(shè)備
@param error 錯(cuò)誤原因
*/
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[MBProgressHUD showError:@"連接失敗"];
}
// 斷開(kāi)連接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
[MBProgressHUD hideHUDForView:self.view animated:NO];
}
CBPeripheral 外設(shè)設(shè)備方法使用
#define CHARACTER_UUID_WRITE @"5E9BF2A8-F93F-4481-A67E-3B2F4A07891A"
#define CHARACTER_UUID_NOTI @"8AC32D3F-5CB9-4D44-BEC2-EE689169F626"
@property (strong, nonatomic) CBPeripheral * peripheral;
// 保存可寫(xiě)的特征,寫(xiě)數(shù)據(jù)的時(shí)候用這個(gè)特征寫(xiě)入數(shù)據(jù)
@property (strong, nonatomic) CBCharacteristic * writeCharacter;
// 連接上外設(shè)之后調(diào)用 discoverServices 方法,查找該外設(shè)所包含的服務(wù)
[self.peripheral discoverServices:nil];
// 寫(xiě)入數(shù)據(jù)
[self.peripheral writeValue:data forCharacteristic:self.writeCharacter type:CBCharacteristicWriteWithResponse];
#pragma mark - CBPeripheralDelegate
/**
查找藍(lán)牙代理的服務(wù),一個(gè)藍(lán)牙外設(shè)可能有多個(gè)服務(wù)
@param peripheral peripheral
@param error 錯(cuò)誤信息
*/
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
// NSString * UUID_str = [peripheral.identifier UUIDString];
// NSLog(@"UUID:%@",UUID_str);
if (error) {
NSLog(@"查找藍(lán)牙服務(wù)出錯(cuò)");
return;
}
// 開(kāi)始遍歷查找服務(wù),查找每個(gè)服務(wù)的特征
for (CBService * service in peripheral.services) {
// 如果知道特征的 UUID 可以在第一個(gè)參數(shù)傳入 UUID 數(shù)組
NSLog(@"服務(wù)CBUUID:%@",service.UUID.UUIDString);
[self.peripheral discoverCharacteristics:nil forService:service];
}
}
// 掃描服務(wù)包含的服務(wù)
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(NSError *)error{
if (error) {
NSLog(@"掃描服務(wù)內(nèi)部的服務(wù)失敗");
return;
}
NSArray * services = service.includedServices;
for (CBService * service in services) {
// 如果知道特征的 UUID 可以在第一個(gè)參數(shù)傳入 UUID 數(shù)組
[peripheral discoverCharacteristics:nil forService:service];
}
}
// 查找服務(wù)的特征,一個(gè)服務(wù)可能有多個(gè)特征,一個(gè)特征可能有多個(gè)屬性,CBCharacteristic 是一個(gè)枚舉值
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(nonnull CBService *)service error:(nullable NSError *)error{
if(error){
NSLog(@"查找特征錯(cuò)誤");
return;
}
for (CBCharacteristic * characteristic in service.characteristics) {
// 這里開(kāi)發(fā)的時(shí)候和硬件溝通,獲取到了具體的特征的 UUID
if([characteristic.UUID.UUIDString isEqualToString: CHARACTER_UUID_WRITE]){
self.writeCharacter = characteristic; // 這是可寫(xiě)屬性,保存起來(lái)后面需要使用它來(lái)寫(xiě)數(shù)據(jù)
}else if([characteristic.UUID.UUIDString isEqualToString: CHARACTER_UUID_NOTI]){
// 監(jiān)聽(tīng)該特征,外設(shè)發(fā)送通知的時(shí)候才能收到數(shù)據(jù)
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}
// 接收通知代理
-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
if (error) {
NSLog(@"錯(cuò)誤:%@",error.localizedDescription);
return;
}
CBCharacteristicProperties properties = characteristic.properties;
if (properties & CBCharacteristicPropertyRead) {
// 如果具備讀特性,即可讀取特性的 Value 值
[peripheral readValueForCharacteristic:characteristic];
}
}
// 讀取 Characteristic 中的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error{
if (error) {
NSLog(@"讀取數(shù)據(jù)錯(cuò)誤:%@",error.localizedDescription);
return;
}
NSData * dada = characteristic.value;
if (dada.length <= 0) {
return;
}
Byte * byteData = (Byte*)[dada bytes];
if (!(byteData[0] == 0x48 && byteData[1] == 0x65 &&byteData[2] == 0x6c &&byteData[3] == 0x6c)) {
NSLog(@"通知數(shù)據(jù):%@",dada);
....
}
}
// 寫(xiě)入數(shù)據(jù)的回調(diào),返回寫(xiě)入成功失敗結(jié)果
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error{
if (error) {
NSLog(@"寫(xiě)入數(shù)據(jù)失敗");
}
}
中心設(shè)備就是主動(dòng)去連接別的設(shè)備的設(shè)備,一般就是手機(jī),外設(shè)就是發(fā)送廣播,被連接的設(shè)備,一般就是手環(huán)或者包含藍(lán)牙模塊的硬件設(shè)備
CoreBlutooth 已經(jīng)把 ble 封裝的很好,只需要順著代理方法一步一步從掃描到連接到數(shù)據(jù)讀寫(xiě)都可以完成。
另外: 藍(lán)牙廣播的數(shù)據(jù)長(zhǎng)度大小有限制,不能通過(guò)廣播獲取外設(shè) MAC 地址來(lái)區(qū)分,所以區(qū)分多個(gè)外設(shè)的話就需要在廣播的 kCBAdvDataManufacturerData 字段的數(shù)據(jù)里面包含, advertisementData 數(shù)據(jù)包含多個(gè)字段,大家可以在使用的時(shí)候打印看看,具體的字段對(duì)數(shù)據(jù)的類(lèi)型也有限制,服務(wù)、特征、描述都是對(duì)應(yīng)的 uuid 來(lái)唯一標(biāo)識(shí),如何知道 UUID 的話直接使用 UUID 能免去多層遍歷。