iOS开发之蓝牙通讯

一、引言
        蓝牙是设备近距离通信的一种方便手段,在iPhone引入蓝牙4.0后,设备之间的通讯变得更加简单。相关的蓝牙操作由专门的CoreBluetooth.framework进行统一管理。通过蓝牙进行通讯交互分为两方,一方为中心设备central,一方为外设peripheral,外设通过广播的方式向外发送信息,中心设备检索到外设发的广播信息,可以进行配对连接,进而进行数据交互。

二、中心设备CBCentralManager
        CBCentralManager是管理中心设备的管理类,其中重要方法如下:

//设置中心设备***
@property(assign, nonatomic, nullable) id<CBCentralManagerDelegate> delegate;
//中心设备当前状态
@property(readonly) CBCentralManagerState state;
//中心设备是否正在扫描
@property(readonly) BOOL isScanning NS_AVAILABLE(NA, 9_0);
其中state是一个枚举,有关蓝牙是否可用的状态如下:


typedef NS_ENUM(NSInteger, CBCentralManagerState) {
        //状态未知
    CBCentralManagerStateUnknown = 0,
    //连接断开 即将重置
    CBCentralManagerStateResetting,
    //该平台不支持蓝牙
    CBCentralManagerStateUnsupported,
    //未授权蓝牙使用 hovertree.com
    CBCentralManagerStateUnauthorized,
    //蓝牙关闭
    CBCentralManagerStatePoweredOff,
    //蓝牙正常开启
    CBCentralManagerStatePoweredOn,
};

下面这些方法用于初始化管理中心:


//初始化方法
//设置的***需要遵守CBCentralManagerDelegate协议
//queue可以设置蓝牙扫描的线程 传入nil则为在主线程中进行
- (instancetype)initWithDelegate:(nullable id<CBCentralManagerDelegate>)delegate
                           queue:(nullable dispatch_queue_t)queue;
//此方法同上 在options字典中用于进行一些管理中心的初始化属性设置
//字典中支持的键值如下 http://www.cnblogs.com/roucheng/
/*
NSString * const CBCentralManagerOptionShowPowerAlertKey 对应一个NSNumber类型的bool值,用于设置是否在关闭蓝牙时弹出用户提示
NSString * const CBCentralManagerOptionRestoreIdentifierKey 对应一个NSString对象,设置管理中心的标识符ID
*/
- (instancetype)initWithDelegate:(nullable id<CBCentralManagerDelegate>)delegate
                           queue:(nullable dispatch_queue_t)queue
                         options:(nullable NSDictionary<NSString *, id> *)options;

//根据获取所有已知设备
- (NSArray<CBPeripheral *> *)retrievePeripheralsWithIdentifiers:(NSArray<NSUUID *> *)identifiers;
//根据服务id获取所有连接的设备 hovertree.com
- (NSArray<CBPeripheral *> *)retrieveConnectedPeripheralsWithServices:(NSArray<CBUUID *> *)serviceUUIDs;
在初始化管理中心完成后,会回调***中的如下方法,我们必须实现如下方法:

//这个方法中可以获取到管理中心的状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
如果上面方法中管理中心状态为蓝牙可用,可以通过下面方法开启扫描外设:


//serviceUUIDs用于扫描一个特点ID的外设 options用于设置一些扫描属性 键值如下
/*
//是否允许重复扫描 对应NSNumber的bool值,默认为NO,会自动去重
NSString *const CBCentralManagerScanOptionAllowDuplicatesKey;
//要扫描的设备UUID 数组 对应NSArray hovertree.com
NSString *const CBCentralManagerScanOptionSolicitedServiceUUIDsKey;
*/
- (void)scanForPeripheralsWithServices:(nullable NSArray<CBUUID *> *)serviceUUIDs options:(nullable NSDictionary<NSString *, id> *)options;
复制代码
//停止扫描外设
- (void)stopScan;
扫描的结果会在如下***方法中回掉:
//peripheral 扫描到的外设
//advertisementData是外设发送的广播数据
//RSSI 是信号强度 http://www.cnblogs.com/roucheng/
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI;
扫描到外设后,通过下面方法可以连接一个外设:

