美文网首页
【iOS】蓝牙学习笔记

【iOS】蓝牙学习笔记

作者: Feroo_J | 来源:发表于2018-02-08 17:28 被阅读10次

1.外围设备

(1)创建外围设备,并设置代理

(2)设置代理会触发下面方法.在方法中,如果蓝牙打开,则创建特征、创建服务,然后将服务添加到外围设备

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral

(3)将服务添加到外围设备会触发下面方法.在方法中,设置广播信息(如名称,UUID),然后开始广播

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error

(4)开始广播会触发下面方法.在方法中,判断启动广播是否成功,如果成功,则自动循环广播

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error

(5)中心设备读取数据会触发下面方法.在方法中,外围设备响应请求

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request

(6)中心设备写入数据会触发下面方法.在方法中,处理写入的数据

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests

(7)中心设备订阅了外围设备的某个特征会触发下面方法.在方法中可以获得中心设备以及被订阅的特征,另外需要将中心设备保存

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic

中心设备取消订阅会触发下面方法

-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic)

2.中心设备

(1).创建中心设备,并设置代理

(2).设置代理会触发下面方法.在方法中,如果蓝牙打开,则开始扫描外围设备

- (void)centralManagerDidUpdateState:(CBCentralManager *)central

(3).发现外围设备会触发下面方法.在方法中,保存外围设备,然后连接外围设备

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI

(4).连接到外围设备会触发下面方法.在方法中,给外围设备设置代理,然后让外围设备根据服务UUID寻找服务

-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

(5).外围设备找到服务后会触发下面方法.在方法中,遍历找到的服务,找到指定服务;外围设备在指定的服务中,根据特征UUID去寻找特征

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error

(6).外围设备找到特征后会触发下面方法.在方法中遍历找到的特征,找到指定特征,此时可以做三种操作:a.读取外围设备特征数据 b.写入数据到外围设备特征 c.订阅特征

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

a.读取外围设备特征数据 或者订阅特征且特征值有变化 会触发下面方法.在方法中,处理得到的数据

-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

b.写入数据到外围设备特征会触发下面方法.在方法中判断是否写入成功

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error

c.订阅特征会触发下面方法.在方法中判断是否订阅成功

-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

相关文章

网友评论

      本文标题:【iOS】蓝牙学习笔记

      本文链接:https://www.haomeiwen.com/subject/jmgttftx.html