国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > IOS 蓝牙介绍

IOS 蓝牙介绍

来源:程序员人生   发布时间:2016-07-19 13:04:42 阅读次数:2152次

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

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

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

CoreBluetooth介绍

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

这里写图片描述

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

服务和特点

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

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

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

#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)的功能,比如哪些是用来交互(读写),哪些可获得模块信息(只读)等.

实现细节

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

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

1建立中心角色 首先在我自己类的头文件中要包括CoreBluetooth的头文件,并继承两个协议<CBCentralManagerDelegate,CBPeripheralDelegate>,代码以下: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 #import <CoreBluetooth/CoreBluetooth.h> CBCentralManager *manager; manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
2扫描外设(discover) 代码以下: [objc] view plain copyCODE上查看代码片派生到我的代码片 [manager scanForPeripheralsWithServices:nil options:options];
这个参数应当也是可以指定特定的peripheral的UUID,那末理论上这个central只会discover这个特定的装备,但是我实际测试发现,如果用特定的UUID传参根本找不到任何装备,我用的代码以下: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 NSArray *uuidArray = [NSArray arrayWithObjects:[CBUUID UUIDWithString:@"1800"],[CBUUID UUIDWithString:@"180A"], [CBUUID UUIDWithString:@"1CB2D155⑶3A0-EC21⑹011-CD4B50710777"],[CBUUID UUIDWithString:@"6765D311-DD4C⑼C14⑺4E1-A431BBFD0652"],nil]; [manager scanForPeripheralsWithServices:uuidArray options:options]; 目前不清楚缘由,怀疑和装备本身在的广播包有关。
3连接外设(connect) 当扫描到4.0的装备后,系统会通过回调函数告知我们装备的信息,然后我们就能够连接相应的装备,代码以下: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI { if(![_dicoveredPeripherals containsObject:peripheral]) [_dicoveredPeripherals addObject:peripheral]; NSLog(@"dicoveredPeripherals:%@", _dicoveredPeripherals); }
//连接指定的装备 -(BOOL)connect:(CBPeripheral *)peripheral { NSLog(@"connect start"); _testPeripheral = nil; [manager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]]; //开1个定时器监控连接超时的情况 connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(connectTimeout:) userInfo:peripheral repeats:NO]; return (YES); }
4扫描外设中的服务和特点(discover) 一样的,当连接成功后,系统会通过回调函数告知我们,然后我们就在这个回调里去扫描装备下所有的服务和特点,代码以下: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { [connectTimer invalidate];//停止时钟 NSLog(@"Did connect to peripheral: %@", peripheral); _testPeripheral = peripheral; [peripheral setDelegate:self]; [peripheral discoverServices:nil]; }
1个装备里的服务和特点常常比较多,大部份情况下我们只是关心其中几个,所以1般会在发现服务和特点的回调里去匹配我们关心那些,比以下面的代码: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { NSLog(@"didDiscoverServices"); if (error) { NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]); if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectService:withPeripheral:error:)]) [self.delegate DidNotifyFailConnectService:nil withPeripheral:nil error:nil]; return; } for (CBService *service in peripheral.services) { if ([service.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]]) { NSLog(@"Service found with UUID: %@", service.UUID); [peripheral discoverCharacteristics:nil forService:service]; isVPOS3356 = YES; break; } } }
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { if (error) { NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]); if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectChar:withPeripheral:error:)]) [self.delegate DidNotifyFailConnectChar:nil withPeripheral:nil error:nil]; return; } for (CBCharacteristic *characteristic in service.characteristics) { if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_TX]]) { NSLog(@"Discovered read characteristics:%@ for service: %@", characteristic.UUID, service.UUID); _readCharacteristic = characteristic;//保存读的特点 if ([self.delegate respondsToSelector:@selector(DidFoundReadChar:)]) [self.delegate DidFoundReadChar:characteristic]; break; } } for (CBCharacteristic * characteristic in service.characteristics) { if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_RX]]) { NSLog(@"Discovered write characteristics:%@ for service: %@", characteristic.UUID, service.UUID); _writeCharacteristic = characteristic;//保存写的特点 if ([self.delegate respondsToSelector:@selector(DidFoundWriteChar:)]) [self.delegate DidFoundWriteChar:characteristic]; break; } } if ([self.delegate respondsToSelector:@selector(DidFoundCharacteristic:withPeripheral:error:)]) [self.delegate DidFoundCharacteristic:nil withPeripheral:nil error:nil]; }
5与外设做数据交互(explore and interact) 发送数据很简单,我们可以封装1个以下的函数: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 //写数据 -(void)writeChar:(NSData *)data { [_testPeripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse]; }
_testPeripheral和_writeCharacteristic是前面我们保存的装备对象和可以读写的特点。 然后我们可以在外部调用它,比如固然我要触发刷卡时,先组好数据包,然后调用发送函数: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 -(void)msrRead { unsigned char command[512] = {0}; unsigned charchar *pTmp; int nSendLen = 0; unsigned char ucCrc[3] = {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 = [[NSData alloc] initWithBytes:&command length:9]; NSLog(@"send data:%@", data); [g_BLEInstance.recvData setLength:0]; [g_BLEInstance writeChar:data]; }
比如说,你要交互的特点,它的properties的值是0x10,表示你只能用定阅的方式来接收数据。我这里是用定阅的方式,启动定阅的代码以下: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 //监听装备 -(void)startSubscribe { [_testPeripheral setNotifyValue:YES forCharacteristic:_readCharacteristic]; }
当装备有数据返回时,一样是通过1个系统回调通知我,以下所示: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if (error) { NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]); if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadError:)]) [_mainMenuDelegate DidNotifyReadError:error]; return; } [_recvData appendData:characteristic.value]; if ([_recvData length] >= 5)//已收到长度 { unsigned charchar *buffer = (unsigned charchar *)[_recvData bytes]; int nLen = buffer[3]*256 + buffer[4]; if ([_recvData length] == (nLen+3+2+2)) { //接收终了,通知代理做事 if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadData)]) [_mainMenuDelegate DidNotifyReadData]; } } }
6 断开连接(disconnect) 这个比较简单,只需要1个API就好了,代码以下: [objc] view plain copy 在CODE上查看代码片派生到我的代码片 //主动断开装备 -(void)disConnect { if (_testPeripheral != nil) { NSLog(@"disConnect start"); [manager cancelPeripheralConnection:_testPeripheral]; } }

效果图就不上传了,你可以找装备试试,尝试操作1下,原理就是这些,如有不好地方,还望给予斧正,不胜感激!!!谢谢!!!

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生