CoreBluetooth中,需要用到的類和協(xié)議(完整導(dǎo)圖):
成都創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:做網(wǎng)站、網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的紅花崗網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
藍(lán)牙分類中心端和外設(shè)端(完整導(dǎo)圖)。
中心端(接收端)
1 .創(chuàng)建中心端控制器(CBCentralManager)
2 .掃描設(shè)備(Discover)
3 .連接 (Connect)
4 .獲取Service和Characteristic
- 掃描Service (一個(gè)service中包含一個(gè)或多個(gè)Characteristic)
- 獲取Service中Characteristic
- 獲取Characteristic的值
5 . 數(shù)據(jù)交互(explore and interact)
- 訂閱Characteristic的通知
6 . 斷開鏈接
外設(shè)端(發(fā)送端)
- 創(chuàng)建Peripheral管理對(duì)象
- 創(chuàng)建Service和Characteristic樹
- 發(fā)送廣告
- 處理讀寫請(qǐng)求和訂閱
藍(lán)牙狀態(tài)
typedef NS_ENUM(NSInteger, CBManagerState) {
CBManagerStateUnknown = 0,
CBManagerStateResetting,
CBManagerStateUnsupported, //不支持
CBManagerStateUnauthorized, //未授權(quán)
CBManagerStatePoweredOff, //關(guān)閉
CBManagerStatePoweredOn, //藍(lán)牙打開狀態(tài)
} NS_ENUM_AVAILABLE(NA, 10_0);
連接狀態(tài)
/*!
* @enum CBPeripheralState
*
* @discussion Represents the current connection state of a CBPeripheral.
*
*/
typedef NS_ENUM(NSInteger, CBPeripheralState) {
CBPeripheralStateDisconnected = 0,
CBPeripheralStateConnecting,
CBPeripheralStateConnected,
CBPeripheralStateDisconnecting NS_AVAILABLE(NA, 9_0),
} NS_AVAILABLE(NA, 7_0);
CBCentralManagerDelegate
@required
// 更新CentralManager狀態(tài),參數(shù)central就是當(dāng)前的Manager。
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
@optional
// 藍(lán)牙狀態(tài)的保存和恢復(fù),進(jìn)入后臺(tái)和重新啟動(dòng)有關(guān)
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *, id> *)dict;
//掃描外部設(shè)備
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI;
//與外設(shè)完成連接
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;
//連接失敗
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
//斷開連接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
CBPeripheralDelegate
@optional
//peripheral更新
- (void)peripheralDidUpdateName:(CBPeripheral *)peripheral NS_AVAILABLE(NA, 6_0);
//服務(wù)更新時(shí)觸發(fā)
- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray<CBService *> *)invalidatedServices NS_AVAILABLE(NA, 7_0);
//更新RSSI,過時(shí)用下一代替
- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(nullable NSError *)error NS_DEPRECATED(NA, NA, 5_0, 8_0);
// RSSI值
- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(nullable NSError *)error NS_AVAILABLE(NA, 8_0);
//發(fā)現(xiàn)服務(wù)
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error;
//發(fā)現(xiàn)嵌套服務(wù)
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(nullable NSError *)error;
//發(fā)現(xiàn)服務(wù)中的Characteristic
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error;
//更新Characteristic
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error;
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error;
CBPeripheralManagerDelegate
@required
//類似CBCentralManager
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral;
@optional
- (void)peripheralManager:(CBPeripheralManager *)peripheral willRestoreState:(NSDictionary<NSString *, id> *)dict;
//開始廣播
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(nullable NSError *)error;
//添加服務(wù)
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(nullable NSError *)error;
//訂閱
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic;
//未訂閱
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic;
//接收讀取請(qǐng)求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request;
//接收寫入請(qǐng)求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests;
//更新訂閱
- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral;
從上面了解了藍(lán)牙開發(fā)的基本流程和API結(jié)構(gòu),那下面我們一起看看中心端的開發(fā)步驟。
//創(chuàng)建CentralManager
- (void)startUpCentralManager {
_centralManager = [[CBCentralManager alloc] initWithDelegate: self queue: nil];
_peripherals = [NSMutableArray array]; //用于存放掃描的外設(shè)
}
創(chuàng)建CentralManager會(huì)調(diào)用Delegate方法:
#pragma mark - CBCentralManagerDelegate
// 實(shí)現(xiàn): 確保支持BL和有效的Central設(shè)備
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
switch (central.state) {
case CBManagerStatePoweredOn:
//只有此狀態(tài)下才可以進(jìn)行掃描設(shè)備
[self scan];
break;
case CBManagerStateUnknown:
break;
case CBManagerStateResetting:
break;
case CBManagerStateUnsupported:
break;
case CBManagerStateUnauthorized:
break;
case CBManagerStatePoweredOff:
break;
default:
break;
}
}
- (void)scan {
[self.centralManager scanForPeripheralsWithServices: nil options: nil];
NSLog(@"Scanning started");
}
serviceUUIDs: 是一個(gè)CBUUID類型的數(shù)組,每個(gè)CBUUID代表一個(gè)service的UUID。使用這個(gè)參數(shù)可以限制掃描內(nèi)容,如果設(shè)置為nil,則表示搜索全部外設(shè)。
options: 定義掃描 ,字典。
- CBCentralManagerScanOptionAllowDuplicatesKey : 布爾值,無重復(fù)過濾的掃描。默認(rèn)是NO。如果設(shè)置為YES,對(duì)電池有不利影響。
- CBCentralManagerScanOptionSolicitedServiceUUIDsKey 想要掃描的Service UUIDs數(shù)組(NSArray)。
另外,在
bluetooth-central
后臺(tái)模式下,option將被忽略。這個(gè)問題后面會(huì)詳細(xì)講解。
當(dāng)啟動(dòng)掃描后,每次掃描到一個(gè)外設(shè)就會(huì)調(diào)用delegate方法:centralManager: didDiscoverPeripheral: advertisementData: RSSI:
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI {
NSLog(@"%@", peripheral.name);
//查找到設(shè)備并持有它,否則不會(huì)保存
[self.peripherals addObject: peripheral];
}
- peripheral : 掃描到的設(shè)備
- advertisementData: 字典包含所有的廣告數(shù)據(jù)
- RSSI:received signal strength indicator,單位分貝。表示信號(hào)強(qiáng)度。
到這一步我們掃描到外部設(shè)備,那接下來就是建立連接了。
通過掃描,我們發(fā)現(xiàn)了目標(biāo)外設(shè),接下來建立連接。
- (void)startUpConnect {
[self.centralManager connectPeripheral: self.peripheral options: nil];
}
self.peripheral : 目標(biāo)外設(shè)
options :字典,用來定制連接行為
- CBConnectPeripheralOptionNotifyOnConnectionKey
- CBConnectPeripheralOptionNotifyOnDisconnectionKey
- CBConnectPeripheralOptionNotifyOnNotificationKey
進(jìn)行連接通常會(huì)出現(xiàn)兩種情況:成功、失敗。
連接成功
本地連接成功,會(huì)調(diào)用方法:
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"鏈接設(shè)備名稱為:%@", peripheral.name);
// 設(shè)置代理
peripheral.delegate = self;
//發(fā)現(xiàn)服務(wù)
[peripheral discoverServices: nil];
}
連接失敗
//鏈接失敗
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@"連接名稱:%@ 失敗,原因:%@", peripheral.name, error.localizedDescription);
}
另外,既然可以建立連接,那么肯定可以斷開連接。
斷開連接
//斷開鏈接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@"與外設(shè)斷開鏈接:%@, %@", peripheral.name, error.localizedDescription);
}
如果斷開連接不是由
cancelPeripheralConnection:
發(fā)起的,error會(huì)給出詳細(xì)信息。需要注意的是,當(dāng)斷開連接,所有的services, characteristics和Characteristic descriptions都是無效的。
創(chuàng)建連接成功后,在delegate方法中
// 設(shè)置代理
peripheral.delegate = self;
//發(fā)現(xiàn)服務(wù)
[peripheral discoverServices: nil];
可以通過
CBUUID
指定的服務(wù)。
CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
NSLog(@"發(fā)現(xiàn)服務(wù)錯(cuò)誤:%@", error.localizedDescription);
return;
}
// 一個(gè)外設(shè)會(huì)發(fā)送多個(gè)服務(wù)
for (CBService *service in peripheral.services) {
//掃描每個(gè)service的Characteristic,通過Characteristic的UUID來指定查找那個(gè)Characteristic。
[peripheral discoverCharacteristics: nil forService: service];
}
}
注:一個(gè)外設(shè)包含多個(gè)Service,可以通過Service的UUID來區(qū)分。一個(gè)Service包含多個(gè)Characteristic,通過Characteristic的UUID來區(qū)分。
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"發(fā)現(xiàn)特征錯(cuò)誤:%@", error.localizedDescription);
return;
}
for (CBCharacteristic *characteristic in service.characteristics) {
//直接讀取Characteristic值,此時(shí)調(diào)用peripheral: didUpdateValueForCharacteristic: error:
[peripheral readValueForCharacteristic: characteristic];
//另一種情況,訂閱特征。此時(shí)調(diào)用?peripheral: didUpdateNotificationStateForCharacteristic: error:
[peripheral setNotifyValue:YES forCharacteristic: characteristic];
}
}
//給指定的特征設(shè)置通知
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(@"Error changing notification state : %@", error.localizedDescription);
}
if (![characteristic.UUID isEqual:[CBUUID UUIDWithString:@""]]) {
return;
}
if (characteristic.isNotifying) {
NSLog(@"Notification began on :%@", characteristic);
} else {
NSLog(@"Notification stoped on : %@ Disconnecting", characteristic);
[self.centralManager cancelPeripheralConnection: peripheral];
}
}
//readValueCharacteristic時(shí)調(diào)用
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
//打印出characteristic的UUID和值
//!注意,value的類型是NSData,具體開發(fā)時(shí),會(huì)根據(jù)外設(shè)協(xié)議制定的方式去解析數(shù)據(jù)
NSLog(@"特性ID::%@ 值:%@",characteristic.UUID, characteristic.value);
}
- (void)writeValue {
NSData *data = [@"Test" dataUsingEncoding:NSUTF8StringEncoding];
[self.peripheral writeValue: data forCharacteristic: self.characteristic type: CBCharacteristicWriteWithResponse];
}
發(fā)送數(shù)據(jù)
- value: 寫入值
- characteristic : 被寫入的特征
- type: 寫入類型,是否有應(yīng)答
typedef NS_ENUM(NSInteger, CBCharacteristicWriteType) { CBCharacteristicWriteWithResponse = 0, CBCharacteristicWriteWithoutResponse, };
當(dāng)type為CBCharacteristicWriteWithResponse時(shí),調(diào)用delegate方法:
peripheral: didWriteValueForCharacteristic: error:
。
//創(chuàng)建PeripheralManager
- (void)startUpPeripheralManager {
_peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue: nil];
}
//唯一@required方法
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
switch (peripheral.state) {
case CBManagerStatePoweredOn:
// 創(chuàng)建服務(wù)和特征
[self buildService];
break;
case CBManagerStateUnknown :
break;
case CBManagerStateResetting:
break;
case CBManagerStateUnsupported:
break;
case CBManagerStateUnauthorized:
break;
case CBManagerStatePoweredOff:
break;
default:
break;
}
}
- (void)buildService {
//創(chuàng)建Characteristic
self.transferCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID] properties:CBCharacteristicPropertyNotify value: nil permissions:CBAttributePermissionsReadable];
//創(chuàng)建服務(wù)
CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID] primary:YES];
//將特征添加到服務(wù)中
transferService.characteristics = @[self.transferCharacteristic];
//將服務(wù)添加到PeripheralManager中,調(diào)用delegate方法: peripheralManager: didAddService: error:
[self.peripheralManager addService: transferService];
}
創(chuàng)建Characteristic
- UUID : 唯一標(biāo)識(shí)
- properties:屬性
- value : 設(shè)置nil, 動(dòng)態(tài)設(shè)置。
- permission : 權(quán)限
屬性
typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
//特征值可以使用特征描述廣播
CBCharacteristicPropertyBroadcast = 0x01,
//特征值可以被讀取,通過readValueForCharacteristic: 來讀取
CBCharacteristicPropertyRead = 0x02,
// 可以被讀寫,通過writeValue: forCharacteristic: type: 寫入特征值,無應(yīng)答標(biāo)識(shí)寫入成功。
CBCharacteristicPropertyWriteWithoutResponse = 0x04,
// 可以被寫入,有應(yīng)答標(biāo)識(shí)寫入成功
CBCharacteristicPropertyWrite = 0x08,
//允許通知特征值,無應(yīng)答表示接收
CBCharacteristicPropertyNotify = 0x10,
//允許通知特征值,有應(yīng)答表示接收
CBCharacteristicPropertyIndicate = 0x20,
CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,
CBCharacteristicPropertyExtendedProperties = 0x80,
//只有信任的設(shè)備接收特征值通知
CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x100,
CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x200
};
屬性特征,可以組合使用。
權(quán)限
typedef NS_OPTIONS(NSUInteger, CBAttributePermissions) {
// 可讀
CBAttributePermissionsReadable = 0x01,
// 可寫
CBAttributePermissionsWriteable = 0x02,
// 信任可讀
CBAttributePermissionsReadEncryptionRequired = 0x04,
// 信任可寫
CBAttributePermissionsWriteEncryptionRequired = 0x08
} NS_ENUM_AVAILABLE(NA, 6_0);
UUID : 唯一標(biāo)識(shí)
isPrimary:YES:主服務(wù);NO:次服務(wù)添加特征到characteristics數(shù)據(jù)
調(diào)用delegate方法: peripheralManager: didAddService: error:
//開始廣告
- (void)startAdvertise {
[self.peripheralManager startAdvertising:@{CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]}];
}
//停止廣告
- (void)stopAdvertise {
[self.peripheralManager stopAdvertising];
}
開始廣告
advertisementData: 可選字典,包含想要廣告的數(shù)據(jù)。兩種類型:
- CBAdvertisementDataLocalNameKey :對(duì)應(yīng)名稱
- CBAdvertisementDataServiceUUIDsKey : 對(duì)應(yīng)UUID
調(diào)用delegate方法:peripheralManagerDidStartAdvertising: error:
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
NSLog(@"當(dāng)前Characteristic被訂閱");
}
當(dāng)characteristic配置為notify或indicate,將喚起次方法。
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic {
NSLog(@"Central unsubscribed from characteristic");
}
當(dāng)central移除特征的notification/indications時(shí)調(diào)用,取消訂閱回調(diào)。
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests {
}
當(dāng)接收到中心端的讀寫請(qǐng)求式,會(huì)觸發(fā)這個(gè)方法。
在該方法被調(diào)用時(shí),可以在方法內(nèi)通過PeripheralManager調(diào)用:respondToRequest: withResult:
來響應(yīng)中心端的讀寫請(qǐng)求。
plist文件中,設(shè)置UIBackgroundModes:
- bluetooth-central
- bluetooth-peripheral
當(dāng)設(shè)置為此模式,允許APP切入后臺(tái)后還能進(jìn)行藍(lán)牙服務(wù)。依然能進(jìn)行掃描,連接,交互數(shù)據(jù)等。
進(jìn)入后臺(tái)CBCentralManagerScanOptionAllowDuplicatesKey
掃描被忽略。
當(dāng)設(shè)置為此模式,允許APP進(jìn)行讀寫,連接中心端等。CBAdvertisementDataLocalNameKey
被忽略,本地外設(shè)名不在廣播。
PeripheralManager
#import "LQPeripheralManager.h"
#import <CoreBluetooth/CoreBluetooth.h>
static NSString *const ServiceUUID1 = @"FFF0";
static NSString *const notifyCharacteristicUUID = @"FFF1";
static NSString *const readwriteCharacteristicUUID = @"FFF2";
static NSString *const ServiceUUID2 = @"FFE0";
static NSString *const readCharacteristicUUID = @"FFE1";
static NSString *const LocalNameKey = @"Owenli";
@interface LQPeripheralManager ()<CBPeripheralManagerDelegate>
@property (nonatomic, strong) CBPeripheralManager *peripheralManager;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger index;
@end
@implementation LQPeripheralManager
+ (instancetype)shareInstance {
static LQPeripheralManager *peripheral;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
peripheral = [[self alloc] init];
});
return peripheral;
}
- (instancetype)init {
if (self = [super init]) {
_peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
_index = 0;
}
return self;
}
/**
* @Description 初始化化UUID和服務(wù)信息
*/
- (void)setup {
//characteristic字段描述
CBUUID *cbuuidCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
/*
可以通知的Characteristic
properities : CBCharacteristicPropertyNotify
permissions : CBAttributePermissionsReadable
*/
CBMutableCharacteristic *notifyCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:notifyCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
/*
可讀寫的characteristic
prperitise: CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead
permisssions : CBAttributePermissionsReadable | CBAttributePermisssionWriteable
*/
CBMutableCharacteristic * readwriteCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:readwriteCharacteristicUUID] properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
// 設(shè)置descriptor
CBMutableDescriptor *readwriteCharacteristicDescription1 = [[CBMutableDescriptor alloc] initWithType:cbuuidCharacteristicUserDescriptionStringUUID value:@"name"];
[readwriteCharacteristic setDescriptors:@[readwriteCharacteristicDescription1]];
/*
只讀Characteristic
properties: CBCharacteristicPropertyRead
permisssions: CBAttributePermissionsReadable
*/
CBMutableCharacteristic *readCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:readCharacteristicUUID] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];
// 第一個(gè)Service
CBMutableService *service1 = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:ServiceUUID1] primary:YES];
[service1 setCharacteristics:@[notifyCharacteristic, readwriteCharacteristic]];
//第二個(gè)Service
CBMutableService *service2 = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:ServiceUUID2] primary:YES];
[service2 setCharacteristics:@[readCharacteristic]];
//添加到periperal此時(shí)會(huì)調(diào)用,peripheralManager: didAddService: error:
[self.peripheralManager addService:service2];
[self.peripheralManager addService:service1];
}
#pragma mark - PeripherManagerDelegate
//檢測藍(lán)牙狀態(tài),
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
switch (peripheral.state) {
case CBManagerStatePoweredOn:
//初始化
[self setup];
break;
case CBManagerStatePoweredOff:
NSLog(@"powered off");
break;
default:
break;
}
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"%@", error.localizedDescription);
return;
}
//添加服務(wù)后,開始廣播
//自動(dòng)回調(diào): peripheralManagerDidStartAdvertising: error:
[self.peripheralManager startAdvertising:@{
CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:ServiceUUID1], [CBUUID UUIDWithString:ServiceUUID2]],
CBAdvertisementDataLocalNameKey : LocalNameKey
}];
}
//通知發(fā)送廣播
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error {
if (error) {
NSLog(@"%@", error.localizedDescription);
}
NSLog(@"start advert");
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
NSLog(@"subscribe data of : %@", characteristic.UUID);
//分配定時(shí)任務(wù)
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendData:) userInfo:characteristic repeats:YES];
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic {
NSLog(@"unsubscrible: %@", characteristic.UUID);
[self.timer invalidate];
}
- (void)sendData:(NSTimer *)timer {
CBMutableCharacteristic *characteristic = timer.userInfo;
if ([self.peripheralManager updateValue:[[NSString stringWithFormat:@"send data : %ld", _index] dataUsingEncoding: NSUTF8StringEncoding] forCharacteristic:characteristic onSubscribedCentrals:nil]) {
NSLog(@"發(fā)送成功");
_index ++;
} else {
NSLog(@"發(fā)送數(shù)據(jù)錯(cuò)誤");
}
}
//中心設(shè)備讀取請(qǐng)求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
NSLog(@"readRequest");
if (request.characteristic.properties & CBCharacteristicPropertyRead) {
NSData *data = [[NSString stringWithFormat:@"by characteristic request"] dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:data];
//對(duì)請(qǐng)求作出成功響應(yīng)
[self.peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
} else {
[self.peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
}
}
//寫入請(qǐng)求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests {
NSLog(@"writeRequest");
CBATTRequest *request = requests.firstObject;
if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
CBMutableCharacteristic *charateristic = (CBMutableCharacteristic *)request.characteristic;
charateristic.value = request.value;
NSLog(@"receive data :%@", [[NSString alloc] initWithData:charateristic.value encoding:NSUTF8StringEncoding]);
[self.peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
} else {
[self.peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
}
}
- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral {
NSLog(@"peripheralManagerIsReadyToUpdateSubscribers");
}
@end
使用LighBlue測試外設(shè)端
命令行生成UUID
方法:uuidgen
。
Mac測試軟件:LighBlue,可以用來測試iOS端外設(shè)。
本文題目:iOS開發(fā),Bluetooth你應(yīng)該了解一些!
本文鏈接:http://aaarwkj.com/article6/gihiig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計(jì)、微信小程序、手機(jī)網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)