BLE4.0 实现蓝牙打印机

一 IOS 蓝牙介绍

蓝牙协议本身经历了从1.0到4.0的升级演变, 最新的4.0以其低功耗著称,所以一般也叫BLE(Bluetoothlow energy)。

iOS 有两个框架支持蓝牙与外设连接。一个是 ExternalAccessory。从ios3.0就开始支持,也是在iphone4s出来之前用的比较多的一种模式,但是它有个不好的地方,External Accessory需要拿到苹果公司的MFI认证。

另一个框架则是本文要介绍的CoreBluetooth,在iphone4s开始支持,专门用于与BLE设备通讯(因为它的API都是基于BLE的)。这个不需要MFI,并且现在很多蓝牙设备都支持4.0,所以也是在IOS比较推荐的一种开发方法。

 

二 CoreBluetooth介绍

CoreBluetooth框架的核心其实是两个东西,peripheral和central, 可以理解成外设和中心。对应他们分别有一组相关的API和类,如下图所示:

 

 

 如果你要编程的设备是central那么你大部分用到,反之亦然。在我们这个示例中,金融刷卡器是peripheral,我们的iphone手机是central,所以我将大部分使用上图中左边部分的类。使用peripheral编程的例子也有很多,比如像用一个ipad和一个iphone通讯,ipad可以认为是central,iphone端是peripheral,这种情况下在iphone端就要使用上图右边部分的类来开发了。

 

三 服务和特征

有个概念有必要先说明一下。什么是服务和特征呢(service and characteristic)?

每个蓝牙4.0的设备都是通过服务和特征来展示自己的,一个设备必然包含一个或多个服务,每个服务下面又包含若干个特征。特征是与外界交互的最小单位。比如说,一台蓝牙4.0设备,用特征A来描述自己的出厂信息,用特征B来与收发数据等。

 

服务和特征都是用UUID来唯一标识的,UUID的概念如果不清楚请自行google,国际蓝牙组织为一些很典型的设备(比如测量心跳和血压的设备)规定了标准的service UUID(特征的UUID比较多,这里就不列举了),如下:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.    
  2. #define      BLE_UUID_ALERT_NOTIFICATION_SERVICE   0x1811  
  3.  #define     BLE_UUID_BATTERY_SERVICE   0x180F  
  4.  #define     BLE_UUID_BLOOD_PRESSURE_SERVICE   0x1810  
  5.  #define     BLE_UUID_CURRENT_TIME_SERVICE   0x1805  
  6.  #define     BLE_UUID_CYCLING_SPEED_AND_CADENCE   0x1816  
  7.  #define     BLE_UUID_DEVICE_INFORMATION_SERVICE   0x180A  
  8.  #define     BLE_UUID_GLUCOSE_SERVICE   0x1808  
  9.  #define     BLE_UUID_HEALTH_THERMOMETER_SERVICE   0x1809  
  10.  #define     BLE_UUID_HEART_RATE_SERVICE   0x180D  
  11.  #define     BLE_UUID_HUMAN_INTERFACE_DEVICE_SERVICE   0x1812  
  12.  #define     BLE_UUID_IMMEDIATE_ALERT_SERVICE   0x1802  
  13.  #define     BLE_UUID_LINK_LOSS_SERVICE   0x1803  
  14.  #define     BLE_UUID_NEXT_DST_CHANGE_SERVICE   0x1807  
  15.  #define     BLE_UUID_PHONE_ALERT_STATUS_SERVICE   0x180E  
  16.  #define     BLE_UUID_REFERENCE_TIME_UPDATE_SERVICE   0x1806  
  17.  #define     BLE_UUID_RUNNING_SPEED_AND_CADENCE   0x1814  
  18.  #define     BLE_UUID_SCAN_PARAMETERS_SERVICE   0x1813  
  19.  #define     BLE_UUID_TX_POWER_SERVICE   0x1804  
  20.  #define     BLE_UUID_CGM_SERVICE   0x181A  


当然还有很多设备并不在这个标准列表里,比如我用的这个金融刷卡器。蓝牙设备硬件厂商通常都会提供他们的设备里面各个服务(service)和特征(characteristics)的功能,比如哪些是用来交互(读写),哪些可获取模块信息(只读)等。

 

五 实现细节

作为一个中心要实现完整的通讯,一般要经过这样几个步骤:

建立中心角色—扫描外设(discover)—连接外设(connect)—扫描外设中的服务和特征(discover)—与外设做数据交互(explore and interact)—断开连接(disconnect)。

 

1建立中心角色

首先在我自己类的头文件中要包含CoreBluetooth的头文件,并继承两个协议<CBCentralManagerDelegate,CBPeripheralDelegate>,代码如下:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #import <CoreBluetooth/CoreBluetooth.h>  
  2. CBCentralManager *manager;  
  3. manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];  


2扫描外设(discover)

代码如下:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. [manager scanForPeripheralsWithServices:nil options:options];  


这个参数应该也是可以指定特定的peripheral的UUID,那么理论上这个central只会discover这个特定的设备,但是我实际测试发现,如果用特定的UUID传参根本找不到任何设备,我用的代码如下:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NSArray *uuidArray = [NSArray arrayWithObjects:[CBUUID UUIDWithString:@"1800"],[CBUUID UUIDWithString:@"180A"],  
  2. [CBUUID UUIDWithString:@"1CB2D155-33A0-EC21-6011-CD4B50710777"],[CBUUID UUIDWithString:@"6765D311-DD4C-9C14-74E1-A431BBFD0652"],nil];  
  3.        
  4. [manager scanForPeripheralsWithServices:uuidArray options:options];  
 

