藍牙BLE(上)---iOS---外設設備汽車

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

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


//CBCentralManager的幾種狀態typedef NS_ENUM(NSInteger, CBCentralManagerState) {// 初始的時候是未知的(剛剛創建的時候)CBCentralManagerStateUnknown = 0,//正在重置狀態CBCentralManagerStateResetting,//設備不支持的狀態CBCentralManagerStateUnsupported,// 設備未授權狀態CBCentralManagerStateUnauthorized,//設備關閉狀態CBCentralManagerStatePoweredOff,// 設備關閉狀態 --不 可用狀態CBCentralManagerStatePoweredOn,};// 設備開啟狀態 -- 可用狀態

直接上代碼:

#import "ZSXKMainPageViewController.h"

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

#import@interface ZSXKMainPageViewController ()

// 中心管理設備

@property (nonatomic, strong) CBCentralManager *cManager;

// 保存外設設備

@property (nonatomic, strong) CBPeripheral *peripheral;



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

- (CBCentralManager *)cManager

{

if (!_cManager) {

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

}

return _cManager;

}


// 中心管理者狀態改變時調用

- (void)centralManagerDidUpdateState:(CBCentralManager *)central

{

switch (central.state) {

case CBCentralManagerStateUnknown:

XKLog(@">>>CBCentralManagerStateUnknown");

break;

case CBCentralManagerStateResetting:

XKLog(@">>>CBCentralManagerStateResetting設備不支持的狀態");

break;

case CBCentralManagerStateUnsupported:

XKLog(@">>>CBCentralManagerStateUnsupported設備未授權狀態");

break;

case CBCentralManagerStateUnauthorized:

XKLog(@">>>CBCentralManagerStateUnauthorized設備關閉狀態");

break;

case CBCentralManagerStatePoweredOff:

XKLog(@">>>CBCentralManagerStatePoweredOff設備g狀態");

break;

case CBCentralManagerStatePoweredOn:

XKLog(@">>>CBCentralManagerStatePoweredOn設備開啟狀態 -- 可用狀態");

// 開始掃描周圍的外設 第一個參數nil就是掃描周圍所有的外設

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

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

break;

default:

break;

}

}

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

{

XKLog(@"%s, line = %d, per外設為 = %@, data = %@, rssi信號強度 = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);

// 連接設備 設置連接規則

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

// 保存外設

self.peripheral = peripheral;

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

// 連接成功,失敗,斷開會進入各自的代理方法

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

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

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

}else

{

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

}

}

// 外設連接成功

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

{

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

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

//設置peripheral代理

[peripheral setDelegate:self];

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

[peripheral discoverServices:nil];

}


// 外設連接失敗

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

{

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

}

// 斷開連接(丟失連接)

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

{

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

}

#pragma mark - CBPeripheralDelegate

// 發現外設的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);

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

[peripheral discoverCharacteristics:nil forService:service];

}

}

// 外設發現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的值,讀到數據會進入方法:-(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]; // 外設讀取特征的值

}

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

for (CBCharacteristic *characteristic in service.characteristics){

[peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外設發現特征的描述

}

}

// 獲取characteristic的值

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

{

// 打印出characteristic的UUID和值

// value的類型是NSData,根據外設協議制定的方式解析數據

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

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

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

}

// 發現特征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);

}

}

// 將數據寫入特征

- (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

};

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

常見read,write,noitfy,indicate.前倆是讀寫權限,后倆都是通知,倆不同的通知方式

*/

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

// 只有特征的properties中有寫的屬性時候,才寫

if (characteristic.properties & CBCharacteristicPropertyWrite) {

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

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

}

}

// 訂閱特征的通知

// 設置通知

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

{

// 設置通知, 數據會進入 peripheral:didUpdateValueForCharacteristic:error:方法

[peripheral setNotifyValue:YES forCharacteristic:characteristic];

}

// 取消通知

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

{

[peripheral setNotifyValue:NO forCharacteristic:characteristic];

}

// 斷開連接

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

{

// 停止掃描

[cMgr stopScan];

// 斷開連接

[cMgr cancelPeripheralConnection:peripheral];

}

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容