CoreBluetooth:无法发现已发现外围设备的特征
Posted
技术标签:
【中文标题】CoreBluetooth:无法发现已发现外围设备的特征【英文标题】:CoreBluetooth: unable to discover characteristics for discovered peripheral 【发布时间】:2015-09-14 13:59:30 【问题描述】:我已经编写了一些 CoreBluetooth 代码,我可以发现设备,但我似乎无法发现我发现的外围设备的特征。有没有人有一个很好的示例代码可以用来验证我的代码?
这是我写的:
#import "ViewController.h"
@property(nonatomic, strong) CBCentralManager* centralmanager;
@end
@implementation ViewController
- (void)viewDidLoad
[super viewDidLoad];
self.centralmanager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
CBCentralManagerState currentState = central.state;
NSLog(@"state %i", currentState);
switch (central.state)
case CBCentralManagerStatePoweredOn:
NSDictionary *options = @
CBCentralManagerScanOptionAllowDuplicatesKey: @YES
;
[self.centralmanager scanForPeripheralsWithServices:nil options:options];
NSLog(@"I just started scanning for peripherals");
break;
- (void)centralManager:(CBCentralManager *)central
didConnectPeripheral:(CBPeripheral *)peripheral
NSLog(@"connected!");
- (void) centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI
[self.centralmanager connectPeripheral:peripheral options:nil];
if ([[advertisementData description] containsString:@“keyword”])
NSLog(@"peripheral count %lu", (unsigned long)[peripheral.services count]);
[peripheral.services count];
for (int i=0; [peripheral.services count]; i++)
for (CBService *s in peripheral.services)
[peripheral discoverCharacteristics:nil forService:s];
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
NSLog(@"did discover characteristic for service");
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSArray *)serviceUuids
NSLog(@"discovered a peripheral's services: %@", serviceUuids);
【问题讨论】:
你需要发现服务,然后发现特征...... 你能分享一些示例代码吗? github.com/paulw11/BTBackground 【参考方案1】:看看这里: Sample Code
基本上流程是:
-
扫描设备
发现设备
连接到设备
向设备请求服务
向服务询问特征
写入、读取或接收特征通知
随后,您不必搜索和发现设备,因为可以从缓存中检索以前发现的设备并直接连接。
编辑:--------
阅读示例:
[aPeripheral readValueForCharacteristic:aChar];
通知示例:
[aPeripheral setNotifyValue:YES forCharacteristic:aChar];
当 BLE 设备返回一个值时,这两个调用都会导致调用 - (void) peripheral:(CBPeripheral *)aPeripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
- 函数。使用 notify 时,每次设备更新该特性的值时,都会自动调用此回调。
【讨论】:
您好,非常感谢。我如何获得特征通知?我设法完成了第 5 步(@Paulw11 评论中的示例代码对我来说比官方的苹果代码更好):github.com/paulw11/BTBackground以上是关于CoreBluetooth:无法发现已发现外围设备的特征的主要内容,如果未能解决你的问题,请参考以下文章
如何在 CoreBluetooth 中测试两个 CBPeripheral 的相等性?
CoreBluetooth 外围设备:didDiscoverServices 未触发
CoreBluetooth:在 CBPeripheralStateConnecting 中的 didDisconnectPeripheral 回调