iOS 蓝牙开发之(CoreBlueTooth)

CoreBlueTooth

简介:

可用于第三方的蓝牙交互设备 设备必须支持蓝牙4.0

iPhone的设备必须是4S或者更新

iPad设备必须是iPad mini或者更新

iOS的系统必须是iOS 6或者更新

蓝牙4.0以低功耗著称,所以一般被称为BLE(bluetooth low energy)

核心概念

CBCenterManager:中心设备(用来连接到外部设备的管家)

CBPeripheralManager:外部设备(第三方的蓝牙4.0设备 用来扫描服务和服务特征)

开发步骤

1.建立中心管家

#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
//中心管家
@property (nonatomic,strong) CBCentralManager *manager;
//存储扫描到的外部设备
@property (nonatomic,strong) CBPeripheral *peripheral;

@end
/*
 1.建立中心管家
 2.扫描外部设备
 3.连接外部设备
 4.扫描服务和特征
 5.数据交互
 6.断开连接
 */
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //建立中心管家 queue 填空 默认为主线程
    CBCentralManager *manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    self.manager = manager;
}

2.扫描外设

//在代理方法中扫描外部设备
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    //在开机状态下才能扫描外部设备
    if (central.state == CBManagerStatePoweredOn) {
        //扫描外部设备的哪些服务
        //scanForPeripheralsWithServices 传空的话 可以扫描外部所有可以发现的设备 否则只扫描传入的相应ID的设备
        [self.manager scanForPeripheralsWithServices:nil options:nil];
    }
}

3.连接外设

//已经找到了外部设备 连接外部设备 我们也可以保存这些外部设备到一个数组 这里不做操作 也可以在这里对外部设备进行筛选
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    
    NSLog(@"peripheral = %@",peripheral);
    //保存外部设备
    self.peripheral = peripheral;
    self.peripheral.delegate = self;
    //连接外部设备 
    [self.manager connectPeripheral:peripheral options:nil];
}

外设连接成功

//已经连接到了外部设备  开始扫描该设备服务
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    //扫描设备的服务 调用CBPeripheralDelegate
    [self.peripheral discoverServices:nil];
}

4.扫描外设服务和特征

每个蓝牙4.0的设备都是通过服务和特征来展示自己的,一个设备必然包含一个或多个服务 一个服务包含一个或多个特征。

#pragma mark - CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    //扫描到的服务
    NSLog(@"扫描到的服务:%@",peripheral.services);
    
    
    for (CBService *service in peripheral.services) {
        //由于有很多服务 我们可以去特定的服务 做特定的功能
//        if ([service.UUID.UUIDString isEqualToString:@"Battery"]) {
//            [self.peripheral discoverCharacteristics:nil forService:service];
//        }
        //扫描服务特征
        [self.peripheral discoverCharacteristics:nil forService:service];
    }
}

发现服务对应的特征

/**
 *  发现服务对应的特征
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    // 服务对应的特征
    NSArray *ctcs = service.characteristics;
    // 遍历所有的特征
    for (CBCharacteristic *character in ctcs) {
        // 根据特征的唯一标示过滤
        if ([character.UUID.UUIDString isEqualToString:@"XMG"]) {
            NSLog(@"可以吃饭了");
        }
    }
}

特征描述

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"descriptor = %@",characteristic.descriptors);
    for (CBDescriptor *descriptor in characteristic.descriptors) {
        //读取特征描述
        [self.peripheral readValueForDescriptor:descriptor];
    }
}

5.与外设做数据的交互 读或写

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"更新特征值%@时发生错误:%@", characteristic.UUID, [error localizedDescription]);
        return;
    }
// 收到数据
    [delegate didGetDataForString:[self hexadecimalString:characteristic.value]];
//    NSLog(@"%@",[self hexadecimalString:characteristic.value]);
}

数据的转换

我们接收到的数据,正是characteristic.value,这是一个NSData类数据,我们可以通过UTF8StringEncoding来转化为NSString,为了代码结构清晰,我专门把NSData和NSString互转写成了两个方法:

//将传入的NSData类型转换成NSString并返回
- (NSString*)hexadecimalString:(NSData *)data{
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return result;
}
//将传入的NSString类型转换成NSData并返回
- (NSData*)dataWithHexstring:(NSString *)hexstring{
    NSData *aData;
    return aData = [hexstring dataUsingEncoding: NSASCIIStringEncoding];
}

写的比较基础,另附大神写的比较全面的蓝牙博客地址

http://liuyanwei.jumppo.com/2015/07/17/ios-BLE-0.html

 

posted @ 2017-03-17 17:01  幻影-2000  阅读(332)  评论(0编辑  收藏  举报