蓝牙是开发中常用的功能。通过手机APP与硬件设备连接,进而操作硬件,在开发中越来越常见。
蓝牙的理论知识可自行从网上搜索,此处只介绍如何在项目中通过代码集成蓝牙功能。
集成蓝牙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;//蓝牙的状态特征,检测是否连接
@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(@"已发现 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{
//如果查到的设备名称不是你需要的,继续查找
}
BOOL replace = NO;
// Match if we have this device from before
//搜索到的蓝牙,在设备数组遍历,如果曾经没有连接过这个蓝牙,就添加,如果链接过,则替换
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 连接外设后的处理
//连接外设成功,开始发现服务
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
[self.peripheral setDelegate:self];
[self.peripheral discoverServices:nil];
NSLog(@"扫描服务");
}
#pragma mark 发现服务和搜索到的Characteristice
//已发现服务
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
NSLog(@"发现服务!");
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);
}
//获取外设发来的数据,不论是read和notify,获取数据都是从这个方法中读取。
- (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);
}
}
当你找到了相应的蓝牙设备,并且需要向蓝牙设备发送数据的时候,调用以下方法。
if (characteristic.properties & CBCharacteristicPropertyWrite) {
// 写入数据
[peripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
}
以上是集成蓝牙的全部代码,不明白的可以留言。具体的操作还需要iOS开发人员和公司的硬件工程师进行配合。
网友评论