IOS蓝牙开发
蓝牙常遇缩写
mfi ======= make for ipad ,iphone, itouch 专们为苹果设备制作的设备
ble ==== buletouch low energy,蓝牙4.0设备因为低耗电,所以也叫做ble
peripheral,central == 外设和中心,发起连接的时central,被连接的设备为perilheral
service and characteristic === 服务和特征 每个设备会提供服务和特征,类似于服务端的api,但是机构不同。每个外设会有很多服务,每个服务中包含很多字段,这些字段的权限一般分为 读read,写write,通知notiy几种,就是我们连接设备后具体需要操作的内容。
description 每个characteristic可以对应一个或多个description用户描述characteristic的信息或属性
mfi === 开发使用externalaccessory 框架
4.0 ble === 开发使用corebluetooth 框架蓝牙基础知识
corebluetooth框架的核心其实是两个东西,peripheral和central, 可以理解成外设和中心。对应他们分别有一组相关的api和类
这两组api分别对应不同的业务场景,左侧叫做中心模式,就是以你的app作为中心,连接其他的外设的场景,而右侧称为外设模式,使用手机作为外设别其他中心设备操作的场景。
服务和特征,特征的属性(service and characteristic):每个设备都会有一些服务,每个服务里面都会有一些特征,特征就是具体键值对,提供数据的地方。每个特征属性分为这么几种:读,写,通知这么几种方式。
//objcetive c特征的定义枚举 typedef ns_options(nsuinteger, cbcharacteristicproperties) { cbcharacteristicpropertybroadcast = 0x01, cbcharacteristicpropertyread = 0x02, cbcharacteristicpropertywritewithoutresponse = 0x04, cbcharacteristicpropertywrite = 0x08, cbcharacteristicpropertynotify = 0x10, cbcharacteristicpropertyindicate = 0x20, cbcharacteristicpropertyauthenticatedsignedwrites = 0x40, cbcharacteristicpropertyextendedproperties = 0x80, cbcharacteristicpropertynotifyencryptionrequired ns_enum_available(na, 6_0) = 0x100, cbcharacteristicpropertyindicateencryptionrequired ns_enum_available(na, 6_0) = 0x200 };
外设、服务、特征间的关系
蓝牙中心模式流程
1. 建立中心角色 2. 扫描外设(discover) 3. 连接外设(connect) 4. 扫描外设中的服务和特征(discover) - 4.1 获取外设的services - 4.2 获取外设的characteristics,获取characteristics的值,获取characteristics的descriptor和descriptor的值 5. 与外设做数据交互(explore and interact) 6. 订阅characteristic的通知 7. 断开连接(disconnect)
蓝牙外设模式流程
1. 启动一个peripheral管理对象 2. 本地peripheral设置服务,特性,描述,权限等等 3. peripheral发送广告 4. 设置处理订阅、取消订阅、读characteristic、写characteristic的委托方法
蓝牙设备状态
1. 待机状态(standby):设备没有传输和发送数据,并且没有连接到任何设 2. 广播状态(advertiser):周期性广播状态 3. 扫描状态(scanner):主动寻找正在广播的设备 4. 发起链接状态(initiator):主动向扫描设备发起连接。 5. 主设备(master):作为主设备连接到其他设备。 6. 从设备(slave):作为从设备连接到其他设备。
蓝牙设备的五种工作状态
- 准备(standby)
- 广播(advertising)
- 监听扫描(scanning
- 发起连接(initiating)
- 已连接(connected)
蓝牙和版本的使用限制
- 蓝牙2.0 === 越狱设备
- 蓝牙4.0 ===ios6 以上
- mfi认证设备(make for ipod/ipad/iphone) === 无限制
名词解释
- gaat : generic attribute profile , gatt配置文件是一个通用规范,用于在ble链路上发送和接收被称为“属性”的数据块。目前所有的ble应用都基于gatt。 蓝牙sig规定了许多低功耗设备的配置文件。配置文件是设备如何在特定的应用程序中工作的规格说明。注意一个设备可以实现多个配置文件。例如,一个设备可能包括心率监测仪和电量检测。
- characteristic 一个characteristic包括一个单一变量和0-n个用来描述characteristic变量的descriptor,characteristic可以被认为是一个类型,类 似于类。
- descriptor descriptor用来描述characteristic变量的属性。例如,一个descriptor可以规定一个可读的描述,或者一个characteristic变量可接受的范围,或者一个characteristic变量特定的测量单位。 service service是characteristic的集合。例如,你可能有一个叫“heart rate monitor(心率监测仪)”的service,它包括了很多characteristics,如“heart rate measurement(心率测量)”等。你可以在bluetooth.org 找到一个目前支持的基于gatt的配置文件和服务列表。
ios连接外设的代码实现流程
1. 建立中心角色 2. 扫描外设(discover) 3. 连接外设(connect) 4. 扫描外设中的服务和特征(discover) - 4.1 获取外设的services - 4.2 获取外设的characteristics,获取characteristics的值,获取characteristics的descriptor和descriptor的值 5. 与外设做数据交互(explore and interact) 6. 订阅characteristic的通知 7. 断开连接(disconnect)
准备环境
1 xcode 2 开发证书和手机(蓝牙程序需要使用使用真机调试,使用模拟器也可以调试,但是方法很蛋疼,我会放在最后说) 3 蓝牙外设
实现步骤
1 导入corebluetooth头文件,建立主设备管理类,设置主设备委托
#import @interface viewcontroller : uiviewcontroller @interface viewcontroller (){ //系统蓝牙设备管理对象,可以把他理解为主设备,通过他,可以去扫描和链接外设 cbcentralmanager *manager; //用于保存被发现设备 nsmutablearray *peripherals; } - (void)viewdidload { [super viewdidload]; /* 设置主设备的委托,cbcentralmanagerdelegate 必须实现的: - (void)centralmanagerdidupdatestate:(cbcentralmanager *)central;//主设备状态改变的委托,在初始化cbcentralmanager的适合会打开设备,只有当设备正确打开后才能使用 其他选择实现的委托中比较重要的: - (void)centralmanager:(cbcentralmanager *)central diddiscoverperipheral:(cbperipheral *)peripheral advertisementdata:(nsdictionary *)advertisementdata rssi:(nsnumber *)rssi; //找到外设的委托 - (void)centralmanager:(cbcentralmanager *)central didconnectperipheral:(cbperipheral *)peripheral;//连接外设成功的委托 - (void)centralmanager:(cbcentralmanager *)central didfailtoconnectperipheral:(cbperipheral *)peripheral error:(nserror *)error;//外设连接失败的委托 - (void)centralmanager:(cbcentralmanager *)central diddisconnectperipheral:(cbperipheral *)peripheral error:(nserror *)error;//断开外设的委托 */ //初始化并设置委托和线程队列,最好一个线程的参数可以为nil,默认会就main线程 manager = [[cbcentralmanager alloc]initwithdelegate:self queue:dispatch_get_main_queue()];
2 扫描外设(discover),扫描外设的方法我们放在centralmanager成功打开的委托中,因为只有设备成功打开,才能开始扫描,否则会报错。
-(void)centralmanagerdidupdatestate:(cbcentralmanager *)central{ 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: nslog(@">>>cbcentralmanagerstatepoweredon"); //开始扫描周围的外设 /* 第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入 - (void)centralmanager:(cbcentralmanager *)central diddiscoverperipheral:(cbperipheral *)peripheral advertisementdata:(nsdictionary *)advertisementdata rssi:(nsnumber *)rssi; */ [manager scanforperipheralswithservices:nil options:nil]; break; default: break; } } //扫描到设备会进入方法 -(void)centralmanager:(cbcentralmanager *)central diddiscoverperipheral:(cbperipheral *)peripheral advertisementdata:(nsdictionary *)advertisementdata rssi:(nsnumber *)rssi{ nslog(@"当扫描到设备:%@",peripheral.name); //接下来可以连接设备 }
3 连接外设(connect)
//扫描到设备会进入方法 -(void)centralmanager:(cbcentralmanager *)central diddiscoverperipheral:(cbperipheral *)peripheral advertisementdata:(nsdictionary *)advertisementdata rssi:(nsnumber *)rssi{ //接下连接我们的测试设备,如果你没有设备,可以下载一个app叫lightbule的app去模拟一个设备 //这里自己去设置下连接规则,我设置的是p开头的设备 if ([peripheral.name hasprefix:@"p"]){ /* 一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接,连接成功,失败,断开会进入各自的委托 - (void)centralmanager:(cbcentralmanager *)central didconnectperipheral:(cbperipheral *)peripheral;//连接外设成功的委托 - (void)centralmanager:(cbcentralmanager *)central didfailtoconnectperipheral:(cbperipheral *)peripheral error:(nserror *)error;//外设连接失败的委托 - (void)centralmanager:(cbcentralmanager *)central diddisconnectperipheral:(cbperipheral *)peripheral error:(nserror *)error;//断开外设的委托 */ //找到的设备必须持有它,否则cbcentralmanager中也不会保存peripheral,那么cbperipheraldelegate中的方法也不会被调用!! [peripherals addobject:peripheral]; //连接设备 [manager connectperipheral:peripheral options:nil]; } } //连接到peripherals-成功 - (void)centralmanager:(cbcentralmanager *)central didconnectperipheral:(cbperipheral *)peripheral { nslog(@">>>连接到名称为(%@)的设备-成功",peripheral.name); } //连接到peripherals-失败 -(void)centralmanager:(cbcentralmanager *)central didfailtoconnectperipheral:(cbperipheral *)peripheral error:(nserror *)error { nslog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizeddescription]); } //peripherals断开连接 - (void)centralmanager:(cbcentralmanager *)central diddisconnectperipheral:(cbperipheral *)peripheral error:(nserror *)error{ nslog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizeddescription]); }
有一点非常容易出错,大家请注意。在diddiscoverperipheral这个委托中有这一行
//找到的设备必须持有它,否则cbcentralmanager中也不会保存peripheral,那么cbperipheraldelegate中的方法也不会被调用!! [peripherals addobject:peripheral];
请特别注意,如果不保存,会影响到后面的方法执行,这个地方很多人出错,在我的蓝牙交流群中每天几乎都会因为这个问题导致无法连接和对外设后续的操作。
大家也可以看一下这个委托在xcode中的说明,重点看@discussion中的内容,里面特别指出了需要retained对象。
/*! * @method centralmanager:diddiscoverperipheral:advertisementdata:rssi: * * @param central the central manager providing this update. * @param peripheral a cbperipheral object. * @param advertisementdata a dictionary containing any advertisement and scan response data. * @param rssi the current rssi of peripheral, in dbm. a value of 127 is reserved and indicates the rssi * was not available. * * @discussion this method is invoked while scanning, upon the discovery of peripheral by central. a discovered peripheral must * be retained in order to use it; otherwise, it is assumed to not be of interest and will be cleaned up by the central manager. for * a list of advertisementdata keys, see {@link cbadvertisementdatalocalnamekey} and other similar constants. * * @seealso cbadvertisementdata.h * */ - (void)centralmanager:(cbcentralmanager *)central diddiscoverperipheral:(cbperipheral *)peripheral advertisementdata:(nsdictionary *)advertisementdata rssi:(nsnumber *)rssi;
4扫描外设中的服务和特征(discover)
设备连接成功后,就可以扫描设备的服务了,同样是通过委托形式,扫描到结果后会进入委托方法。但是这个委托已经不再是主设备的委托(cbcentralmanagerdelegate),而是外设的委托(cbperipheraldelegate),这个委托包含了主设备与外设交互的许多 回叫方法,包括获取services,获取characteristics,获取characteristics的值,获取characteristics的descriptor,和descriptor的值,写数据,读rssi,用通知的方式订阅数据等等。
4.1获取外设的services
//连接到peripherals-成功 - (void)centralmanager:(cbcentralmanager *)central didconnectperipheral:(cbperipheral *)peripheral { nslog(@">>>连接到名称为(%@)的设备-成功",peripheral.name); //设置的peripheral委托cbperipheraldelegate //@interface viewcontroller : uiviewcontroller [peripheral setdelegate:self]; //扫描外设services,成功后会进入方法:-(void)peripheral:(cbperipheral *)peripheral diddiscoverservices:(nserror *)error{ [peripheral discoverservices:nil]; } //扫描到services -(void)peripheral:(cbperipheral *)peripheral diddiscoverservices:(nserror *)error{ // nslog(@">>>扫描到服务:%@",peripheral.services); if (error) { nslog(@">>>discovered services for %@ with error: %@", peripheral.name, [error localizeddescription]); return; } for (cbservice *service in peripheral.services) { nslog(@"%@",service.uuid); //扫描每个service的characteristics,扫描到后会进入方法: -(void)peripheral:(cbperipheral *)peripheral diddiscovercharacteristicsforservice:(cbservice *)service error:(nserror *)error [peripheral discovercharacteristics:nil forservice:service]; } }
### 4.2获取外设的characteristics,获取characteristics的值,获取characteristics的descriptor和descriptor的值
//扫描到characteristics -(void)peripheral:(cbperipheral *)peripheral diddiscovercharacteristicsforservice:(cbservice *)service error:(nserror *)error{ if (error) { nslog(@"error discovered characteristics for %@ with error: %@", service.uuid, [error localizeddescription]); return; } for (cbcharacteristic *characteristic in service.characteristics) { nslog(@"service:%@ 的 characteristic: %@",service.uuid,characteristic.uuid); } //获取characteristic的值,读到数据会进入方法:-(void)peripheral:(cbperipheral *)peripheral didupdatevalueforcharacteristic:(cbcharacteristic *)characteristic error:(nserror *)error for (cbcharacteristic *characteristic in service.characteristics){ { [peripheral readvalueforcharacteristic:characteristic]; } } //搜索characteristic的descriptors,读到数据会进入方法:-(void)peripheral:(cbperipheral *)peripheral diddiscoverdescriptorsforcharacteristic:(cbcharacteristic *)characteristic error:(nserror *)error for (cbcharacteristic *characteristic in service.characteristics){ [peripheral discoverdescriptorsforcharacteristic:characteristic]; } } //获取的charateristic的值 -(void)peripheral:(cbperipheral *)peripheral didupdatevalueforcharacteristic:(cbcharacteristic *)characteristic error:(nserror *)error{ //打印出characteristic的uuid和值 //!注意,value的类型是nsdata,具体开发时,会根据外设协议制定的方式去解析数据 nslog(@"characteristic uuid:%@ value:%@",characteristic.uuid,characteristic.value); } //搜索到characteristic的descriptors -(void)peripheral:(cbperipheral *)peripheral diddiscoverdescriptorsforcharacteristic:(cbcharacteristic *)characteristic error:(nserror *)error{ //打印出characteristic和他的descriptors nslog(@"characteristic uuid:%@",characteristic.uuid); for (cbdescriptor *d in characteristic.descriptors) { nslog(@"descriptor uuid:%@",d.uuid); } } //获取到descriptors的值 -(void)peripheral:(cbperipheral *)peripheral didupdatevaluefordescriptor:(cbdescriptor *)descriptor error:(nserror *)error{ //打印出descriptorsuuid 和value //这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析 nslog(@"characteristic uuid:%@ value:%@",[nsstring stringwithformat:@"%@",descriptor.uuid],descriptor.value); }
5 把数据写到characteristic中
//写数据 -(void)writecharacteristic:(cbperipheral *)peripheral characteristic:(cbcharacteristic *)characteristic value:(nsdata *)value{ //打印出 characteristic 的权限,可以看到有很多种,这是一个ns_options,就是可以同时用于好几个值,常见的有read,write,notify,indicate,知知道这几个基本就够用了,前连个是读写权限,后两个都是通知,两种不同的通知方式。 /* typedef ns_options(nsuinteger, cbcharacteristicproperties) { cbcharacteristicpropertybroadcast = 0x01, cbcharacteristicpropertyread = 0x02, cbcharacteristicpropertywritewithoutresponse = 0x04, cbcharacteristicpropertywrite = 0x08, cbcharacteristicpropertynotify = 0x10, cbcharacteristicpropertyindicate = 0x20, cbcharacteristicpropertyauthenticatedsignedwrites = 0x40, cbcharacteristicpropertyextendedproperties = 0x80, cbcharacteristicpropertynotifyencryptionrequired ns_enum_available(na, 6_0) = 0x100, cbcharacteristicpropertyindicateencryptionrequired ns_enum_available(na, 6_0) = 0x200 }; */ nslog(@"%lu", (unsigned long)characteristic.properties); //只有 characteristic.properties 有write的权限才可以写 if(characteristic.properties & cbcharacteristicpropertywrite){ /* 最好一个type参数可以为cbcharacteristicwritewithresponse或type:cbcharacteristicwritewithresponse,区别是是否会有反馈 */ [peripheral writevalue:value forcharacteristic:characteristic type:cbcharacteristicwritewithresponse]; }else{ nslog(@"该字段不可写!"); } }
6 订阅characteristic的通知
//设置通知 -(void)notifycharacteristic:(cbperipheral *)peripheral characteristic:(cbcharacteristic *)characteristic{ //设置通知,数据通知会进入:didupdatevalueforcharacteristic方法 [peripheral setnotifyvalue:yes forcharacteristic:characteristic]; } //取消通知 -(void)cancelnotifycharacteristic:(cbperipheral *)peripheral characteristic:(cbcharacteristic *)characteristic{ [peripheral setnotifyvalue:no forcharacteristic:characteristic]; }
7 断开连接(disconnect)
//停止扫描并断开连接 -(void)disconnectperipheral:(cbcentralmanager *)centralmanager peripheral:(cbperipheral *)peripheral{ //停止扫描 [centralmanager stopscan]; //断开连接 [centralmanager cancelperipheralconnection:peripheral]; }
温馨提示:如果想实时获取蓝牙与外设是否还在连接状态的话,一定要有
//peripherals断开连接 - (void)centralmanager:(cbcentralmanager *)central diddisconnectperipheral:(cbperipheral *)peripheral error:(nserror *)error{ nslog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizeddescription]); }来实时发现手机蓝牙与外设的连接状,这样就可以做到外设断开后只要外设还是可以连接的 那么就可以在这里写进入app就自动连接可搜到的这个外设就可以了 本人亲测的,有什么问题可以找我
上一篇: php学习--变量和数据类型
下一篇: 求最大公约数