(一)CoreBluetooth iOS 藍牙 “中心模式”

使用Corebluetooth框架進行藍牙開發,有兩種模式:一種是中心模式,另一種是外設模式。
中心模式
分爲以下幾步:
1.建立中心設備 2.掃描外部設備 3.連接外部設備 4.掃描外部設備的服務和特徵 5.利用外部設備的特徵與外部設備手法數據

一、首先導入框架 CoreBluetooth/CoreBluetooth.h
創建中心設備並設置代理
CBCentralManager *manager = [CBCentralManager alloc]init];
一旦設置代理,在程序運行的時候就會調用協議方法
- (void)centralManagerDidUpdateState:(CBCentralManager*)central ;
- 這個方法是判斷中心設備是否打開藍牙設備

二、利用中心設備掃描外部設備
[manager scanForPeripheralsWithServices: option:];
第一個參數表示掃描帶有相關服務的外部設備,例如填寫@[[CBUUID UUIDWithString:@”需要連接的外部設備的服務的UUID”]] nil 表示掃描全部設備
options @{CBCentralManagerScanOptionAllowDuplicatesKey : YES}
一旦掃描到有外部設備
- centalManager:(CBCentraManager*)centralManager didDiscoverPeripheral:() advertisementData:(NSDictionary*)
- 在這個協議裏,我們可以根據我們獲取到的硬件的某些條件進行篩選,然後連接我們需要連接的外部設備,例如連接名字帶有”*“的外部設備
- if(peripheral.namehasPrefix:@”*“){
連接設備
manager connectPeripheral:peripheral options:nil];
}
-(void)peripheral: didDiscoverCharacteristicsForService: error: ;

5、掃描到特徵之後,我們就可以拿到特徵進行讀寫操作
例如進行讀取數據的操作:
if([characteristic.UUID.UUIDStringisEqualToString:@”“]){
peripheral readValueForCharacteristic:characteristic];
}
只要讀取了就會進入另一個協議方法

-(void)peripheral: didUpdateValueForCharacteristic:
在這個方法裏我們就拿到了我們需要的數據,進行寫的操作是:
peripheral writeValue: forCharacteristic: type:

每寫一次數據就會進入

-(void)peripheral: didWriteValueForCharacteristc: error:

這個方法會告訴我們,寫操作成功與否
外設模式請查看:
http://blog.csdn.net/flover5724059/article/details/73521754

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章