baseK(相关基础知识)
蓝牙常见名称和缩写
- BLE:(Bluetooth low energy)蓝牙4.0设备因为低耗电,也叫BLE
- peripheral,central:外设和中心设备,发起链接的是central(一般是指手机),被链接的设备是peripheral(运动手环)
- service and characteristic:(服务和特征)每个设备会提供服务和特征,类似于服务端的API,但是结构不同.
每个设备会有很多服务
,每个服务中包含很多字段
,这些字段的权限一般分为读(read),写(write),通知(notify)几种,就是我们连接设备后具体需要操作的内容 - Description:每个characteristic可以对应一个或者多个Description用于描述characteristic的信息或属性(eg.范围,计量单位)
蓝牙基础知识
-
CoreBluetooth框架的核心其实是俩东西:peripheral和central,对应他们分别有一组相关的API和类
-
这两组api粉笔对应不同的业务常见:左侧叫中心模式,就是以你的app作为中心,连接其他的外设的场景;而右侧称为外设模式,使用
手机作为外设
连接其他中心设备操作的场景 -
服务和特征(service and characteristic)
- 每个设备都会有1个or多个服务
- 每个服务里都会有1个or多个特征
- 特征就是具体键值对,提供数据的地方
- 每个特征属性分为:读,写,通知等等
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
};
- 外设,服务,特征的关系
BLE中心模式流程
- 1.建立中心角色
- 2.扫描外设(Discover Peripheral)
- 3.连接外设(Connect Peripheral)
- 4.扫描外设中的服务和特征(Discover Services And Characteristics)
- 4.1 获取外设的services
- 4.2 获取外设的Characteristics,获取characteristics的值,,获取Characteristics的Descriptor和Descriptor的值
- 5.利用特征与外设做数据交互(Explore And Interact)
- 6.订阅Characteristic的通知
- 7.断开连接(Disconnect)
BLE外设模式流程
- 1.启动一个Peripheral管理对象
- 2.本地peripheral设置服务,特征,描述,权限等等
- 3.peripheral发送广告
- 4.设置处理订阅,取消订阅,读characteristic,写characteristic的代理方法
蓝牙设备的状态
- 1.待机状态(standby):设备没有传输和发送数据,并且没有连接到任何外设
- 2.广播状态(Advertiser):周期性广播状态
- 3.扫描状态(Scanner):主动搜索正在广播的设备
- 4.发起链接状态(Initiator):主动向扫描设备发起连接
- 5.主设备(Master):作为主设备连接到其它设备.
- 6.从设备(Slave):作为从设备链接到其它设备
蓝牙设备的五种工作状态
- 准备(Standby)
- 广播(Advertising)
- 监听扫描(Scanning)
- 发起连接(Initiating)
- 已连接(Connected)
蓝牙和版本使用限制
- 蓝牙2.0:越狱设备
- BLE:iOS6以上
- MFI认证设备:无限制
BLE测试
- 两台BLE设备
- 如何让iOS模拟器也能测试BLE?
- 买一个CSR蓝牙4.0 USB适配器,插在Mac上
- 在终端输入sudo nvram bluetoothHostControllerSwitchBehavior="never"
- 重启Mac
- 用Xcode4.6调试代码,将程序跑在iOS6.1模拟器上
- 苹果把iOS7.0模拟器对BLE的支持移除了
-
BLE中心模式流程-coding
BLE中心模式流程
- 1.建立中心角色
- 2.扫描外设(Discover Peripheral)
- 3.连接外设(Connect Peripheral)
- 4.扫描外设中的服务和特征(Discover Services And Characteristics)
- 4.1 获取外设的services
- 4.2 获取外设的Characteristics,获取characteristics的值,,获取Characteristics的Descriptor和Descriptor的值
- 5.利用特征与外设做数据交互(Explore And Interact)
- 6.订阅Characteristic的通知
- 7.断开连接(Disconnect)
准备环境
- 1.Xcode7.0
- 2.手机
- 3.外设(手机+LightBlue)
实现步骤
1.导入CB头文件,建立主设备管理类,设置主设备代理
#import <CoreBluetooth/CoreBluetooth.h> @interface XMGBLEController () <CBCentralManagerDelegate> @property (nonatomic, strong) CBCentralManager *cMgr; /**< 中心管理设备 */ @end @implementation XMGBLEController #pragma mark - 懒加载 // 1.建立中心管理者 - (CBCentralManager *)cMgr { if (!_cMgr) { NSLog(@"%s, line = %d", __FUNCTION__, __LINE__); /* 设置主设备的代理,CBCentralManagerDelegate 必须实现的: - (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主设备状态改变调用,在初始化CBCentralManager的适合会打开设备,只有当设备正确打开后才能使用 其他选择实现的委托中比较重要的: - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外设 - (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;//断开外设 */ _cMgr = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; // 线程不传默认是主线程 } return _cMgr; } - (void)viewDidLoad { [super viewDidLoad]; self.title = @"BLE"; self.view.backgroundColor = [UIColor orangeColor]; // 初始化 [self cMgr]; // 不能在此处扫描,因为状态还没变为打开 //[self.cMgr scanForPeripheralsWithServices:nil options:nil]; }
2.扫描外设
- 扫描的方法防治cMgr成功打开的代理方法中
- 只有设备成功打开,才能开始扫描,否则会报错
#pragma mark - CBCentralManagerDelegate // 中心管理者状态改变, 在初始化CBCentralManager的时候会打开设备,只有当设备正确打开后才能使用 - (void)centralManagerDidUpdateState:(CBCentralManager *)central { NSLog(@"%s, line = %d", __FUNCTION__, __LINE__); switch (central.state) { case CBCentralManagerStateUnknown: NSLog(@">>>CBCentralManagerStateUnknown"); break; case CBCentralManagerStateResetting: NSLog(@">>>CBCentralManagerStateResetting"); break; case CBCentralManagerStateUnsupported: NSLog(@">>>CBCentralManagerStateUnsupported"); break; case CBCentralManagerStateUnauthorized: NSLog(@">>>CBCentralManagerStateUnauthorized"); break; case CBCentralManagerStatePoweredOff: NSLog(@">>>CBCentralManagerStatePoweredOff"); break; case CBCentralManagerStatePoweredOn: NSLog(@">>>CBCentralManagerStatePoweredOn"); // 2.开始扫描周围的外设 /* 第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; */ [self.cMgr scanForPeripheralsWithServices:nil options:nil]; break; default: break; } } // 扫描到设备会进入到此代理方法 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI { NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI); // 接下来连接设备 }
3.连接外设
- 扫描手环,打印结果
- 根据打印结果
// 扫描到设备会进入到此代理方法 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI { NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI); // 3.接下来可以连接设备 //如果你没有设备,可以下载一个app叫lightbule的app去模拟一个设备 //这里自己去设置下连接规则,我设置的是二维码扫描到的运动手环的设备号 // 判断设备号是否扫描到 if ([peripheral.name isEqualToString:@"OBand-75"]) { /* 一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接,连接成功,失败,断开会进入各自的委托 - (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;//断开外设的委托 */ // 保存外设,否则方法结束就销毁 self.per = peripheral; [self.cMgr connectPeripheral:self.per options:nil]; }else { // 此处Alert提示未扫描到设备,重新扫描 #warning noCode NSLog(@"没扫描到 >>>>>>>> %s, line = %d", __FUNCTION__, __LINE__); } } // 外设连接成功 - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { NSLog(@"%s, line = %d", __FUNCTION__, __LINE__); NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name); } // 外设连接失败 - (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__); }
4.扫描外设中的服务和特征
设备链接成功后,就可以扫描设备的服务(services)了,同样是通过代理,扫描到结果后会触发某代理方法. 注意:此时CBCentralManagerDelegate已经不能满足需求,需要新的CBPeripheralDelegate来搞定. 该协议中包含了central与peripheral的许多回调方法 (eg.:获取services,获取characteristics,获取characteristics的值,获取characteristics的Descriptor以及Descriptor的值,写数据,读RSSI,用通知的方式订阅数据等等).
- 4.1 获取外设的services
- 首先设置外设的代理,并搜寻services
- 然后在代理方法
peripheral:didDiscoverServices:
中遍历services
// 外设连接成功 - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { NSLog(@"%s, line = %d", __FUNCTION__, __LINE__); NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name); //设置的peripheral代理CBPeripheralDelegate //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate> [peripheral setDelegate:self]; //扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{ [peripheral discoverServices:nil]; /* Discovers the specified services of the peripheral. An array of CBUUID objects that you are interested in. Here, each CBUUID object represents a UUID that identifies the type of service you want to discover. */ } #pragma mark - CBPeripheralDelegate // 发现外设的service - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { if (error) { NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]); return; } for (CBService *service in peripheral.services) { NSLog(@"service.UUID = %@", service.UUID); //扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error [peripheral discoverCharacteristics:nil forService:service]; } }
- 4.2 获取外设的characteris,获取Characteristics的值,获取Characteristics的Descriptor以及Descriptor的值
// 外设发现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:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID); } #warning noCodeFor 优化,分开写是为了让大家看注释清晰,并不符合编码规范 //获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error for (CBCharacteristic *characteristic in service.characteristics){ [peripheral readValueForCharacteristic:characteristi