目前不清楚原因,怀疑和设备本身在的广播包有关。

 

3连接外设(connect)

当扫描到4.0的设备后,系统会通过回调函数告诉我们设备的信息,然后我们就可以连接相应的设备,代码如下:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI  
  2. {  
  3.   
  4.     if(![_dicoveredPeripherals containsObject:peripheral])  
  5.         [_dicoveredPeripherals addObject:peripheral];  
  6.       
  7.     NSLog(@"dicoveredPeripherals:%@", _dicoveredPeripherals);  
  8. }  


[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //连接指定的设备  
  2. -(BOOL)connect:(CBPeripheral *)peripheral  
  3. {  
  4.     NSLog(@"connect start");  
  5.     _testPeripheral = nil;  
  6.       
  7.     [manager connectPeripheral:peripheral  
  8.                        options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];  
  9.       
  10.     //开一个定时器监控连接超时的情况  
  11.     connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(connectTimeout:) userInfo:peripheral repeats:NO];  
  12.   
  13.     return (YES);  
  14. }  

 

4扫描外设中的服务和特征(discover)

同样的,当连接成功后,系统会通过回调函数告诉我们,然后我们就在这个回调里去扫描设备下所有的服务和特征,代码如下:

 

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral  
  2. {  
  3.     [connectTimer invalidate];//停止时钟  
  4.       
  5.     NSLog(@"Did connect to peripheral: %@", peripheral);  
  6.     _testPeripheral = peripheral;  
  7.       
  8.     [peripheral setDelegate:self];  
  9.     [peripheral discoverServices:nil];  
  10.       
  11.       
  12. }  

一个设备里的服务和特征往往比较多,大部分情况下我们只是关心其中几个,所以一般会在发现服务和特征的回调里去匹配我们关心那些,比如下面的代码:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error  
  2. {  
  3.   
  4.       
  5.     NSLog(@"didDiscoverServices");  
  6.       
  7.     if (error)  
  8.     {  
  9.         NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);  
  10.           
  11.         if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectService:withPeripheral:error:)])  
  12.             [self.delegate DidNotifyFailConnectService:nil withPeripheral:nil error:nil];  
  13.           
  14.         return;  
  15.     }  
  16.       
  17.   
  18.     for (CBService *service in peripheral.services)  
  19.     {  
  20.           
  21.         if ([service.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]])  
  22.         {  
  23.             NSLog(@"Service found with UUID: %@", service.UUID);  
  24.             [peripheral discoverCharacteristics:nil forService:service];  
  25.             isVPOS3356 = YES;  
  26.             break;  
  27.         }  
  28.           
  29.           
  30.     }  
  31. }  

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error   
  2. {  
  3.       
  4.     if (error)   
  5.     {  
  6.         NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);  
  7.           
  8.         if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectChar:withPeripheral:error:)])  
  9.             [self.delegate DidNotifyFailConnectChar:nil withPeripheral:nil error:nil];  
  10.           
  11.         return;  
  12.     }  
  13.       
  14.       
  15.     for (CBCharacteristic *characteristic in service.characteristics)  
  16.     {  
  17.         if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_TX]])  
  18.         {  
  19.             NSLog(@"Discovered read characteristics:%@ for service: %@", characteristic.UUID, service.UUID);  
  20.               
  21.             _readCharacteristic = characteristic;//保存读的特征  
  22.               
  23.             if ([self.delegate respondsToSelector:@selector(DidFoundReadChar:)])  
  24.                 [self.delegate DidFoundReadChar:characteristic];  
  25.               
  26.             break;  
  27.         }  
  28.     }  
  29.   
  30.       
  31.     for (CBCharacteristic * characteristic in service.characteristics)  
  32.     {  
  33.           
  34.           
  35.         if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_RX]])  
  36.         {  
  37.   
  38.             NSLog(@"Discovered write characteristics:%@ for service: %@", characteristic.UUID, service.UUID);  
  39.             _writeCharacteristic = characteristic;//保存写的特征  
  40.               
  41.             if ([self.delegate respondsToSelector:@selector(DidFoundWriteChar:)])  
  42.                 [self.delegate DidFoundWriteChar:characteristic];  
  43.               
  44.             break;  
  45.               
  46.               
  47.         }  
  48.     }  
  49.       
  50.     if ([self.delegate respondsToSelector:@selector(DidFoundCharacteristic:withPeripheral:error:)])  
  51.         [self.delegate DidFoundCharacteristic:nil withPeripheral:nil error:nil];  
  52.       
  53. }  

相信你应该已经注意到了,回调函数都是以"did"开头的,这些函数不用你调用,达到条件后系统后自动调用。

 

 

5与外设做数据交互(explore and interact)

发送数据很简单:

   


接收数据:

   


接收数据操作要先监听,后发送指令,最后才能获取到数据,数据在didUpdateValueForCharacteristic代理事件里面

   

_peripheral ,_notifyPeripheral和_writeCharacteristic是前面我们保存的设备对象和可以读/写/订阅的特征。


效果图如下:





  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值