更新14/08 - 3 - 找到真正的解决方案:
您可以在下面的答案中查看解决方案!
更新16/06 - 2 - 可能是解决方案:
正如Sandy Chapman在他的回答评论中建议的那样,现在我能够通过使用这种方法在扫描开始时检索到我的外围设备:
- (NSArray<CBPeripheral *> * nonnull)retrievePeripheralsWithIdentifiers:(NSArray<NSUUID *> * nonnull)identifiers
我正在尝试通过在扫描开始时获取我的外围设备并启动连接(即使它不在范围内)来使其工作。iOS会保持其活动状态,直到找到我正在寻找的设备。
请注意,如果后台有使用蓝牙的发布版本应用程序,可能会导致iOS 8.x中存在错误,从时间到时间中断扫描(消失回调)。
更新于16/06:
所以我使用retrievePeripheralsWithServices检查是否有设备在我开始扫描时已连接。当我遇到此错误时,我启动应用程序并首先要做的事情是
- (void) applicationDidBecomeActive:(UIApplication *)application
问题是要检查返回数组的大小。每次出现错误时,它总是为0。如果我的设备在当前运行中没有建立任何连接,也会出现错误。当我用另一个设备触发命令时,我也能够看到我的设备广告,但在另一个设备中出现错误。
更新10/06:
- 我让我的应用程序整晚运行,以检查是否有任何内存泄漏或大量资源使用情况,在后台运行约12-14个小时后,这是我的结果。内存/CPU使用情况与我离开时完全相同。这使我认为我的应用程序没有任何泄漏,可能导致iOS关闭它以获得内存/CPU使用情况。
更新08/06:
- 请注意,这不是广告问题,因为我们的BLE设备持续供电,并且我们使用了我们可以找到的最强的BLE电子卡。
- 这也不是后台iOS检测时间的问题。我等待很长时间(20〜30分钟)来确保不是这个问题。
原始问题:
我目前正在开发一个处理与BLE设备通信的应用程序。我的一个限制条件是,只有在发送命令或读取数据时才必须连接到此设备。完成后,我必须尽快断开连接,以允许其他潜在用户执行相同的操作。
应用程序的一个功能如下:
- 当应用程序处于后台时,用户可以启用自动命令。如果在10分钟内未检测到该设备,则触发此自动命令。
- 我的应用程序一直扫描直到找到我的BLE设备。
- 为了在需要时保持其唤醒状态,我每次都重新开始扫描,因为忽略CBCentralManagerScanOptionAllowDuplicatesKey选项。
- 当检测到它时,我会检查上次检测是否超过10分钟。如果是这种情况,我将连接到设备,然后写入对应所需服务的特征。
目标是在用户进入范围时触发此设备。这可能会在离开范围几分钟或几个小时后发生,这取决于我的用户习惯。
一切运行良好,但有时(似乎随机时间),扫描会“冻结”。我的处理程序已成功完成,但是经过几次后,我的应用程序正在扫描,但我的didDiscoverPeripheral:回调从未被调用,即使我的测试设备就在我的BLE设备面前。有时可能需要一段时间才能检测到它,但是在这里,几分钟后什么都没有发生。
我认为 iOS 可能会在内存不足时杀死我的应用程序,但是当我关闭和打开蓝牙时,"centralManagerDidUpdateState:" 将被正确调用。如果我的应用程序被系统强制关闭了,这种情况就不应该发生,对吗?如果我打开我的应用程序,扫描将重新启动并恢复运行。我还检查了 iOS 是否在 180 秒的活动之后关闭我的应用程序,但实际上并不是这样,因为它在此时间后仍然正常工作。
我已经设置了我的 .plist 文件以具有正确的设置(在 "UIBackgroundModes" 中的 "bluetooth-central")。管理所有 BLE 处理的类存储在我的 AppDelegate 中,是一个通过我整个应用程序访问的单例。我还尝试切换创建此对象的位置,目前我在 "application:didFinishLaunchingWithOptions:" 方法中创建它。但如果我在 "AppDelegate init:" 中创建它,每次在后台时扫描都会失败。
我不知道哪部分代码可以帮助您更好地了解我的过程。以下是一些可能有所帮助的示例。请注意,"AT_appDelegate" 是为了访问我的 AppDelegate 而使用的宏。
// Init of my DeviceManager class that handles all BLE processing
- (id) init {
self = [super init];
// Flags creation
self.autoConnectTriggered = NO;
self.isDeviceReady = NO;
self.connectionUncomplete = NO;
self.currentCommand = NONE;
self.currentCommand_index = 0;
self.signalOkDetectionCount = 0; // Helps to find out if device is at a good range or too far
self.connectionFailedCount = 0; // Helps in a "try again" process if a command fails
self.main_uuid = [CBUUID UUIDWithString:MAINSERVICE_UUID];
self.peripheralsRetainer = [[NSMutableArray alloc] init];
self.lastDeviceDetection = nil;
// Ble items creation
dispatch_queue_t queue = dispatch_queue_create("com.onset.corebluetooth.queue", DISPATCH_QUEUE_SERIAL);
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:queue];
[self startScanning];
return self;
}
// The way i start the scan
- (void) startScanning {
if (!self.isScanning && self.centralManager.state == CBCentralManagerStatePoweredOn) {
CLS_LOG(@"### Start scanning ###");
self.isScanning = YES;
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:!self.isBackground] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.centralManager scanForPeripheralsWithServices:@[self.main_uuid] options:options];
});
}
}
// The way i stop and restart the scan after i've found our device. Contains some of foreground (UI update) process that you can ignore
- (void) stopScanningAndRestart: (BOOL) restart {
CLS_LOG(@"### Scanning terminated ###");
if (self.isScanning) {
self.isScanning = NO;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.centralManager stopScan];
});
// Avoid clearing the connection when waiting for notification (remote + learning)
if (!self.isWaitingNotifiy && !self.isSynchronizing && self.currentCommand == NONE ) {
// If no device found during scan, update view
if (self.deviceToReach == nil && !self.isBackground) {
// Check if any connected devices last
if (![self isDeviceStillConnected]) {
CLS_LOG(@"--- Device unreachable for view ---");
} else {
self.isDeviceInRange = YES;
self.deviceToReach = AT_appDelegate.user.device.blePeripheral;
}
[self.delegate performSelectorOnMainThread:@selector(updateView) withObject:nil waitUntilDone:YES];
}
// Reset var
self.deviceToReach = nil;
self.isDeviceInRange = NO;
self.signalOkDetectionCount = 0;
// Check if autotrigger needs to be done again - If time interval is higher enough,
// reset autoConnectTriggered to NO. If user has been away for <AUTOTRIGGER_INTERVAL>
// from the device, it will trigger again next time it will be detected.
if ([[NSDate date] timeIntervalSinceReferenceDate] - [self.lastDeviceDetection timeIntervalSinceReferenceDate] > AUTOTRIGGER_INTERVAL) {
CLS_LOG(@"### Auto trigger is enabled ###");
self.autoConnectTriggered = NO;
}
}
}
if (restart) {
[self startScanning];
}
}
// Here is my detection process, the flag "isInBackground" is set up each time the app goes background
- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
CLS_LOG(@"### : %@ -- %@", peripheral.name, RSSI);
BOOL deviceAlreadyShown = [AT_appDelegate isDeviceAvailable];
// If current device has no UUID set, check if peripheral is the right one
// with its name, containing his serial number (macaddress) returned by
// the server on remote adding
NSString *p1 = [[[peripheral.name stringByReplacingOccurrencesOfString:@":" withString:@""] stringByReplacingOccurrencesOfString:@"Extel " withString:@""] uppercaseString];
NSString *p2 = [AT_appDelegate.user.device.serial uppercaseString];
if ([p1 isEqualToString:p2]) {
AT_appDelegate.user.device.scanUUID = peripheral.identifier;
}
// Filter peripheral connection with uuid
if ([AT_appDelegate.user.device.scanUUID isEqual:peripheral.identifier]) {
if (([RSSI intValue] > REQUIRED_SIGNAL_STRENGTH && [RSSI intValue] < 0) || self.isBackground) {
self.signalOkDetectionCount++;
self.deviceToReach = peripheral;
self.isDeviceInRange = (self.signalOkDetectionCount >= REQUIRED_SIGNAL_OK_DETECTIONS);
[peripheral setDelegate:self];
// Reset blePeripheral if daughter board has been switched and there were
// not enough time for the software to notice connection has been lost.
// If that was the case, the device.blePeripheral has not been reset to nil,
// and might be different than the new peripheral (from the new daugtherboard)
if (AT_appDelegate.user.device.blePeripheral != nil) {
if (![AT_appDelegate.user.device.blePeripheral.name isEqualToString:peripheral.name]) {
AT_appDelegate.user.device.blePeripheral = nil;
}
}
if (self.lastDeviceDetection == nil ||
([[NSDate date] timeIntervalSinceReferenceDate] - [self.lastDeviceDetection timeIntervalSinceReferenceDate] > AUTOTRIGGER_INTERVAL)) {
self.autoConnectTriggered = NO;
}
[peripheral readRSSI];
AT_appDelegate.user.device.blePeripheral = peripheral;
self.lastDeviceDetection = [NSDate date];
if (AT_appDelegate.user.device.autoconnect) {
if (!self.autoConnectTriggered && !self.autoTriggerConnectionLaunched) {
CLS_LOG(@"--- Perform trigger ! ---");
self.autoTriggerConnectionLaunched = YES;
[self executeCommand:W_TRIGGER onDevice:AT_appDelegate.user.device]; // trigger !
return;
}
}
}
if (deviceAlreadyShown) {
[self.delegate performSelectorOnMainThread:@selector(updateView) withObject:nil waitUntilDone:YES];
}
}
if (self.isBackground && AT_appDelegate.user.device.autoconnect) {
CLS_LOG(@"### Relaunch scan ###");
[self stopScanningAndRestart:YES];
}
}
- (void) applicationDidBecomeActive:(UIApplication *)application
中的第一件事是检查返回数组的大小。每次我遇到错误时,它总是为0 :/ 如果我的设备在当前运行中之前没有进行任何连接,也可能会出现错误。我将尝试在扫描开始后立即进行检查。 - JissayretrievePeripheralsWithIdentifiers:
方法吗?基本上,该方法应返回任何先前连接的设备,然后即使您尚未收到广告,您也应该能够启动与该设备的连接。 - Sandy Chapman