蓝牙相关

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

 

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

 

1建立中心角色

 

 

 

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

 

 

  1. #import <CoreBluetooth/CoreBluetooth.h>  
  2. CBCentralManager *manager;  
  3. manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

 

 

2扫描外设(discover)

 


 

代码如下:

 

 
  1. [manager scanForPeripheralsWithServices:nil options:options];  



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

 

 
  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的设备后,系统会通过回调函数告诉我们设备的信息,然后我们就可以连接相应的设备,代码如下:

 

 
  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. }  



 
  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)

 

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

 

 

 

 
  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. }  


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

 

 
  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. }  
  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. }  

 

 

 

 

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

 

 

 

发送数据很简单,我们可以封装一个如下的函数:

 

  1. //写数据  
  2. -(void)writeChar:(NSData *)data  
  3. {  
  4.     [_testPeripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];  
  5. }  

 


 

_testPeripheral和_writeCharacteristic是前面我们保存的设备对象和可以读写的特征。

 

 

 

然后我们可以在外部调用它,比如当然我要触发刷卡时,先组好数据包,然后调用发送函数:

 

  1. -(void)msrRead  
  2. {  
  3.       
  4.     unsigned char command[512] = {0};  
  5.     unsigned charchar *pTmp;  
  6.     int nSendLen = 0;  
  7.     unsigned char ucCrc[3] = {0};  
  8.       
  9.     _commandType = COMMAND_MSR_READ;  
  10.       
  11.     pTmp = command;  
  12.       
  13.       
  14.     *pTmp = 0x02;//start  
  15.     pTmp++;  
  16.       
  17.     *pTmp = 0xc1;//main cmd  
  18.     pTmp++;  
  19.       
  20.     *pTmp = 0x07;//sub cmd  
  21.     pTmp++;  
  22.       
  23.       
  24.       
  25.     nSendLen = 2;  
  26.       
  27.     *pTmp = nSendLen/256;  
  28.     pTmp++;  
  29.     *pTmp = nSendLen%256;  
  30.     pTmp++;  
  31.       
  32.     *pTmp = 0x00;//sub cmd  
  33.     pTmp++;  
  34.       
  35.     *pTmp = 0x00;//sub cmd  
  36.     pTmp++;  
  37.       
  38.       
  39.     Crc16CCITT(command+1,pTmp-command-1,ucCrc);  
  40.     memcpy(pTmp,ucCrc,2);  
  41.       
  42.       
  43.     NSData *data = [[NSData alloc] initWithBytes:&command length:9];  
  44.     NSLog(@"send data:%@", data);  
  45.     [g_BLEInstance.recvData setLength:0];  
  46.       
  47.     [g_BLEInstance writeChar:data];  
  48. }  



数据的读分为两种,一种是直接读(reading directly),另外一种是订阅(subscribe)。从名字也能基本理解两者的不同。实际使用中具体用一种要看具体的应用场景以及特征本身的属性。前一个好理解,特征本身的属性是指什么呢?特征有个properties字段(characteristic.properties),它是一个整型值,有如下几个定义:

 

  1. enum {  
  2.      CBCharacteristicPropertyBroadcast = 0x01,  
  3.      CBCharacteristicPropertyRead = 0x02,  
  4.      CBCharacteristicPropertyWriteWithoutResponse = 0x04,  
  5.      CBCharacteristicPropertyWrite = 0x08,  
  6.      CBCharacteristicPropertyNotify = 0x10,  
  7.      CBCharacteristicPropertyIndicate = 0x20,  
  8.      CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,  
  9.      CBCharacteristicPropertyExtendedProperties = 0x80,  
  10.      };  

 


 

比如说,你要交互的特征,它的properties的值是0x10,表示你只能用订阅的方式来接收数据。我这里是用订阅的方式,启动订阅的代码如下:

 

  1. //监听设备  
  2. -(void)startSubscribe  
  3. {  
  4.     [_testPeripheral setNotifyValue:YES forCharacteristic:_readCharacteristic];  
  5. }  



当设备有数据返回时,同样是通过一个系统回调通知我,如下所示:

 

  1. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error  
  2. {  
  3.           
  4.     if (error)   
  5.     {  
  6.         NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);  
  7.           
  8.         if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadError:)])  
  9.             [_mainMenuDelegate DidNotifyReadError:error];  
  10.           
  11.         return;  
  12.     }  
  13.       
  14.     [_recvData appendData:characteristic.value];  
  15.       
  16.       
  17.     if ([_recvData length] >= 5)//已收到长度  
  18.     {  
  19.         unsigned charchar *buffer = (unsigned charchar *)[_recvData bytes];  
  20.         int nLen = buffer[3]*256 + buffer[4];  
  21.         if ([_recvData length] == (nLen+3+2+2))  
  22.         {  
  23.             //接收完毕,通知代理做事  
  24.             if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadData)])  
  25.                 [_mainMenuDelegate DidNotifyReadData];  
  26.               
  27.         }  
  28.     }  
  29.   
  30. }  



6 断开连接(disconnect)

 

 

 

这个比较简单,只需要一个API就行了,代码如下:

 

 

 

  1. //主动断开设备  
  2. -(void)disConnect  
  3. {  
  4.       
  5.     if (_testPeripheral != nil)  
  6.     {  
  7.         NSLog(@"disConnect start");  
  8.         [manager cancelPeripheralConnection:_testPeripheral];  
  9.     }  
  10.   
  11. }  

 

 

 

posted on 2015-11-10 15:12  骑蜗牛溜溜弯  阅读(206)  评论(0编辑  收藏  举报

导航