前言:最近项目中用到了蓝牙和公司硬件通信,所以入手研究了一下相关知识,特此记录下.
利用CoreBlueTooth解决蓝牙通信前提是硬件外设需是蓝牙4.0及其以上规格设备.
@property (nonatomic, strong) CBPeripheral *peripheralBLE; //外设
@property (nonatomic, strong) CBCentralManager *centralBLE; //中心管理者
@property (nonatomic, strong) CBCharacteristic *characteristicBLE; //外设特征
#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;