iOS低功耗蓝牙BLE编程实战
最近有两个月没有更新博客了,主要是因为2015年12月,找了实习的工作。接下来将继续为大家提供工作和学习过程中的开发经验。
本人实习的是一家微型打印机制造企业,需要将数据从 iPhoe 通过蓝牙传输到打印机上打印。由于苹果的封闭生态,之前对蓝牙的�限制比较严格,如果要和 iOS 设备通信,必须是经过了 MFI 认证的芯片才可以。近年来可穿戴的智能设备的兴起和蓝牙4.0低功耗模式的到来,苹果也对蓝牙放开了一些限制。所以目前针对 iOS 的蓝牙编程主要就是针对蓝牙4.0以上的低功耗蓝牙,也就是 BLE 模式。
BLE 模式的特点:
- 功耗低。
- 连接速度很快,连接距离远(100米)。
- 相应的传输数据量小,比传统蓝牙传输的小很多,据说单次发送也就20字节。
综上,BLE 模式也就是适合用来做遥控,遥控一下 LED 灯,窗帘,智能电视之类。智能手环和手机的数据同步,防丢器之类的东西。BLE 模式并不适合用来做较大数据量的传输使用。用来传输一些文本信息还可以,但是如果要传输的是图片等较大数据量的�信息速度上就很感人了。
阅读前推荐阅读:iOS低功耗蓝牙 BLE 编程代理方法流程,先对代理流程有个大概的了解。
Bluetooth.h
@property(nonatomic,strong) CBCentralManager *centralManager;
@property(nonatomic,strong) CBPeripheral *peripheral;
@property(nonatomic,strong) CBCharacteristic *characteristic;
@property(nonatomic,strong) NSMutableArray *peripheralArray;
- (void)initBluetooth; //初始化蓝牙
- (void)scanBluetooth; //扫描蓝牙
- (void)stopScanBluetooth; //停止扫描
- (void)connectPeripheral:(CBPeripheral *)peripheral; //连接蓝牙
- (void)disConnectPeripheral:(CBPeripheral *)peripheral; //取消连接蓝牙
- (void)sendData:(NSData *)data; //向扫描到的蓝牙Characteristic 发送数据
Bluetooth.m
初始化蓝牙
- (void)initBluetooth
{
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];//创建CBCentralManager对象
_peripheralArray = [[NSMutableArray alloc] init];
}
扫描蓝牙
- (void)scanBluetooth
{
NSLog(@"BluetoothBase scanBluetooth");
//CBCentralManagerScanOptionAllowDuplicatesKey值为 No,表示不重复扫描已发现的设备
NSDictionary *optionDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
[_centralManager scanForPeripheralsWithServices:nil options:optionDic];//如果你将第一个参数设置为nil,Central Manager就会开始寻找所有的服务。
}
停止扫描
- (void)stopScanBluetooth
{
[self.centralManager stopScan];
NSLog(@"BluetoothBase stopScanBluetooth,已经连接外设停止扫描或者手动停止扫描");
}
连接蓝牙
- (void)connectPeripheral:(CBPeripheral *)peripheral
{
[self.centralManager connectPeripheral:peripheral options:nil];
self.peripheral = peripheral;
peripheral.delegate = self; //连接时设置代理
}
取消连接蓝牙
- (void)disConnectPeripheral:(CBPeripheral *)peripheral
{
[_centralManager cancelPeripheralConnection:peripheral];
}
向蓝牙写入数据:
如果发送的数据过大,就需要做分包处理了。至于传输的最大字节数是多大,就需要和硬件工程师讨论了。我测试的好像达到了单次发送1110字节数。
- (void)sendData:(NSData *)data
{
[self initBluetoothDispatch];
if (_characteristic.properties & CBCharacteristicPropertyWrite){
[_peripheral writeValue:data forCharacteristic:_characteristic type:CBCharacteristicWriteWithResponse];
NSLog(@"BluetoothBase writeDataToCharacteristic:%@",[_characteristic.UUID UUIDString]);
}else{
NSLog(@"没有发现可以写入的characteristic");
}
}
下面是蓝牙的一些代理方法(CBCentralManagerDelegate):
代理方法:centralManager已经更新状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
NSLog(@"centralManagerDidUpdateState:%ld",(long)central.state);
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:
[self scanBluetooth]; //很重要,当蓝牙处于打开状态,开始扫描。
break;
default:
NSLog(@"蓝牙未工作在正确状态");
break;
}
}
代理方法:centralManager已经发现外设
//扫描到外设,停止扫描,连接设备(每扫描到一个外设都会调用一次这个函数,若要展示搜索到的蓝牙,可以逐一保存 peripheral 并展示)
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
[_peripheralArray addObject:peripheral]; //保存用于连接的 peripheral
[PRTBluetoothModel share].peripheralArray = _peripheralArray;
[[NSNotificationCenter defaultCenter] postNotificationName:@"PRTBluetoothScanUpdatePeripheralList" object:nil];
}
代理方法:已经连接外设
//连接外设成功,扫描外设中的服务和特征
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
[PRTDispatchModel share].currentDispatchMode = PRTPrinterModeBle; //将蓝牙模式保存到当前传输模式。
NSLog(@"didConnectPeripheral:%@",peripheral.name);
[[NSNotificationCenter defaultCenter] postNotificationName:@"PRTBluetoothScanDidConnectPeripheral" object:nil];
[self stopScanBluetooth]; //连接成功后停止扫描
[self.peripheral setDelegate:self];
//数组中存放两个服务的 UUID
NSMutableArray *uuidArray = [[NSMutableArray alloc] initWithObjects:[CBUUID UUIDWithString:UUID_String_DeviceInfo_Service], [CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE], nil];
[peripheral discoverServices:uuidArray];//发现服务,成功后执行:peripheral:didDiscoverServices委托方法
}
代理方法:连接外设失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"didFailToConnectPeripheral:%@",error);
}
代理方法:已经发现服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
NSLog(@"didDiscoverServices:%@",peripheral.name);
if (error) {
NSLog(@"didDiscoverServices error:%@",[error localizedDescription]);
return;
}
for (CBService *service in peripheral.services) {
//发现特征,成功后执行:peripheral:didDiscoverCharacteristicsForService:error委托方法
[peripheral discoverCharacteristics:nil forService:service];
}
}
代理方法:已经为服务发现特征
蓝牙都会有几个服务,每个服务都会有几个特征,服务和特征都是用不同的 UUID 来标识的。每个特征的 properties 是不同的,就是说有不同的功能属性,有的对应写入,有的对应读取。蓝牙联盟有一个规范,但是这个也是可以自定义的,所以不清楚的话,联系硬件工程师问清楚。
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
NSLog(@"didDiscoverCharacteristicsForServic:%@",service.UUID);
CBCharacteristic *characteristic = nil;
if ([service.UUID isEqual:[CBUUID UUIDWithString:@"这里填你的蓝牙服务的 UUID"]]) {
for (characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"这里填你的蓝牙特征的 UUID"]]) {
self.characteristic = characteristic;//重要,将满足条件的特征保存为全局特征,以便对齐进行写入操作。
[PRTBluetoothModel share].characteristicWrite = characteristic;
[self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}
if (error) {
NSLog(@"didDiscoverCharacteristicsForService error:%@",[error localizedDescription]);
}
}
代理方法:已经更新特征的值
//获取外设发来的数据,不论是read和notify,获取数据都是从这个方法中读取。
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"didUpdateValueForCharacteristic:%@",[characteristic.UUID UUIDString]);
if (error) {
NSLog(@"didUpdateValueForCharacteristic error:%@",[error localizedDescription]);
}
for (CBDescriptor *descriptor in characteristic.descriptors) //12.23新增
{
[peripheral readValueForDescriptor:descriptor];
}
}
代理方法:已经写入特征的值
//委托方法:已经为特征【写入值】
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"didWriteValueForCharacteristic:%@",[characteristic.UUID UUIDString]);
if (error) {
NSLog(@"didWriteValueForCharacteristic error:%@",[error localizedDescription]);
}
[peripheral readValueForCharacteristic:characteristic]; //12.23新增
}
代理方法:已经发现特征的描述
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"didDiscoverDescriptorsForCharacteristic:%@",characteristic);
for (CBDescriptor *d in characteristic.descriptors) {
NSLog(@"Descriptor UUID:%@",d.UUID);
}
}
代理方法:已经更新描述的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
NSLog(@"didUpdateValueForDescriptor:%@",descriptor);
[peripheral readValueForDescriptor:descriptor]; //12.23新增
}
代理方法:已经更新特征的通知状态
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(@"didUpdateNotificationStateForCharacteristic:%@",characteristic);
[peripheral readValueForCharacteristic:characteristic]; //12.23新增
[peripheral discoverDescriptorsForCharacteristic:characteristic];
}
- 如果觉得本文有趣或者实用,请点击“喜欢”鼓励下作者哦
- 当然也接受打赏鼓励咯 :)