由于最近咨询蓝牙问题的较多,所以在此总结一下!马尾哥的第一个完整项目就是蓝牙与外设交互的项目!考虑到功耗的因素现在市场上普遍使用--蓝牙BLE4.0,接下来我们介绍的也是4.0版本。
扣扣:137026391 欢迎交流!
//CBCentralManager的几种状态typedef NS_ENUM(NSInteger, CBCentralManagerState) {// 初始的时候是未知的(刚刚创建的时候)CBCentralManagerStateUnknown = 0,//正在重置状态CBCentralManagerStateResetting,//设备不支持的状态CBCentralManagerStateUnsupported,// 设备未授权状态CBCentralManagerStateUnauthorized,//设备关闭状态CBCentralManagerStatePoweredOff,// 设备关闭状态 --不 可用状态CBCentralManagerStatePoweredOn,};// 设备开启状态 -- 可用状态
直接上代码:
#import "ZSXKMainPageViewController.h"
#import "AppDelegate.h"#import "OBShapedButton.h"
#import@interface ZSXKMainPageViewController ()
// 中心管理设备
@property (nonatomic, strong) CBCentralManager *cManager;
// 保存外设设备
@property (nonatomic, strong) CBPeripheral *peripheral;
#pragma mark - lazy---初始化中心管理者并设置代理
- (CBCentralManager *)cManager
{
if (!_cManager) {
_cManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
return _cManager;
}
// 中心管理者状态改变时调用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
switch (central.state) {
case CBCentralManagerStateUnknown:
XKLog(@">>>CBCentralManagerStateUnknown");
break;
case CBCentralManagerStateResetting:
XKLog(@">>>CBCentralManagerStateResetting设备不支持的状态");
break;
case CBCentralManagerStateUnsupported:
XKLog(@">>>CBCentralManagerStateUnsupported设备未授权状态");
break;
case CBCentralManagerStateUnauthorized:
XKLog(@">>>CBCentralManagerStateUnauthorized设备关闭状态");
break;
case CBCentralManagerStatePoweredOff:
XKLog(@">>>CBCentralManagerStatePoweredOff设备g状态");
break;
case CBCentralManagerStatePoweredOn:
XKLog(@">>>CBCentralManagerStatePoweredOn设备开启状态 -- 可用状态");
// 开始扫描周围的外设 第一个参数nil就是扫描周围所有的外设
// 扫描到外设后会进入 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
[self.cManager scanForPeripheralsWithServices:nil options:nil];
break;
default:
break;
}
}
// 扫描到设备会进入此代理方法- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary*)advertisementData RSSI:(NSNumber *)RSSI
{
XKLog(@"%s, line = %d, per外设为 = %@, data = %@, rssi信号强度 = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);
// 连接设备 设置连接规则
if ([peripheral.name isEqualToString:@"kai"] && (RSSI.integerValue > 30)) {
// 保存外设
self.peripheral = peripheral;
[self.cManager connectPeripheral:self.peripheral options:nil];
// 连接成功,失败,断开会进入各自的代理方法
// - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功
// - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败
// - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设
}else
{
XKLog(@"没扫描到 >>>>>>>> %s, line = %d", __FUNCTION__, __LINE__);
}
}
// 外设连接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
XKLog(@"%s, line = %d", __FUNCTION__, __LINE__);
XKLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
//设置peripheral代理
[peripheral setDelegate:self];
//扫描外设Services 成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
[peripheral discoverServices:nil];
}
// 外设连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}
// 断开连接(丢失连接)
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}
#pragma mark - CBPeripheralDelegate
// 发现外设的service
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
if (error)
{
XKLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
return;
}
for (CBService *service in peripheral.services) {
XKLog(@"service.UUID = %@", service.UUID);
//扫描每个service的Characteristics 扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
[peripheral discoverCharacteristics:nil forService:service];
}
}
// 外设发现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;
}
//获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
XKLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
[peripheral readValueForCharacteristic:characteristic]; // 外设读取特征的值
}
//搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外设发现特征的描述
}
}
// 获取characteristic的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
// 打印出characteristic的UUID和值
// value的类型是NSData,根据外设协议制定的方式解析数据
XKLog(@"%s, line = %d, characteristic.UUID:%@ value:%@", __FUNCTION__, __LINE__, characteristic.UUID, characteristic.value);
}
// 获取Characteristics的 descriptor的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
{
//打印出DescriptorsUUID 和value
//这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
XKLog(@"%s, line = %d, descriptor.UUID:%@ value:%@", __FUNCTION__, __LINE__, descriptor.UUID, descriptor.value);
}
// 发现特征Characteristics的描述Descriptor
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
XKLog(@"%s, line = %d", __FUNCTION__, __LINE__);
for (CBDescriptor *descriptor in characteristic.descriptors)
{
XKLog(@"descriptor.UUID:%@",descriptor.UUID);
}
}
// 将数据写入特征
- (void)xk_peripheral:(CBPeripheral *)peripheral writeData:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic
{
/*
typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
CBCharacteristicPropertyBroadcast = 0x01,
CBCharacteristicPropertyRead = 0x02,
CBCharacteristicPropertyWriteWithoutResponse = 0x04,
CBCharacteristicPropertyWrite = 0x08,
CBCharacteristicPropertyNotify = 0x10,
CBCharacteristicPropertyIndicate = 0x20,
CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,
CBCharacteristicPropertyExtendedProperties = 0x80,
CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x100,
CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x200
};
打印出特征的权限(characteristic.properties),可以看到有很多种,这是一个NS_OPTIONS的枚举,可以是多个值
常见read,write,noitfy,indicate.前俩是读写权限,后俩都是通知,俩不同的通知方式
*/
XKLog(@"%s, line = %d, characteristic.properties:%lu", __FUNCTION__, __LINE__, (unsigned long)characteristic.properties);
// 只有特征的properties中有写的属性时候,才写
if (characteristic.properties & CBCharacteristicPropertyWrite) {
// 这句才是正宗的核心代码
[peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
}
// 订阅特征的通知
// 设置通知
- (void)xk_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
// 设置通知, 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
// 取消通知
- (void)xk_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
}
// 断开连接
- (void)xk_cMgr:(CBCentralManager *)cMgr stopScanAndDisConnectWithPeripheral:(CBPeripheral *)peripheral
{
// 停止扫描
[cMgr stopScan];
// 断开连接
[cMgr cancelPeripheralConnection:peripheral];
}
@end