IOS 蓝牙---广州鼎瀛APP开发专家
CoreBluetooth介绍CoreBluetooth框架的核心其实是两个东西,peripheral和central, 可以理解成外设和中心。对应他们分别有一组相关的API和类,如下图所示:
http://img.blog.csdn.net/20140523195339187?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcG9ueV9tYWdnaWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast
如果你要编程的设备是central那么你大部分用到,反之亦然。在我们这个示例中,金融刷卡器是peripheral,我们的iphone手机是central,所以我将大部分使用上图中左边部分的类。使用peripheral编程的例子也有很多,比如像用一个ipad和一个iphone通讯,ipad可以认为是central,iphone端是peripheral,这种情况下在iphone端就要使用上图右边部分的类来开发了。
www.dyage.com 公司官网
ios/ipad/andriod客户端/OA进销存客户管理
软件定制/winCE、winMobile软件开发/JAVA/php/asp/.net大型资讯/SNS网站开发/400客服热线电话/网站推广/平面设计/windows
phone 客户端/电子商务/政府网站开发/winCE、winMobile ipad
官网: www.dyage.com
四 服务和特征
有个概念有必要先说明一下。什么是服务和特征呢(service and characteristic)?
每个蓝牙4.0的设备都是通过服务和特征来展示自己的,一个设备必然包含一个或多个服务,每个服务下面又包含若干个特征。特征是与外界交互的最小单位。比如说,一台蓝牙4.0设备,用特征A来描述自己的出厂信息,用特征B来与收发数据等。
服务和特征都是用UUID来唯一标识的,UUID的概念如果不清楚请自行google,国际蓝牙组织为一些很典型的设备(比如测量心跳和血压的设备)规定了标准的service UUID(特征的UUID比较多,这里就不列举了),如下:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]
[*]#define BLE_UUID_ALERT_NOTIFICATION_SERVICE 0x1811
[*]#define BLE_UUID_BATTERY_SERVICE 0x180F
[*]#define BLE_UUID_BLOOD_PRESSURE_SERVICE 0x1810
[*]#define BLE_UUID_CURRENT_TIME_SERVICE 0x1805
[*]#define BLE_UUID_CYCLING_SPEED_AND_CADENCE 0x1816
[*]#define BLE_UUID_DEVICE_INFORMATION_SERVICE 0x180A
[*]#define BLE_UUID_GLUCOSE_SERVICE 0x1808
[*]#define BLE_UUID_HEALTH_THERMOMETER_SERVICE 0x1809
[*]#define BLE_UUID_HEART_RATE_SERVICE 0x180D
[*]#define BLE_UUID_HUMAN_INTERFACE_DEVICE_SERVICE 0x1812
[*]#define BLE_UUID_IMMEDIATE_ALERT_SERVICE 0x1802
[*]#define BLE_UUID_LINK_LOSS_SERVICE 0x1803
[*]#define BLE_UUID_NEXT_DST_CHANGE_SERVICE 0x1807
[*]#define BLE_UUID_PHONE_ALERT_STATUS_SERVICE 0x180E
[*]#define BLE_UUID_REFERENCE_TIME_UPDATE_SERVICE 0x1806
[*]#define BLE_UUID_RUNNING_SPEED_AND_CADENCE 0x1814
[*]#define BLE_UUID_SCAN_PARAMETERS_SERVICE 0x1813
[*]#define BLE_UUID_TX_POWER_SERVICE 0x1804
[*]#define BLE_UUID_CGM_SERVICE 0x181A
#define BLE_UUID_ALERT_NOTIFICATION_SERVICE 0x1811 #define BLE_UUID_BATTERY_SERVICE 0x180F #define BLE_UUID_BLOOD_PRESSURE_SERVICE 0x1810 #define BLE_UUID_CURRENT_TIME_SERVICE 0x1805 #define BLE_UUID_CYCLING_SPEED_AND_CADENCE 0x1816 #define BLE_UUID_DEVICE_INFORMATION_SERVICE 0x180A #define BLE_UUID_GLUCOSE_SERVICE 0x1808 #define BLE_UUID_HEALTH_THERMOMETER_SERVICE 0x1809 #define BLE_UUID_HEART_RATE_SERVICE 0x180D #define BLE_UUID_HUMAN_INTERFACE_DEVICE_SERVICE 0x1812 #define BLE_UUID_IMMEDIATE_ALERT_SERVICE 0x1802 #define BLE_UUID_LINK_LOSS_SERVICE 0x1803 #define BLE_UUID_NEXT_DST_CHANGE_SERVICE 0x1807 #define BLE_UUID_PHONE_ALERT_STATUS_SERVICE 0x180E #define BLE_UUID_REFERENCE_TIME_UPDATE_SERVICE 0x1806 #define BLE_UUID_RUNNING_SPEED_AND_CADENCE 0x1814 #define BLE_UUID_SCAN_PARAMETERS_SERVICE 0x1813 #define BLE_UUID_TX_POWER_SERVICE 0x1804 #define BLE_UUID_CGM_SERVICE 0x181A
当然还有很多设备并不在这个标准列表里,比如我用的这个金融刷卡器。蓝牙设备硬件厂商通常都会提供他们的设备里面各个服务(service)和特征(characteristics)的功能,比如哪些是用来交互(读写),哪些可获取模块信息(只读)等。
五 实现细节
作为一个中心要实现完整的通讯,一般要经过这样几个步骤:
建立中心角色—扫描外设(discover)—连接外设(connect)—扫描外设中的服务和特征(discover)—与外设做数据交互(explore and interact)—断开连接(disconnect)。
1建立中心角色
首先在我自己类的头文件中要包含CoreBluetooth的头文件,并继承两个协议<CBCentralManagerDelegate,CBPeripheralDelegate>,代码如下:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]#import <CoreBluetooth/CoreBluetooth.h>
[*]CBCentralManager *manager;
[*]manager = [ alloc] initWithDelegate:self queue:nil];
#import <CoreBluetooth/CoreBluetooth.h>CBCentralManager *manager;manager = [ initWithDelegate:self queue:nil];
2扫描外设(discover)
代码如下:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*] scanForPeripheralsWithServices:nil options:options];
;
这个参数应该也是可以指定特定的peripheral的UUID,那么理论上这个central只会discover这个特定的设备,但是我实际测试发现,如果用特定的UUID传参根本找不到任何设备,我用的代码如下:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]NSArray *uuidArray = arrayWithObjects: UUIDWithString:@"1800"], UUIDWithString:@"180A"],
[*] UUIDWithString:@"1CB2D155-33A0-EC21-6011-CD4B50710777"], UUIDWithString:@"6765D311-DD4C-9C14-74E1-A431BBFD0652"],nil];
[*]
[*] scanForPeripheralsWithServices:uuidArray options:options];
NSArray *uuidArray = ,,,,nil]; ;
目前不清楚原因,怀疑和设备本身在的广播包有关。
3连接外设(connect)
当扫描到4.0的设备后,系统会通过回调函数告诉我们设备的信息,然后我们就可以连接相应的设备,代码如下:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
[*]{
[*]
[*] if(! containsObject:peripheral])
[*] addObject:peripheral];
[*]
[*] NSLog(@"dicoveredPeripherals:%@", _dicoveredPeripherals);
[*]}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{ if(!) ; NSLog(@"dicoveredPeripherals:%@", _dicoveredPeripherals);}
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]//连接指定的设备
[*]-(BOOL)connect:(CBPeripheral *)peripheral
[*]{
[*] NSLog(@"connect start");
[*] _testPeripheral = nil;
[*]
[*] connectPeripheral:peripheral
[*] options: dictionaryWithObject: numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
[*]
[*] //开一个定时器监控连接超时的情况
[*] connectTimer = scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(connectTimeout:) userInfo:peripheral repeats:NO];
[*]
[*] return (YES);
[*]}
//连接指定的设备-(BOOL)connect:(CBPeripheral *)peripheral{ NSLog(@"connect start"); _testPeripheral = nil; forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]]; //开一个定时器监控连接超时的情况 connectTimer = ; return (YES);}
4扫描外设中的服务和特征(discover)
同样的,当连接成功后,系统会通过回调函数告诉我们,然后我们就在这个回调里去扫描设备下所有的服务和特征,代码如下:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
[*]{
[*] invalidate];//停止时钟
[*]
[*] NSLog(@"Did connect to peripheral: %@", peripheral);
[*] _testPeripheral = peripheral;
[*]
[*] setDelegate:self];
[*] discoverServices:nil];
[*]
[*]
[*]}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{ ;//停止时钟 NSLog(@"Did connect to peripheral: %@", peripheral); _testPeripheral = peripheral; ; ; }
一个设备里的服务和特征往往比较多,大部分情况下我们只是关心其中几个,所以一般会在发现服务和特征的回调里去匹配我们关心那些,比如下面的代码:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
[*]{
[*]
[*]
[*] NSLog(@"didDiscoverServices");
[*]
[*] if (error)
[*] {
[*] NSLog(@"Discovered services for %@ with error: %@", peripheral.name, localizedDescription]);
[*]
[*] if ( respondsToSelector:@selector(DidNotifyFailConnectService:withPeripheral:error:)])
[*] DidNotifyFailConnectService:nil withPeripheral:nil error:nil];
[*]
[*] return;
[*] }
[*]
[*]
[*] for (CBService *service in peripheral.services)
[*] {
[*]
[*] if ( isEqual: UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]])
[*] {
[*] NSLog(@"Service found with UUID: %@", service.UUID);
[*] discoverCharacteristics:nil forService:service];
[*] isVPOS3356 = YES;
[*] break;
[*] }
[*]
[*]
[*] }
[*]}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{ NSLog(@"didDiscoverServices"); if (error) { NSLog(@"Discovered services for %@ with error: %@", peripheral.name, ); if () ; return; } for (CBService *service in peripheral.services) { if (]) { NSLog(@"Service found with UUID: %@", service.UUID); ; isVPOS3356 = YES; break; } }}
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
[*]{
[*]
[*] if (error)
[*] {
[*] NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, localizedDescription]);
[*]
[*] if ( respondsToSelector:@selector(DidNotifyFailConnectChar:withPeripheral:error:)])
[*] DidNotifyFailConnectChar:nil withPeripheral:nil error:nil];
[*]
[*] return;
[*] }
[*]
[*]
[*] for (CBCharacteristic *characteristic in service.characteristics)
[*] {
[*] if ( isEqual: UUIDWithString:UUIDSTR_ISSC_TRANS_TX]])
[*] {
[*] NSLog(@"Discovered read characteristics:%@ for service: %@", characteristic.UUID, service.UUID);
[*]
[*] _readCharacteristic = characteristic;//保存读的特征
[*]
[*] if ( respondsToSelector:@selector(DidFoundReadChar:)])
[*] DidFoundReadChar:characteristic];
[*]
[*] break;
[*] }
[*] }
[*]
[*]
[*] for (CBCharacteristic * characteristic in service.characteristics)
[*] {
[*]
[*]
[*] if ( isEqual: UUIDWithString:UUIDSTR_ISSC_TRANS_RX]])
[*] {
[*]
[*] NSLog(@"Discovered write characteristics:%@ for service: %@", characteristic.UUID, service.UUID);
[*] _writeCharacteristic = characteristic;//保存写的特征
[*]
[*] if ( respondsToSelector:@selector(DidFoundWriteChar:)])
[*] DidFoundWriteChar:characteristic];
[*]
[*] break;
[*]
[*]
[*] }
[*] }
[*]
[*] if ( respondsToSelector:@selector(DidFoundCharacteristic:withPeripheral:error:)])
[*] DidFoundCharacteristic:nil withPeripheral:nil error:nil];
[*]
[*]}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { if (error) { NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, ); if () ; return; } for (CBCharacteristic *characteristic in service.characteristics) { if (]) { NSLog(@"Discovered read characteristics:%@ for service: %@", characteristic.UUID, service.UUID); _readCharacteristic = characteristic;//保存读的特征 if () ; break; } } for (CBCharacteristic * characteristic in service.characteristics) { if (]) { NSLog(@"Discovered write characteristics:%@ for service: %@", characteristic.UUID, service.UUID); _writeCharacteristic = characteristic;//保存写的特征 if () ; break; } } if () ; }
相信你应该已经注意到了,回调函数都是以"did"开头的,这些函数不用你调用,达到条件后系统后自动调用。
5与外设做数据交互(explore and interact)
发送数据很简单,我们可以封装一个如下的函数:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]//写数据
[*]-(void)writeChar:(NSData *)data
[*]{
[*] writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
[*]}
//写数据-(void)writeChar:(NSData *)data{ ;}
_testPeripheral和_writeCharacteristic是前面我们保存的设备对象和可以读写的特征。
然后我们可以在外部调用它,比如当然我要触发刷卡时,先组好数据包,然后调用发送函数:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]-(void)msrRead
[*]{
[*]
[*] unsigned char command = {0};
[*] unsigned charchar *pTmp;
[*] int nSendLen = 0;
[*] unsigned char ucCrc = {0};
[*]
[*] _commandType = COMMAND_MSR_READ;
[*]
[*] pTmp = command;
[*]
[*]
[*] *pTmp = 0x02;//start
[*] pTmp++;
[*]
[*] *pTmp = 0xc1;//main cmd
[*] pTmp++;
[*]
[*] *pTmp = 0x07;//sub cmd
[*] pTmp++;
[*]
[*]
[*]
[*] nSendLen = 2;
[*]
[*] *pTmp = nSendLen/256;
[*] pTmp++;
[*] *pTmp = nSendLen%256;
[*] pTmp++;
[*]
[*] *pTmp = 0x00;//sub cmd
[*] pTmp++;
[*]
[*] *pTmp = 0x00;//sub cmd
[*] pTmp++;
[*]
[*]
[*] Crc16CCITT(command+1,pTmp-command-1,ucCrc);
[*] memcpy(pTmp,ucCrc,2);
[*]
[*]
[*] NSData *data = [ alloc] initWithBytes:&command length:9];
[*] NSLog(@"send data:%@", data);
[*] setLength:0];
[*]
[*] writeChar:data];
[*]}
-(void)msrRead{ unsigned char command = {0}; unsigned char *pTmp; int nSendLen = 0; unsigned char ucCrc = {0}; _commandType = COMMAND_MSR_READ; pTmp = command; *pTmp = 0x02;//start pTmp++; *pTmp = 0xc1;//main cmd pTmp++; *pTmp = 0x07;//sub cmd pTmp++; nSendLen = 2; *pTmp = nSendLen/256; pTmp++; *pTmp = nSendLen%256; pTmp++; *pTmp = 0x00;//sub cmd pTmp++; *pTmp = 0x00;//sub cmd pTmp++; Crc16CCITT(command+1,pTmp-command-1,ucCrc); memcpy(pTmp,ucCrc,2); NSData *data = [ initWithBytes:&command length:9]; NSLog(@"send data:%@", data); ; ;}
数据的读分为两种,一种是直接读(reading directly),另外一种是订阅(subscribe)。从名字也能基本理解两者的不同。实际使用中具体用一种要看具体的应用场景以及特征本身的属性。前一个好理解,特征本身的属性是指什么呢?特征有个properties字段(characteristic.properties),它是一个整型值,有如下几个定义:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]enum {
[*] CBCharacteristicPropertyBroadcast = 0x01,
[*] CBCharacteristicPropertyRead = 0x02,
[*] CBCharacteristicPropertyWriteWithoutResponse = 0x04,
[*] CBCharacteristicPropertyWrite = 0x08,
[*] CBCharacteristicPropertyNotify = 0x10,
[*] CBCharacteristicPropertyIndicate = 0x20,
[*] CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,
[*] CBCharacteristicPropertyExtendedProperties = 0x80,
[*] };
enum { CBCharacteristicPropertyBroadcast = 0x01, CBCharacteristicPropertyRead = 0x02, CBCharacteristicPropertyWriteWithoutResponse = 0x04, CBCharacteristicPropertyWrite = 0x08, CBCharacteristicPropertyNotify = 0x10, CBCharacteristicPropertyIndicate = 0x20, CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40, CBCharacteristicPropertyExtendedProperties = 0x80, };
比如说,你要交互的特征,它的properties的值是0x10,表示你只能用订阅的方式来接收数据。我这里是用订阅的方式,启动订阅的代码如下:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]//监听设备
[*]-(void)startSubscribe
[*]{
[*] setNotifyValue:YES forCharacteristic:_readCharacteristic];
[*]}
//监听设备-(void)startSubscribe{ ;}
当设备有数据返回时,同样是通过一个系统回调通知我,如下所示:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
[*]{
[*]
[*] if (error)
[*] {
[*] NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, localizedDescription]);
[*]
[*] if ( respondsToSelector:@selector(DidNotifyReadError:)])
[*] DidNotifyReadError:error];
[*]
[*] return;
[*] }
[*]
[*] appendData:characteristic.value];
[*]
[*]
[*] if ( length] >= 5)//已收到长度
[*] {
[*] unsigned charchar *buffer = (unsigned charchar *) bytes];
[*] int nLen = buffer*256 + buffer;
[*] if ( length] == (nLen+3+2+2))
[*] {
[*] //接收完毕,通知代理做事
[*] if ( respondsToSelector:@selector(DidNotifyReadData)])
[*] DidNotifyReadData];
[*]
[*] }
[*] }
[*]
[*]}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{ if (error) { NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, ); if () ; return; } ; if ( >= 5)//已收到长度 { unsigned char *buffer = (unsigned char *); int nLen = buffer*256 + buffer; if ( == (nLen+3+2+2)) { //接收完毕,通知代理做事 if () ; } }}
6 断开连接(disconnect)
这个比较简单,只需要一个API就行了,代码如下:
view plaincopyprint?https://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg
[*]//主动断开设备
[*]-(void)disConnect
[*]{
[*]
[*] if (_testPeripheral != nil)
[*] {
[*] NSLog(@"disConnect start");
[*] cancelPeripheralConnection:_testPeripheral];
[*] }
[*]
[*]}
//主动断开设备-(void)disConnect{ if (_testPeripheral != nil) { NSLog(@"disConnect start"); ; }}
六 成果展示
上几张效果图,UI没怎么修饰,主要关注功能,实现了读取磁道信息,与金融ic卡进行APDU交互等功能。
http://img.blog.csdn.net/20140523201201734?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcG9ueV9tYWdnaWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast http://img.blog.csdn.net/20140523201215000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcG9ueV9tYWdnaWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast
http://img.blog.csdn.net/20140523201330109?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcG9ueV9tYWdnaWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast http://img.blog.csdn.net/20140523201343156?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcG9ueV9tYWdnaWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast
http://img.blog.csdn.net/20140523201358312?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcG9ueV9tYWdnaWU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast
页:
[1]