標籤:
iOS的藍芽用到了 CoreBluetooth 架構
首先匯入架構
#import <CoreBluetooth/CoreBluetooth.h>
我們需要一個管理者來管理藍牙裝置,CBCentralManager
首先建立管理者
self.manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil];
這裡只需要設定一個代理,隊列根據需求來選擇,這裡用了nil 就是預設在主線程。options是篩選裝置的條件。
建立完管理者後 會執行代理方法
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
可以查看manager的一個屬性 : state 來識別藍芽的狀態 ,該屬性是一個枚舉值 CBCentralManagerState
typedef NS_ENUM(NSInteger, CBCentralManagerState) {
CBCentralManagerStateUnknown = 0, 初始的時候是未知的(剛剛建立的時候)
CBCentralManagerStateResetting, 正在重設狀態
CBCentralManagerStateUnsupported, 裝置不支援的狀態
CBCentralManagerStateUnauthorized, 裝置未授權狀態
CBCentralManagerStatePoweredOff, 裝置關閉狀態
CBCentralManagerStatePoweredOn, 裝置開啟狀態 -- 可用狀態
};
如果是處於 CBCentralManagerStatePoweredOn 狀態,那麼就可以開始搜尋裝置 [self.manager scanForPeripheralsWithServices:nil options:nil];
可以設定一個計時器 在一段時間後停止搜尋,避免耗電 [self.manager stopScan];
如果搜尋到了裝置,那麼會調用代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
其中 peripheral是搜尋到的裝置,advertisementData是關於裝置的一些資訊,RSSI是裝置的訊號強度
可以根據 advertisementData 裡面的 kCBAdvDataServiceUUIDs 的值 UUID來篩選某種裝置
搜尋到裝置後就可以進行串連了,藍芽4.0支援一對多串連。
串連裝置 [self.manager connectPeripheral:peripheral options:nil];
串連成功後 會執行代理方法
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
如果需要斷開某個裝置,則調用方法 [self.manager cancelPeripheralConnection:peripheral];
裝置不管是自己斷開還是手動斷開,都會調用代理方法
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
在這裡可以判斷一下,如果不是手動斷開的串連,則可以再串連斷開的裝置,實現斷開裝置自動連接的功能
CBCentralManager就是用來做以上這些事情的,要給裝置發送資料和接受資料 則要用到 CBPeripheral
首先設定裝置的代理
peripheral.delegate = self;
然後開始搜尋裝置服務 [peripheral discoverServices:nil];
搜尋成功後會執行代理方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
在這裡 裝置的 services 屬性裡面就有裝置服務的資料了,可以遍曆這個數組來匹配到我們需要的服務,這個一般跟硬體廠商協商,這裡我們假如需要UUID為FF00的服務
如果成功匹配到服務,那麼調用方法 [peripheral discoverCharacteristics:nil forService:s];
成功後會執行代理方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
在這個方法裡面,服務的屬性 characteristics ,會是一組的 CBCharacteristic,是服務的一些特徵,在這裡,我們假設發送資料需要用到特徵的UUID為 FF02
發送的資料為 550504010101AA,我們將其轉換為 NSData 類型 調用方法 [peripheral writeValue:data forCharacteristic:c type:CBCharacteristicWriteWithoutResponse] 將資料發送給裝置
發送成功後會執行代理方法
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
如果是讀取裝置的資料 那麼使用方法 [peripheral readValueForCharacteristic:c] ,讀取資料後會執行代理方法
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
這就簡單的完成了藍芽4.0
這是我的第一篇部落格,也是初步接觸到藍芽,寫的有點亂,有問題的可以來互相討論。
如果有要轉載的請 註明出處。
iOS藍芽4.0