iOS 蓝牙开发和注意点
前言
- 藍牙傳輸所用的框架是<CoreBluetooth/CoreBluetooth.h>
- 藍牙連接需要中心管理者和外部設備,我們所做的開發基本是圍繞中心管理來的;
- 藍牙設備發過來的每個數據包,為了保證數據在傳輸的時候沒有丟失,一般需要包頭,包尾,校驗和
- 有很多藍牙協議很復雜,需要把數據轉化成二進制進行轉化解析,對于高字節,低字節,小端模式,大端模式,符號位,位運算這些基本概念需要了解清楚
1.關于Mac地址的獲取
自iOS7之后,蘋果不支持獲取Mac地址,只能用UUID來標識設備,要注意的是同一個設備在不同手機上顯示的UUID不相同,但有的設備可以通過 “180A”這個服務來發現特征,再來讀取 “2A23”這個特征值,可以獲得Mac地址。如果你的藍牙設備不支持這樣獲取,你可以跟硬件工程師溝通,來獲得Mac地址,添加一個獲取地址命令或者增加一個含地址的特征值都可以很容易的獲取。上面獲取地址的前提都是需要先建立連接,如果一定要在掃描的時候獲得Mac地址,讓硬件工程師把數據寫入廣播包里,看是否可行;
2.藍牙連接流程
如果你不是新手,又不想浪費時間,請直接看第三點 注意點,核心部分
- 建立中心設備管理者
- 掃描外設
- 連接外設
- 掃描外設中的服務
- 掃描外設中的特征
- 訂閱或讀取特征值
- 獲取外設中的數據
建立中心設備管理者
// 創建之后會馬上檢查藍牙的狀態,nil默認為主線程 self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil]藍牙線程沒必要去開異步線程,在主線程消耗不了什么性能
掃描外設
// 藍牙狀態發生改變,這個方法一定要實現 - (void)centralManagerDidUpdateState:(CBCentralManager *)central {// 藍牙狀態可用if (central.state == CBCentralManagerStatePoweredOn) {// 如果藍牙支持后臺模式,一定要指定服務,否則在后臺斷開連接不上,如果不支持,可設為nil, option里的CBCentralManagerScanOptionAllowDuplicatesKey默認為NO, 如果設置為YES,允許搜索到重名,會很耗電[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:nil];} }連接外設
/*** 發現設備* @param peripheral 設備* @param advertisementData 廣播內容* @param RSSI 信號強度*/ - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {// 判斷是否是你需要連接的設備if ([peripheral.name isEqualToString:kPeripheralName]) {peripheral.delegate = self;// 一定要記得把外設保存起來self.selectedPeripheral = peripheral;// 開始連接設備[self.centralManager connectPeripheral:self.selectedPeripheral options:nil];} }掃描外設中的服務
/*** 已經連接上設備*/ - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {// 停止掃描[self.centralManager stopScan];// 發現服務[self.selectedPeripheral discoverServices:nil]; }掃描外設中的特征
/*** 已經發現服務*/ - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {for (CBService *service in peripheral.services) {if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {// 根據你要的那個服務去發現特性[self.selectedPeripheral discoverCharacteristics:nil forService:service];}// 這里我是根據 180A 用來獲取Mac地址,沒什么實際作用,可刪掉if ([service.UUID isEqual:[CBUUID UUIDWithString:@"180A"]]) {[self.selectedPeripheral discoverCharacteristics:nil forService:service];}} }訂閱或讀取特征值
/*** 已經發現特性*/ - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {for (CBCharacteristic *characteristic in service.characteristics) {if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A23"]]) {// 這里是讀取Mac地址, 可不要, 數據固定, 用readValueForCharacteristic, 不用setNotifyValue:setNotifyValue[self.selectedPeripheral readValueForCharacteristic:characteristic];}if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {// 訂閱特性,當數據頻繁改變時,一般用它, 不用readValueForCharacteristic[peripheral setNotifyValue:YES forCharacteristic:characteristic];// 獲取電池電量unsigned char send[4] = {0x5d, 0x08, 0x01, 0x3b};NSData *sendData = [NSData dataWithBytes:send length:4];// 這里的type類型有兩種 CBCharacteristicWriteWithResponse CBCharacteristicWriteWithoutResponse,它的屬性枚舉可以組合[self.selectedPeripheral writeValue:sendData forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];/*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};*/NSLog(@"%@",characteristic);// 打印結果為 <CBCharacteristic: 0x1702a2a00, UUID = FFF6, properties = 0x16, value = (null), notifying = NO>// 我的結果 為 0x16 (0x08 & 0x16)結果不成立, (0x04 & 0x16)結果成立,那寫入類型就是 CBCharacteristicPropertyWriteWithoutResponse}} }獲取外設中的數據
/*** 數據更新的回調*/ - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {// 這里收到的數據都是16進制,有兩種轉換,一種就直接轉字符串,另一種是轉byte數組,看用哪種方便// 直接轉字符串NSString *orStr = characteristic.value.description;NSString *str = [orStr substringWithRange:NSMakeRange(1, orStr.length - 2)];NSString *dataStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""];NSLog(@"dataStr = %@",dataStr);// 轉Byte數組Byte *byte = (Byte *)characteristic.value.bytes;//_______________________________________________________________________________________________________________// 解析你的協議,附幾個解協議或許能用到的函數 }設備連接斷開
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {// 讓它自動重連[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:nil]; }這是系統代理方法,如果要主動斷開需要調用 - (void)cancelPeripheralConnection:(CBPeripheral *)peripheral; 這個方法
寫入數據成功的回調
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {// 讀取數據[self.selectedPeripheral readValueForCharacteristic:characteristic]; }如果類型是CBCharacteristicWriteWithoutResponse,不會走這個方法;
3.注意點,核心部分,請仔細看
做藍牙前一定要去商城下個LightBlue,一個設備有很多服務,服務中又有很多特性,特性中又分讀的,寫的等,有了LightBlue,你可以很快的找到你需要的特性;
LightBlue截圖
從上圖中我們可以清晰的看到每個服務中又多少個特性,特性的屬性Read、Write、Write Without Response、Notify等也標明的很清楚,
一般的藍牙都要支持重連和后臺運行,如果掃描設備的時候,用這個方法- (void)scanForPeripheralsWithServices:options:沒有指定特定的服務,而是用nil代替,設備在后臺斷開的時候是不會重連的;
藍牙是可以同時連接多個外部設備
關于readValueForCharacteristic和 setNotifyValue:forCharacteristic: 的區別, readValueForCharacteristic適合用來讀取數據不怎么更新的特征值, 如果獲取的數據是經常更新的,那就 一定要用setNotifyValue:forCharacteristic:來訂閱這個特征;
當我們寫入命令時writeValue:forCharacteristic:type:,這個type類型到時是用CBCharacteristicWriteWithResponse還是用CBCharacteristicWriteWithoutResponse會有疑惑,先看一下特性屬性的枚舉,它們是可以組合的
/*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};再來看看我打印的兩個特征值,第一個是獲取Mac地址的特性,另一個是獲取數據的特性
<CBCharacteristic: 0x1700b8ae0, UUID = System ID, properties = 0x2, value = (null), notifying = NO>
<CBCharacteristic: 0x1702a2a00, UUID = FFF6, properties = 0x16, value = (null), notifying = NO>
第一個0x2對應只可讀, 第二個 (0x16 & 0x08)不成立,(0x16 & 0x04)成立,所以用CBCharacteristicWriteWithoutResponse,而且這個特征值還可讀,可以通知
代理方法- (void)centralManagerDidUpdateState:(CBCentralManager *)central;一定要調用,否則會報錯,這個方法只要設置中心設備的代理之后,就一定會走,我們最開始的掃描外設應放在這個方法里;
對于是否要單獨創建一個工具類來獲取藍牙數據,如果只是一個界面需要用到藍牙數據,我覺得完全沒必要,如果是多個界面的話,最好還是創建一個工具類。
如果藍牙支持要支持后臺模式,只需要去把藍牙后臺模式打開
后臺運行藍牙
記住只要勾選Uses Bluetooth LE accessories就行了,別勾選Acts As a Bluetooth LE accessory,除非你把你的手機當做外部設備使用;
簡單又詳細的Demo地址
作者:alenpaulkevin
鏈接:http://www.jianshu.com/p/0ccfd53fc559
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
轉載于:https://www.cnblogs.com/Ghosgt/p/7779463.html
總結
以上是生活随笔為你收集整理的iOS 蓝牙开发和注意点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Spring boot] Spring
- 下一篇: 关于mysql的ddl_log.log文