iOS開發(fā) 藍牙技術

藍牙是開發(fā)中常用的功能。通過手機APP與硬件設備連接,進而操作硬件,在開發(fā)中越來越常見。

藍牙的理論知識可自行從網上搜索,此處只介紹如何在項目中通過代碼集成藍牙功能。

集成藍牙SDK時,用到的是iOS自帶的SDK,在pch文件或者是用到藍牙的某個類(此處小編假設用到藍牙的是自定義的BlueTooth類)的頭部引入:

#import <CoreBluetooth/CoreBluetooth.h>

在BlueTooth類中聲明一下屬性

@property (nonatomic, strong) CBCentralManager *manager;//藍牙的中心管理者

@property (nonatomic, strong) CBPeripheral *peripheral;

@property (strong ,nonatomic) CBCharacteristic *writeCharacteristic;//藍牙的寫特征

@property (nonatomic,strong) CBCharacteristic *readCharacteristic;//藍牙的讀特征

@property (nonatomic,strong) CBCharacteristic *vedioCharacteristic;

@property (nonatomic,strong) CBCharacteristic *batteryCharacteristic;//藍牙的電池特征,可以檢測電池電量

@property (nonatomic,strong) CBCharacteristic *stateCharacteristic;//藍牙的狀態(tài)特征,檢測是否連接

@property (strong,nonatomic) NSMutableArray *nDevices;//搜索到的所有藍牙設備

@property (strong,nonatomic) NSMutableArray *nServices;//當前匹配的藍牙設備的所有服務

@property (strong,nonatomic) NSMutableArray *nCharacteristics;//當前匹配的藍牙設備的所有特征

在BlueTooth類中加入藍牙代理

<CBCentralManagerDelegate,CBPeripheralDelegate>

在BlueTooth類的viewDidLoad方法中初始化:

_manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

_nDevices = [[NSMutableArray alloc]init];?

_nServices = [[NSMutableArray alloc]init];

_nCharacteristics = [[NSMutableArray alloc]init];

點擊頁面的某個button,點擊方法中開始掃描周圍的藍牙設備:

[_manager scanForPeripheralsWithServices:nil options:nil];

#pragma mark 查到外設后,停止掃描,連接設備

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{


? ? NSLog(@"已發(fā)現(xiàn) peripheral: %@ ---%@--rssi: %@,---UUID: %@ --advertisementData: %@ ", peripheral, peripheral.name,RSSI, peripheral.identifier, advertisementData);

? ? [peripheral setDelegate:self];

? ? [peripheral discoverServices:nil];

? ? NSString *blueName = peripheral.name;

? ? if([你要查找的設備名稱 isEqualToString:blueName]){

? ? ? ? ? ? self.peripheral = peripheral;//找到需要的外設,并賦值

? ? ? ? ? ? [_manager connectPeripheral:_peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey : @YES }];

? ? ? ? ? ? [self.manager stopScan];

? ? ? ? }else{

????????????//如果查到的設備名稱不是你需要的,繼續(xù)查找

? ? ? ? }

? ? ? ? BOOL replace = NO;

? ? ? ? // Match if we have this device from before

? ? ? ? //搜索到的藍牙,在設備數(shù)組遍歷,如果曾經沒有連接過這個藍牙,就添加,如果鏈接過,則替換

? ? ? ? for (int i=0; i < _nDevices.count; i++) {

? ? ? ? ? ? CBPeripheral *p = [_nDevices objectAtIndex:i];

????????????if ([p isEqual:peripheral]) {

????????????????[_nDevices replaceObjectAtIndex:i withObject:peripheral];

? ? ? ? ? ? ? ? replace = YES;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? if (!replace) {

? ? ? ? ? ? [_nDevices addObject:peripheral];

? ? ? ? }

? ? }

}

//連接外設失敗

-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{

? ? NSLog(@"鏈接外設失敗%@",error);

}

#pragma mark 連接外設后的處理

//連接外設成功,開始發(fā)現(xiàn)服務

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {

?? ?[self.peripheral setDelegate:self];

? ? [self.peripheral discoverServices:nil];

? ? NSLog(@"掃描服務");

}

#pragma mark 發(fā)現(xiàn)服務和搜索到的Characteristice

//已發(fā)現(xiàn)服務

-(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

? ? NSLog(@"發(fā)現(xiàn)服務!");

? ? int i = 0;

? ? for(CBService* s in peripheral.services){

? ? ? ? [self.nServices addObject:s];

? ? }

? ? for(CBService* s in peripheral.services){

?????????//NSLog(@"%d :服務 UUID: %@(%@)", i, s.UUID.data, s.UUID);

? ? ? ? i++;

? ? ? ? [peripheral discoverCharacteristics:nil forService:s];

? ? ? ? //NSLog(@"掃描Characteristics...");

? ? }

}

#pragma mark? 已搜索到Characteristics

-(void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{

? ? for(CBCharacteristic* c in service.characteristics){

? ? ? ? [peripheral readValueForCharacteristic:c];

? ? ? ? //NSLog(@"特征 UUID:? %@-- %@-- (%@)", c,c.UUID.data, c.UUID);

? ? ? ? [peripheral setNotifyValue:YES forCharacteristic:c];

? ? ? ? if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]]){ //寫

? ? ? ? ? ? self.writeCharacteristic = c;

? ? ? ? ? ? [peripheral readValueForCharacteristic:c];

? ? ? ? }else if([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]]){//讀

? ? ? ? ? ? self.readCharacteristic = c;

? ? ? ? ? ? [peripheral readValueForCharacteristic:c];

? ? ? ? }else if ([c.UUID isEqual:[CBUUID UUIDWithString:@"2a19"]]){//電池電量

? ? ? ? ? ? self.batteryCharacteristic = c;

? ? ? ? }

? ? ? ? uint8_t val[c.value.length];

? ? ? ? [c.value getBytes:val length:c.value.length];

? ? ? ? if([c.UUID.UUIDString isEqualToString:@"FFF6"]){

? ? ? ? ? ? self.stateCharacteristic = c;

? ? ? ? ? ? [peripheral readValueForCharacteristic:c];

? ? ? ? ? ? [peripheral setNotifyValue:YES forCharacteristic:c];

? ? ? ? }

? ? }

}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {

? ? NSLog(@"已斷開與設備:[%@]的連接",peripheral.name);

}

//獲取外設發(fā)來的數(shù)據(jù),不論是read和notify,獲取數(shù)據(jù)都是從這個方法中讀取。

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

? ? NSData *data = characteristic.value;

? ? NSString* value = [self hexadecimalString:data];

? ? if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]]) {

? ? }else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2a19"]]){//電池

? ? ? ? NSData *data = characteristic.value;

? ? ? ? NSString *value = [self hexadecimalString:data];

? ? ? ? NSString * temp10 = [NSString stringWithFormat:@"%lu",strtoul([value UTF8String],0,16)];

? ? ? ? //NSLog(@"電池----%@",temp10);

? ? }else{

? ? ? ? //NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

? ? ? ? //NSLog(@"其他的特征值--%@",value);

? ? }

}

當你找到了相應的藍牙設備,并且需要向藍牙設備發(fā)送數(shù)據(jù)的時候,調用以下方法。

if (characteristic.properties & CBCharacteristicPropertyWrite) {

? ? ? ? // 寫入數(shù)據(jù)

? ? ? ? [peripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];

? ? }

以上是集成藍牙的全部代碼,不明白的可以留言。具體的操作還需要iOS開發(fā)人員和公司的硬件工程師進行配合。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容