藍(lán)牙BLE(上)---iOS---外設(shè)設(shè)備汽車(chē)

由于最近咨詢藍(lán)牙問(wèn)題的較多,所以在此總結(jié)一下!馬尾哥的第一個(gè)完整項(xiàng)目就是藍(lán)牙與外設(shè)交互的項(xiàng)目!考慮到功耗的因素現(xiàn)在市場(chǎng)上普遍使用--藍(lán)牙BLE4.0,接下來(lái)我們介紹的也是4.0版本。

扣扣:137026391 ? ? ? ? ? ? ? ? ? ? ? ? ? 歡迎交流!


//CBCentralManager的幾種狀態(tài)typedef NS_ENUM(NSInteger, CBCentralManagerState) {// 初始的時(shí)候是未知的(剛剛創(chuàng)建的時(shí)候)CBCentralManagerStateUnknown = 0,//正在重置狀態(tài)CBCentralManagerStateResetting,//設(shè)備不支持的狀態(tài)CBCentralManagerStateUnsupported,// 設(shè)備未授權(quán)狀態(tài)CBCentralManagerStateUnauthorized,//設(shè)備關(guān)閉狀態(tài)CBCentralManagerStatePoweredOff,// 設(shè)備關(guān)閉狀態(tài) --不 可用狀態(tài)CBCentralManagerStatePoweredOn,};// 設(shè)備開(kāi)啟狀態(tài) -- 可用狀態(tài)

直接上代碼:

#import "ZSXKMainPageViewController.h"

#import "AppDelegate.h"#import "OBShapedButton.h"

#import@interface ZSXKMainPageViewController ()

// 中心管理設(shè)備

@property (nonatomic, strong) CBCentralManager *cManager;

// 保存外設(shè)設(shè)備

@property (nonatomic, strong) CBPeripheral *peripheral;



#pragma mark - lazy---初始化中心管理者并設(shè)置代理

- (CBCentralManager *)cManager

{

if (!_cManager) {

_cManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];

}

return _cManager;

}


// 中心管理者狀態(tài)改變時(shí)調(diào)用

- (void)centralManagerDidUpdateState:(CBCentralManager *)central

{

switch (central.state) {

case CBCentralManagerStateUnknown:

XKLog(@">>>CBCentralManagerStateUnknown");

break;

case CBCentralManagerStateResetting:

XKLog(@">>>CBCentralManagerStateResetting設(shè)備不支持的狀態(tài)");

break;

case CBCentralManagerStateUnsupported:

XKLog(@">>>CBCentralManagerStateUnsupported設(shè)備未授權(quán)狀態(tài)");

break;

case CBCentralManagerStateUnauthorized:

XKLog(@">>>CBCentralManagerStateUnauthorized設(shè)備關(guān)閉狀態(tài)");

break;

case CBCentralManagerStatePoweredOff:

XKLog(@">>>CBCentralManagerStatePoweredOff設(shè)備g狀態(tài)");

break;

case CBCentralManagerStatePoweredOn:

XKLog(@">>>CBCentralManagerStatePoweredOn設(shè)備開(kāi)啟狀態(tài) -- 可用狀態(tài)");

// 開(kāi)始掃描周?chē)耐庠O(shè) 第一個(gè)參數(shù)nil就是掃描周?chē)械耐庠O(shè)

// 掃描到外設(shè)后會(huì)進(jìn)入 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;

[self.cManager scanForPeripheralsWithServices:nil options:nil];

break;

default:

break;

}

}

// 掃描到設(shè)備會(huì)進(jìn)入此代理方法- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary*)advertisementData RSSI:(NSNumber *)RSSI

{

XKLog(@"%s, line = %d, per外設(shè)為 = %@, data = %@, rssi信號(hào)強(qiáng)度 = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);

// 連接設(shè)備 設(shè)置連接規(guī)則

if ([peripheral.name isEqualToString:@"kai"] && (RSSI.integerValue > 30)) {

// 保存外設(shè)

self.peripheral = peripheral;

[self.cManager connectPeripheral:self.peripheral options:nil];

// 連接成功,失敗,斷開(kāi)會(huì)進(jìn)入各自的代理方法

// - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)成功

// - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設(shè)連接失敗

// - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//斷開(kāi)外設(shè)

}else

{

XKLog(@"沒(méi)掃描到 >>>>>>>>? %s, line = %d", __FUNCTION__, __LINE__);

}

}

// 外設(shè)連接成功

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

{

XKLog(@"%s, line = %d", __FUNCTION__, __LINE__);

XKLog(@">>>連接到名稱為(%@)的設(shè)備-成功",peripheral.name);

//設(shè)置peripheral代理

[peripheral setDelegate:self];

//掃描外設(shè)Services 成功后會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

[peripheral discoverServices:nil];

}


// 外設(shè)連接失敗

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

{

NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);

}

