蓝牙开发简介

概念

蓝牙开发主要用的Core Bluetooth 框架你的 Mac/iOS app 能够与低功耗蓝牙设备进行通讯。例如,你的app能够搜寻,探索低功耗蓝牙设备,并与之互动,如心率监听器,数字恒温器,甚至能够与其它iOS设备进行交互。

开发分类

1.中心设备开发(设备作为中央设备,对外围进行扫描连接,目前iOS开发中都是使用中心设备开发)
2.外设开发(设备作为一种外围设备,对周围进行广播,使周围知道外设的存在,目前iOS开发中比较少见)

当2个iPhone手机需要蓝牙4.0进行通讯时(比如通过蓝牙4.0进行数据交互时),在开发中必须一端需要是中心设备,一端则是外设

蓝牙开发简介_第1张图片
lanya.jpg

将外围设备(心率探测装置)的心率数据传送给中心设备(手机)时, 数据是经过两层包装的

  • 第一层是Service(服务), 可以是一个或多个, 如心率传感器和血压传感器
  • 第二层是Characteristic(特征), 他提供了更多关于Service(服务)的数据, 例如心率传感器(服务)中包含了两个数据, 分别是心率数据和身体位置数据, 这两个就是心率传感器(服务)的具体数据(特征)


    蓝牙开发简介_第2张图片
    waiwei.jpg

外围设备开发步骤

  • 建立外设管理器(CBPeripheralManager)
  • 创建服务(Service)和特征(Characteristic)
  • 外设管理器开始广播
  • 实现外设代理方法,处理读写及订阅
蓝牙开发简介_第3张图片
w.jpg
1. 建立外设管理器
- (void)viewDidLoad {
    [super viewDidLoad];
    // 1. 建立外设管理器(CBPeripheralManager)
    _pheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
2. 创建服务(Service)和特征并广播
#define SERVICE_UUID            @"581E9834-7C2D-4F64-9DFE-72ABD2B1E578"
#define CHARACTERISTIC_UUID     @"5C1CD210-DB0E-45FB-A8B2-3FCA8E4031E0"
在终端通过输入uuidgen来随机生成

// 状态被更新时回调
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    /*
     CBManagerStateUnknown = 0,     未知
     CBManagerStateResetting,       重置中
     CBManagerStateUnsupported,     不支持
     CBManagerStateUnauthorized,    未授权
     CBManagerStatePoweredOff,      关闭中
     CBManagerStatePoweredOn,       开启中
     */
    //设备处于开启状态
    if (peripheral.state == CBManagerStatePoweredOn) {
        
        // 2. 创建服务与特征
        [self createService];
        
        // 3. 开始广播
        [_pheralManager startAdvertising:@{CBAdvertisementDataLocalNameKey : @[[CBUUID UUIDWithString:SERVICE_UUID]]}];
    }
}

- (void)createService {
    // 2.1 创建服务
    CBUUID *serviceUUID = [CBUUID UUIDWithString:SERVICE_UUID];
    
    CBMutableService *service = [[CBMutableService alloc] initWithType:serviceUUID primary:YES];
    
    // 2.2 创建特征(可读可写)
    CBUUID *characteristicUUID = [CBUUID UUIDWithString:CHARACTERISTIC_UUID];

    CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic alloc] initWithType:characteristicUUID properties:CBCharacteristicPropertyRead | CBCharacteristicPropertyWrite value:nil permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
    
    // 2.3 将特征添加至服务中
    service.characteristics = @[characteristic];
    
    // 2.4 添加服务到外设中
    [_pheralManager addService:service];
}
3. 实现外设代理方法,处理读写及订阅
//中心设备向外设读取数据
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
    
    //将数据给中心设备
    request.value = [self.textField.text dataUsingEncoding:NSUTF8StringEncoding];
    
    //响应读取的操作(读取成功)
    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
}

////中心设备向外设写入数据
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests {
    
    //获取设备请求对象
    CBATTRequest *request = requests.lastObject;
    
    self.textField.text = [[NSString alloc] initWithData:request.value encoding:NSUTF8StringEncoding];
}

中心设备开发步骤

  • 建立中心设备管理器(CBCentralManager)
  • 扫描外设(Peripheral)
  • 连接外设
  • 扫描外设中的服务与特征
  • 利用外设与特征做数据交互
  • 断开连接
蓝牙开发简介_第4张图片
z.jpg
1. 建立中心设备
- (void)viewDidLoad {
    [super viewDidLoad];
    //1. 建立中心设备
    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
2. 扫描外设(CBCentralManagerDelegate代理方法)
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
    if (central.state == CBManagerStatePoweredOn) {
        // 2. 扫描外设
        [_centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:SERVICE_UUID]] options:nil];
    }
}
3. 连接外设
//当扫描到设备时回调
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    
    //_peripheral需要强引用
    _peripheral = peripheral;
    _peripheral.delegate = self;
    
    // 3. 连接到外设
    [_centralManager connectPeripheral:peripheral options:nil];
}
4. 对外设进行扫描并发现服务与特征
//当外设与中心设备连接成功回调
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    // 4.对外设进行扫描
    [peripheral discoverServices:@[[CBUUID UUIDWithString:SERVICE_UUID]]];
}
#pragma mark - CBPeripheralDelegate

// 外设发现服务回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error{
    
    for (CBService *service in peripheral.services) {
        //4. 1对外设扫描到的服务进行特征扫描
        [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:CHARACTERISTIC_UUID]] forService:service];
    }
}
// 外设发现特征回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {

    // 4.2 记录特征
    _characteristic = service.characteristics.lastObject;
}
5. 利用外设与特征做数据交互
// 当特征的值发生变化时回调
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    
    self.textField.text = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
}

#pragma mark - action
// 外设向中心设备发送数据(发送数据Button)
- (IBAction)sendData:(id)sender {
    
    [_peripheral writeValue:[self.textField.text dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_characteristic type:CBCharacteristicWriteWithResponse];
}
// 外设读取中心设备数据(接收数据Button)
- (IBAction)readData:(id)sender {
    
    [_peripheral readValueForCharacteristic:_characteristic];
}
6. 断开连接
// 中心设备断开连接(断开连接Button)
- (IBAction)disConnect:(id)sender {
    [_centralManager cancelPeripheralConnection:_peripheral];
}

// 断开时重新连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
    [_centralManager connectPeripheral:peripheral options:nil];
}

你可能感兴趣的:(蓝牙开发简介)