CoreBlueTooth 蓝牙开发相关总结

前言:最近项目中用到了蓝牙和公司硬件通信,所以入手研究了一下相关知识,特此记录下.


利用CoreBlueTooth解决蓝牙通信前提是硬件外设需是蓝牙4.0及其以上规格设备.

@property (nonatomic, strong) CBPeripheral *peripheralBLE;   //外设
@property (nonatomic, strong) CBCentralManager *centralBLE;  //中心管理者
@property (nonatomic, strong) CBCharacteristic *characteristicBLE;  //外设特征

以上是蓝牙主要属性.一般来说我们的手机作为中心管理者,同时硬件设备作为外设.程序在确定使用蓝牙时初始化manager.
#pragma mark 初始化蓝牙
- (CBCentralManager *)centralBLE{
    if (!_centralBLE) {
        _centralBLE = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    return _centralBLE;
}
这就会触发 CBCentralManagerDelegate 相关代理方法.

- (void)centralManagerDidUpdateState:(CBCentralManager *)central ;//用来判断手机蓝牙状态

在确保手机蓝牙打开状态下搜索外设:


[self.centralBLE scanForPeripheralsWithServices:nil
                                                    options:nil];

在发现相关外设时会调用相关方法,我们需要做的是根据自己的实际业务需求来判断连接相关外设并设置

CBPeripheralDelegate委托代理.

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

    NSLog(@"外设名字%@---信号强度%@",peripheral.name,RSSI);

    if ( [peripheral.name hasSuffix:self.imei]) {


        self.peripheralBLE = peripheral;
        [self.centralBLE connectPeripheral:peripheral options:nil];
        [self.centralBLE stopScan];
    }
}

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

    NSLog(@"链接成功%@",peripheral);

    self.peripheralBLE.delegate = self;
    [self.peripheralBLE discoverServices:nil];
}

对链接失败及断开连接也相应做些反应

//链接外设失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{

}
//断开外设链接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{}

在外设中发现相关服务:

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error;

应在相应的服务中寻找满足需求的特征

    for (CBService *s in peripheral.services) {
        [peripheral discoverCharacteristics:nil forService:s];
    }

在发现相关特征后执行以下方法

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

应在提供的特征中找到具体服务并执行相应操作:


    if([service.UUID isEqual:[CBUUID UUIDWithString:@"FFE0"]]){
        self.characteristicBLE = service.characteristics[0];

        [self.peripheralBLE setNotifyValue:YES forCharacteristic:self.characteristicBLE];

        self.label.text = @"已连接设备";
    }
其中收取数据及发送数据如下:


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



 - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;



你可能感兴趣的:(IOS随笔札记)