From 17f4b7e1beccdad0f8051864b55d01754caec087 Mon Sep 17 00:00:00 2001 From: Richard Nelson Date: Sat, 20 Jun 2020 22:22:27 +1000 Subject: [PATCH] Clean up Central's scannedPeripherals dict. When COVIDSafe removed the timer code, it also removed the reset of this dictionary, so currently it grows and grows in size. It probably doesn't get large enough to cause real problems (e.g. the OS killing the app), but for completeness also reset it on a memory warning. By my scrap paper calculations, a group of 50 people (with identifiers changing every 15m) will get it to ~200kb in 2 hours, so potentially over days it could cause issues currently. --- CovidSafe/CentralController.swift | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CovidSafe/CentralController.swift b/CovidSafe/CentralController.swift index b87c15f..d69c001 100644 --- a/CovidSafe/CentralController.swift +++ b/CovidSafe/CentralController.swift @@ -29,6 +29,7 @@ class CentralController: NSObject { private var central: CBCentralManager? private var recoveredPeripherals: [CBPeripheral] = [] private var queue: DispatchQueue + private var lastCleanedScannedPeripherals = Date() // This dict is to keep track of discovered android devices, so that i do not connect to the same android device multiple times within the same BluetraceConfig.CentralScanInterval private var discoveredAndroidPeriManufacturerToUUIDMap = [Data: UUID]() @@ -42,6 +43,12 @@ class CentralController: NSObject { public init(queue: DispatchQueue) { self.queue = queue super.init() + NotificationCenter.default.addObserver( + forName: UIApplication.didReceiveMemoryWarningNotification, + object: nil, + queue: .main) { [weak self] notification in + self?.cleanupScannedPeripherals() + } } func turnOn() { @@ -94,6 +101,14 @@ class CentralController: NSObject { return false } + fileprivate func cleanupScannedPeripherals() { + scannedPeripherals = scannedPeripherals.filter { scan in + guard let encounterTime = scan.value.encounter.timestamp else { return true } + return abs(encounterTime.timeIntervalSinceNow) < BluetraceConfig.CentralScanInterval + } + lastCleanedScannedPeripherals = Date() + } + public func getState() -> CBManagerState? { return central?.state } @@ -181,6 +196,9 @@ extension CentralController: CBCentralManagerDelegate { "advertisments": advertisementData as AnyObject] as AnyObject DLog("\(debugLogs)") + if (abs(lastCleanedScannedPeripherals.timeIntervalSince(Date())) > BluetraceConfig.CentralScanInterval) { + cleanupScannedPeripherals() + } var initialEncounter = EncounterRecord(rssi: RSSI.doubleValue, txPower: advertisementData[CBAdvertisementDataTxPowerLevelKey] as? Double) initialEncounter.timestamp = nil