复制代码
/*
options中可以设置一些连接设备的初始属性键值如下
//对应NSNumber的bool值,设置当外设连接后是否弹出一个警告
NSString *const CBConnectPeripheralOptionNotifyOnConnectionKey;
//对应NSNumber的bool值,设置当外设断开连接后是否弹出一个警告
NSString *const CBConnectPeripheralOptionNotifyOnDisconnectionKey;
//对应NSNumber的bool值,设置当外设暂停连接后是否弹出一个警告 http://www.cnblogs.com/roucheng/
NSString *const CBConnectPeripheralOptionNotifyOnNotificationKey;
*/
- (void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary<NSString *, id> *)options;
//取消一个外设的连接
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral;
复制代码
调用过连接外设的方法后,会回掉如下***方法:
//连接外设成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;
//连接外设失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
//断开外设连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
当管理中心恢复时会调用如下***:


  //dict中会传入如下键值对 hovertree.com
  /*
  //恢复连接的外设数组
  NSString *const CBCentralManagerRestoredStatePeripheralsKey;
  //恢复连接的服务UUID数组
  NSString *const CBCentralManagerRestoredStateScanServicesKey;
  //恢复连接的外设扫描属性字典数组
  NSString *const CBCentralManagerRestoredStateScanOptionsKey;
  */
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *, id> *)dict;

三、外设CBPeripheralManager
        从上面我们知道,中心设备是用来扫描周围的外设,两台设备的通讯中,必须有一个充当中心设备,一个充当外设,外设是由CBPeripheralManager进行管理,主要方法如下:


  //设置外设管理中心***
  @property(assign, nonatomic, nullable) id<CBPeripheralManagerDelegate> delegate;
  //外设状态 枚举如中心设备
  @property(readonly) CBPeripheralManagerState state;
  //是否正在发送广播
  @property(readonly) BOOL isAdvertising;
  //用户的授权状态
  + (CBPeripheralManagerAuthorizationStatus)authorizationStatus;
  //初始化并设置*** 参数的具体含义与中心设备管理中心
 - (instancetype)initWithDelegate:(nullable id<CBPeripheralManagerDelegate>)delegate
                            queue:(nullable dispatch_queue_t);
 - (instancetype)initWithDelegate:(nullable id<CBPeripheralManagerDelegate>)delegate
                            queue:(nullable dispatch_queue_t)queue
                          options:(nullable NSDictionary<NSString *, id> *)options;
 //开始发送广播 hovertree.com  何问起
 //advertisementData中可以发送的数据有约定 如下
 /*
 对应设置NSString类型的广播名
 NSString *const CBAdvertisementDataLocalNameKey;
外设制造商的NSData数据
 NSString *const CBAdvertisementDataManufacturerDataKey;
 外设制造商的CBUUID数据
 NSString *const CBAdvertisementDataServiceDataKey;
 服务的UUID与其对应的服务数据字典数组
 NSString *const CBAdvertisementDataServiceUUIDsKey;
 附加服务的UUID数组
 NSString *const CBAdvertisementDataOverflowServiceUUIDsKey;
 外设的发送功率 NSNumber类型
 NSString *const CBAdvertisementDataTxPowerLevelKey;
 外设是否可以连接
 NSString *const CBAdvertisementDataIsConnectable;
 服务的UUID数组
 NSString *const CBAdvertisementDataSolicitedServiceUUIDsKey;
 */
 - (void)startAdvertising:(nullable NSDictionary<NSString *, id> *)advertisementData;
 //停止发送广播
 - (void)stopAdvertising;
 //设置一个连接的具体central设备的延时 枚举如下
 /*
 typedef NS_ENUM(NSInteger, CBPeripheralManagerConnectionLatency) {
    CBPeripheralManagerConnectionLatencyLow = 0,
    CBPeripheralManagerConnectionLatencyMedium,
     CBPeripheralManagerConnectionLatencyHigh
 } NS_ENUM_AVAILABLE(NA, 6_0);
 */
 - (void)setDesiredConnectionLatency:(CBPeripheralManagerConnectionLatency)latency forCentral:(CBCentral *)central;
 //添加一个服务 http://www.cnblogs.com/roucheng/
 - (void)addService:(CBMutableService *)service;
 //移除一个服务
 - (void)removeService:(CBMutableService *)service;
 //移除所有服务
 - (void)removeAllServices;
 //响应中心设备的读写请求
 - (void)respondToRequest:(CBATTRequest *)request withResult:(CBATTError)result;
 //更新一个连接中心设备的订阅特征值
 - (BOOL)updateValue:(NSData *)value forCharacteristic:(CBMutableCharacteristic *)characteristic onSubscribedCentrals:(nullable NSArray<CBCentral *> *)centrals;

