最近寫iOS App要跟低功耗藍芽連線,接著傳輸資料解碼後來分析。兩年前有碰藍芽體脂計,是看著韌體溝通協議來實作,兩年後的今天再一次依樣畫葫蘆,這次要搞的硬體是24小時配戴的「玩意兒」。
感謝網路上已有許多教學,學習藍芽只要拾人「芽」慧,就能快速上手!
底下是iOS SDK內建的API,熟悉之後對於實作就能了然於心!首先來看一下藍芽傳輸時各個角色:
藍芽中心模式流程:
一、建立CBCentralManager 中心對象
二、central掃描外設discover
三、central連接外設connect
四、掃描外設中的服務和特徵discover
4.1、獲取外設的services:
* 執行:discoverServices
* 成功後執行:peripheral:didDiscoverServices
委託方法
4.2、獲取外設的Characteristics,獲取Characteristics 的值:
* 執行:discoverCharacteristics:forService
* 成功後執行:peripheral:didDiscoverCharacteristicsForService:error
委託方法
4.3、獲取外設的Characteristics 的Descriptor 和Descriptor 的值:
* 讀特徵值:readValueForCharacteristic
* 讀到後進入:didUpdateValueForCharacteristic:error委託方法
* 搜索Characteristic:discoverDescriptorsForCharacteristic
* 搜到後進入:didDiscoverDescriptorsForCharacteristic:error委託方法
* 獲取到Descriptors 的值:peripheral:didUpdateValueForDescriptor:error
Descriptors 是對characteristic 的描述,一般是字符串
4.4、把資料寫到Characteristic:writeCharacteristic:charactericstic:value
4.5、讀RSSI,用通知的方式訂閱資料等。
五、與外設做資料交互explored interact
六、訂閱Characteristic 的通知:notifyCharacteristic:characteristic
取消通知:cancelNotifyCharacteristic:characteristic
七、斷開連接disconnect:disconnnectPeripheral:peripheral
藍芽外設模式流程:
一、創建一個Peripheral 管理對象。
peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
* 藍芽設備打開成功後會進入委託方法:peripheralManagerDidUpdateState:
二、本地Peripheral 設置服務、特性、描述、權限等。
* 創建Characteristics 及其description,創建service,把characteristics 添加到service 中,再把service 添加到peripheralManager 中。
三、Peripheral 發送廣播advertising:peripheralManagerDidStartAdvertising:error
* Peripheral 添加service:peripheralManager:didAddService:error
四、對central 的操作進行響應
* 讀characteristics 請求:peripheralManager:didReceiveReadQuest:
* 寫characteristics 請求:peripheralManager:didReceiveWriteRequests:
* 訂閱特徵:peripheralManager:central:didSubscribeToCharacteristic:
* 取消訂閱:peripheralManager:central:didUnsubscribeFromCharacteristic:
一些基本屬性:
* RSSI:信號強弱值,可用在粗估距離。
* UUID:唯一標識符,可用於區別設備。
* service UUID:服務,一個Server 會包含多個characteristic,會用UUID 來區分。
* characteristic UUID:特徵,會用UUID 來區分。
如果上述條列式還不是很清楚,那就來看流程圖吧~
參考:
- iOS低功耗藍牙BLE 編程代理方法流程
- iOS低功耗藍牙BLE編程實戰
- Introduction to CoreBluetooth in iOS: Creating a group chat room
隨意留個言吧:)~