// 斷開(kāi)連接(丟失連接)

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

{

NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);

}

#pragma mark - CBPeripheralDelegate

// 發(fā)現(xiàn)外設(shè)的service

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

{

if (error)

{

XKLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);

return;

}

for (CBService *service in peripheral.services) {

XKLog(@"service.UUID = %@", service.UUID);

//掃描每個(gè)service的Characteristics 掃描到后會(huì)進(jìn)入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

[peripheral discoverCharacteristics:nil forService:service];

}

}

// 外設(shè)發(fā)現(xiàn)service的特征

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

{

if (error)

{

NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);

return;

}

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

for (CBCharacteristic *characteristic in service.characteristics){

XKLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);

[peripheral readValueForCharacteristic:characteristic]; // 外設(shè)讀取特征的值

}

//搜索Characteristic的Descriptors,讀到數(shù)據(jù)會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

for (CBCharacteristic *characteristic in service.characteristics){

[peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外設(shè)發(fā)現(xiàn)特征的描述

}

}

// 獲取characteristic的值

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

{

// 打印出characteristic的UUID和值

// value的類型是NSData,根據(jù)外設(shè)協(xié)議制定的方式解析數(shù)據(jù)

XKLog(@"%s, line = %d, characteristic.UUID:%@? value:%@", __FUNCTION__, __LINE__, characteristic.UUID, characteristic.value);

}

// 獲取Characteristics的 descriptor的值

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error

{

//打印出DescriptorsUUID 和value

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

XKLog(@"%s, line = %d, descriptor.UUID:%@ value:%@", __FUNCTION__, __LINE__, descriptor.UUID, descriptor.value);

}

// 發(fā)現(xiàn)特征Characteristics的描述Descriptor

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

{

XKLog(@"%s, line = %d", __FUNCTION__, __LINE__);

for (CBDescriptor *descriptor in characteristic.descriptors)

{

XKLog(@"descriptor.UUID:%@",descriptor.UUID);

}

}

// 將數(shù)據(jù)寫(xiě)入特征

- (void)xk_peripheral:(CBPeripheral *)peripheral writeData:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic

{

/*

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

};

打印出特征的權(quán)限(characteristic.properties),可以看到有很多種,這是一個(gè)NS_OPTIONS的枚舉,可以是多個(gè)值

常見(jiàn)read,write,noitfy,indicate.前倆是讀寫(xiě)權(quán)限,后倆都是通知,倆不同的通知方式

*/

XKLog(@"%s, line = %d, characteristic.properties:%lu", __FUNCTION__, __LINE__, (unsigned long)characteristic.properties);

// 只有特征的properties中有寫(xiě)的屬性時(shí)候,才寫(xiě)

if (characteristic.properties & CBCharacteristicPropertyWrite) {

// 這句才是正宗的核心代碼

[peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];

}

}

// 訂閱特征的通知

// 設(shè)置通知

- (void)xk_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic

{

// 設(shè)置通知, 數(shù)據(jù)會(huì)進(jìn)入 peripheral:didUpdateValueForCharacteristic:error:方法

[peripheral setNotifyValue:YES forCharacteristic:characteristic];

}

// 取消通知

- (void)xk_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic

{

[peripheral setNotifyValue:NO forCharacteristic:characteristic];

}

// 斷開(kāi)連接

- (void)xk_cMgr:(CBCentralManager *)cMgr stopScanAndDisConnectWithPeripheral:(CBPeripheral *)peripheral

{

// 停止掃描

[cMgr stopScan];

// 斷開(kāi)連接

[cMgr cancelPeripheralConnection:peripheral];

}

@end

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

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

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