蓝牙基础知识
蓝牙库
当前iOS中的蓝牙开发使用的都是系统自带的蓝牙库<CoreBluetooth/CoreBluetooth.h>
蓝牙设备版本要求
蓝牙设备必须是4.0或者以上
CoreBluetooth框架的核心
CoreBluetooth框架中的核心是peripheral和central, 它们分别表示外设和中心,设备上可以认为手机就是中心, 蓝牙设备就是外设
服务和特征
蓝牙设备它有若干个服务service,每个服务里面有包含若干个特征characteristic,特征就是提供数据的地方
外设, 服务, 特征间的关系
![](https://img.haomeiwen.com/i25331915/5634fd0e37deca75.png)
CoreBluetooth框架的架构
![](https://img.haomeiwen.com/i25331915/ffff87bb1d7ebe25.png)
连接蓝牙的具体实现
实现流程
1.建立中心角色
2.扫描外设
3.连接外设
4.获取外设中的服务和特征
5.与外设做交互
实现步骤
1.导入CoreBluetooth头文件,添加代理,建立中心角色
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (strong, nonatomic) CBCentralManager *centralManager; //蓝牙管理者
@property(strong,nonatomic)CBPeripheral *peripheral; //存储匹配成功的外设
-(void)viewDidLoad {
[super viewDidLoad];
//初始化,最后一个线程参数可以为nil,默认是main线程
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
复制代码
2.扫描外设
/*
1.初始化成功会自动调用
2.必须实现的代理,返回centralManager的状态
3.只有在状态为CBManagerStatePoweredOn的情况下才可以开始扫描外设
*/
-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
switch (central.state) {
case CBManagerStateUnknown:
NSLog(@">>>未知");
break;
case CBManagerStateResetting:
NSLog(@">>>重置");
break;
case CBManagerStateUnsupported:
NSLog(@">>>设备不支持");
break;
case CBManagerStateUnauthorized:
NSLog(@">>>设备未授权");
break;
case CBManagerStatePoweredOff:
{
NSLog(@">>>设备关闭");
self.bleStatusBlock(NO);
}
break;
case CBManagerStatePoweredOn:
{
NSLog(@">>>设备打开");
//开始扫描外设, 然后会进入didDiscoverPeripheral方法
/*
1\. 两个参数为nil表示默认扫描所有可见的蓝牙设备
2\. 第一个参数用来设置扫描有指定服务的外设
3\. 第二个参数用来设置是否重复扫描已经发现的设备
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
Bool值为Yes,表示重复扫描, 反之表示不会重复扫描
*/
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
}
break;
default:
break;
}
}
复制代码
连接外设
//扫描到的设备可以在这个方法里面打印
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI {
NSLog(@">>>advertisementData :%@ name :%@ ",advertisementData,peripheral.name);
//有些产品是根据Mac地址来进行配对, 在这里我们就可以拿到,具体什么规则, 根据各个蓝牙设备来定
NSData *data = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"];
//解析
//.....
if(自己的判断) {
//找到的设备必须持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!!
self.peripheral = peripheral;
//停止扫描
[self.centralManager stopScan];
//连接外设
[_centralManager connectPeripheral:peripheral options:nil];
}
}
//连接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
}
//连接到Peripherals-失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
}
//Peripherals断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);
}
复制代码
获取外设中的服务和特征
//连接外设成功
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
peripheral.delegate=self;//这个方法调用发现服务协议
[peripheral discoverServices:nil];
}
//扫描到服务
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
NSLog(@">>>扫描到服务:%@",peripheral.services);
if (error) {
NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
return;
}
for (CBService *service in [peripheral services]){
[peripheral discoverCharacteristics:nil forService:service];
}
}
//扫描到特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
return;
}
for (CBCharacteristic *characteristic in service.characteristics) {
NSLog(@">>>服务:%@ 的 特征: %@",service.UUID,characteristic.UUID);
//筛选你需要的UUID,进行连接
if ([characteristic.UUID isEqual:yourUUID) {
订阅,实时接收
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}
复制代码
读取数据
//获取指定特性的数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
//接收蓝牙发来的数据
NSLog(@"characteristic uuid:%@ value:%@",characteristic.UUID,characteristic.value);
}
复制代码
写入数据
//写入数据
-(void)writeData {
[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}
//写入数据的回调
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
if (error) {
NSLog(@"error Discovered characteristics for %@ with error: %@", characteristic.UUID, [error localizedDescription]);
return;
}
NSLog(@"characteristic uuid:%@ value:%@",characteristic.UUID,characteristic.value);
}
复制代码
断开连接
- (void)disConnect{
[self.centralManager cancelPeripheralConnection:self.peripheral];
}
收录:原文地址
网友评论