本文介紹了Apple 公司提供的 CoreBluetooth 框架中的藍牙編程流程。
閱讀后推薦閱讀:iOS低功耗藍牙BLE編程實戰
藍牙中心模式流程:
一、創建 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 來區分
如果覺得本文有趣或者實用,請點擊“喜歡”鼓勵下作者哦
當然也接受打賞鼓勵咯 :)