外设***的相关方法如下:


 1 //这个方法是必须实现的 状态可用后可以发送广播
 2 - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral;
 3 //连接回复时调用的方法 和centralManager类似
 4 - (void)peripheralManager:(CBPeripheralManager *)peripheral willRestoreState:(NSDictionary<NSString *, id> *)dict;
 5 //开始发送广播时调用的方法
 6 - (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(nullable NSError *)error;
 7 //添加服务调用的回调
 8 - (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(nullable NSError *)error;
 9 //当一个central设备订阅一个特征值时调用的方法
10 - (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic;
11 //取消订阅一个特征值时调用的方法
12 - (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic;
13 //收到读请求时触发的方法 何问起 hovertree.com
14 - (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request;
15 //收到写请求时触发的方法
16 - (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests;
17 //外设准备更新特征值时调用的方法
18 - (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral;

四、中心设备与外设对象CBCentral与CBPeripheral
        上面介绍了中心设备管理类与外设管理类,这些类用于将设备连接建立起来,器具的数据交换的服务和一些信息则是在对应的设备对象中。

1、中心设备 CBCentral属性与方法
//设备UUID
@property(readonly, nonatomic) NSUUID *identifier;
//中心设备最大接收的数据长度
@property(readonly, nonatomic) NSUInteger maximumUpdateValueLength;
2、外设CAPeripheral属性与方法
        外设对象要比中心对象复杂的多,当centralManager连接到外设后,需要通过外设对象的***方法进行数据交互,其中主要方法属性如下:

 View Code
外设的***方法如下:

 View Code
五、服务对象CBService
    服务对象是用来管理外设提供的一些数据服务的,其中属性如下:


//对应的外设
@property(assign, readonly, nonatomic) CBPeripheral *peripheral;
//是否是初等服务
@property(readonly, nonatomic) BOOL isPrimary;
//包含的自服务 http://www.cnblogs.com/roucheng/
@property(retain, readonly, nullable) NSArray<CBService *> *includedServices;
//服务中的特征值
@property(retain, readonly, nullable) NSArray<CBCharacteristic *> *characteristics;

六、服务的特征值CBCharacteristic
        通过绑定服务中的特征值来进行数据的读写操作,其中属性如下:


//对应的服务对象
@property(assign, readonly, nonatomic) CBService *service;
//特征值的属性 枚举如下
/*
typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
    CBCharacteristicPropertyBroadcast,//允许广播特征
    CBCharacteristicPropertyRead,//可读属性
    CBCharacteristicPropertyWriteWithoutResponse,//可写并且接收回执
    CBCharacteristicPropertyWrite,//可写属性
    CBCharacteristicPropertyNotify,//可通知属性
    CBCharacteristicPropertyIndicate,//可展现的特征值
    CBCharacteristicPropertyAuthenticatedSignedWrites,//允许签名的特征值写入
    CBCharacteristicPropertyExtendedProperties,
    CBCharacteristicPropertyNotifyEncryptionRequired,
    CBCharacteristicPropertyIndicateEncryptionRequired
};
*/
@property(readonly, nonatomic) CBCharacteristicProperties properties;
//特征值的数据 http://www.cnblogs.com/roucheng/
@property(retain, readonly, nullable) NSData *value;
//特征值的描述
@property(retain, readonly, nullable) NSArray<CBDescriptor *> *descriptors;
//是否是当前广播的特征
@property(readonly) BOOL isBroadcasted;
//是否是正在通知的特征
@property(readonly) BOOL isNotifying;

七、读写请求对象CBATTRequest
        服务对象是外设向中心设备提供的相关数据服务,获取到相应服务后,中心设备可以进行读写请求,读写对象属性如下:
//对应的中心设备
@property(readonly, nonatomic) CBCentral *central;
//对应的特征值
@property(readonly, nonatomic) CBCharacteristic *characteristic;
//读写数据值
@property(readwrite, copy, nullable) NSData *value;
http://www.cnblogs.com/roucheng/p/texiao.html

本文小结:

iOS开发之蓝牙通讯
一、引言
二、中心设备CBCentralManager
三、外设CBPeripheralManager
四、中心设备与外设对象CBCentral与CBPeripheral
1、中心设备 CBCentral属性与方法
2、外设CAPeripheral属性与方法
五、服务对象CBService
六、服务的特征值CBCharacteristic
七、读写请求对象CBATTRequest

来自http://www.cnblogs.com/roucheng/p/ioslanya.html
全部评论
66666
点赞 回复 分享
发布于 2015-12-23 09:48

相关推荐

面试官人很好,态度和蔼可亲,没答出来时也会引导你去思考。由于是晚上面的,导致我白天一天都有点紧张,面的时候状态也不是很好,正常可能面试官提问完应该思考几秒再答,而我就像抢答一样一口气把所有会的都说出来,这样就导致逻辑比较混乱,东一句西一句的。首先是自我介绍,先把会的技术大致讲一下,由于我八股背的多所以着重讲了一下,Java,go,jvm,MySQL,Redis,计网,操作系统这些,然后一小部分闲聊,然后先问了一下项目,面试官问我这个项目是否落实之类的,直接坦言说是写的练手的,包括之前也写过IM通讯,外卖之类的。然后面试官就把提问的重点放在了八股上。先问了Java:类加载器(答:3种+自定义类加载器、tomcat、原因+双亲委派+好处)JVM参数(答:xmx,xms,newsize这些,问我是如何设定的,我回答是把内存分一半给堆,再把堆分一半给新生代,这方面确实不太了解)然后问了一下并发相关的:线程池(答:线程池的7个参数(忘了线程工厂和阻塞时间了),3个重要参数,还有线程如何启用,为什么要设计最大线程数之类的,提到Java栈默认分配1MB运行时不可以更改)AQS(答:先讲clh是自旋锁+list,然后是AQS在这个基础上做的两个优化,然后举了一下reentrantlock根据state如何获取资源)CAS(答:使用三个字段,aba问题,然后将通常搭配自旋锁实现,面试官问通常会自旋多少次,这个不太了解,答的100,然后问100次大概多少秒,回答微秒级,然后面试官讲了一下怎么做资源可能没用完,意识到可能还需要进行阻塞操作)然后考虑一下Linux命令(top,ps,如何使用管道符过滤线程和使用Linux启动线程没答出来)然后问Redis:持久化机制(答:三种aof,rdb,混合,aof的三个参数刷盘策略,rdb以快照保存,使用bgsave会使用子线程来保存不会阻塞,而aof虽然会阻塞但是只在写完数据后追加一条命令,不会太影响,然后是他俩的优缺点,还有混合是怎么保存数据的)集群模式(答:三种,主从复制到缺点再到哨兵机制,正常使用三个哨兵互相监督,主节点挂了投票选主哨兵然后选主节点,然后额外讲一下脑裂的问题,主节点进行数据更新然后把命令写入aof来同步从节点,最后cluster集群,如何实现,使用16383个哈希槽(艹答成16384了),先根据哈希码取余,再根据节点数取余决定放在哪个节点上,然后问了一下我会怎么选集群模式,首先是cluster的问题,会让管道操作之类的失效,然后哨兵会导致整个集群结构变得复杂,使用小项目可能会考虑哨兵,大的考虑cluster,然后考了一下cluster如果一个节点挂了怎么办,根据节点数重新取余然后数据转移,面试官说这么转移比较慢,有没有别的办法,我隐约记得使用一个类似环形数组的方式,想不起来了)然后考了一下MySQL的b+树(这方面的知识点太多了,导致我什么都想讲逻辑就比较乱,讲了一下聚簇索引,树的叶子节点对应着一张页16KB,MySQL有一个区的概念,把这些页放在同一个区中,这样叶子节点的双向链表遍历时速度更快,然后b+树的扇出比较大(非常二,说成扇度之类的,面试官以为说的是扇区)这样层数就比较小,一行1kb数据的话3层可以放心2000w数据)其他的暂时想不起来了算法是lru,面试官问要不要提示,我说写个,然后写了10分钟左右,说大概写好了,但是面试官指出了2个小错误,第一个马上就改回来了,第二个一直没看出来(大脑这时候已经停止工作了)反问:问学习建议,说根据实际的项目进行深入,考虑应该怎么做,还问了一下组里面是做Java的吗?面试官说他是做go的,组里什么语言都有,语言影响不大,连忙补充了一句我对go的底层有深入源码的学习)结束。总体感觉答得不太好,没有太体现出深度,细节也不够全面。
下一个更好呗:佬,我投完云智一直没消息,多久约的一面啊
查看14道真题和解析
点赞 评论 收藏
分享
04-10 11:56
如皋中学 Java
高斯林的信徒:双c9能简历挂的?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务