Just My Life & My Work

[iOS] 低功耗藍芽連線流程

最近寫iOS App要跟低功耗藍芽連線,接著傳輸資料解碼後來分析。兩年前有碰藍芽體脂計,是看著韌體溝通協議來實作,兩年後的今天再一次依樣畫葫蘆,這次要搞的硬體是24小時配戴的「玩意兒」。

bluetooth peripheral service characteristics

感謝網路上已有許多教學,學習藍芽只要拾人「芽」慧,就能快速上手!

底下是iOS SDK內建的API,熟悉之後對於實作就能了然於心!首先來看一下藍芽傳輸時各個角色:

bluetooth Central Peripheral

藍芽中心模式流程:

一、建立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 來區分。

如果上述條列式還不是很清楚,那就來看流程圖吧~

ble-workflow-chart.png

參考:

 

廣告

隨意留個言吧:)~

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

標籤雲

%d 位部落客按了讚: