From 8211b0ac885f9b0970f0e0441f57dd8b376e2dd0 Mon Sep 17 00:00:00 2001 From: Matthias Urhahn Date: Thu, 2 Feb 2023 16:45:39 +0100 Subject: [PATCH] Track case battery state outside of history list and simplify history clean up. (#92) --- .../capod/pods/core/apple/ApplePodsFactory.kt | 27 +++++++++---------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/app-common/src/main/java/eu/darken/capod/pods/core/apple/ApplePodsFactory.kt b/app-common/src/main/java/eu/darken/capod/pods/core/apple/ApplePodsFactory.kt index eba9dd9b..74b22766 100644 --- a/app-common/src/main/java/eu/darken/capod/pods/core/apple/ApplePodsFactory.kt +++ b/app-common/src/main/java/eu/darken/capod/pods/core/apple/ApplePodsFactory.kt @@ -37,7 +37,8 @@ abstract class ApplePodsFactory(private val tag: String) { val id: PodDevice.Id, val seenFirstAt: Instant, val seenCounter: Int, - val history: List + val history: List, + val lastCaseBattery: Float?, ) { val lastMessage: ProximityPairing.Message get() = history.last().proximityMessage @@ -73,7 +74,9 @@ abstract class ApplePodsFactory(private val tag: String) { internal val knownDevices = mutableMapOf() - fun KnownDevice.getLatestCaseBattery(): Float? = history + fun KnownDevice.getLatestCaseBattery(): Float? = this.lastCaseBattery + + private fun Collection.determineLatestCaseBattery(): Float? = this .filterIsInstance() .mapNotNull { it.batteryCasePercent } .lastOrNull() @@ -97,17 +100,7 @@ abstract class ApplePodsFactory(private val tag: String) { open fun historyTrimmer( pods: List ): List { - var trimmed = pods.takeLast(KnownDevice.MAX_HISTORY) - - // We want to keep the case information - // If both pods are removed, and produce more history, we otherwise lose the case battery info. - val caseInfoFat = pods.lastOrNull { it is HasCase && it.batteryCasePercent != null } - val caseInfoTrimmed = trimmed.lastOrNull { it is HasCase && it.batteryCasePercent != null } - if (caseInfoFat != null && caseInfoTrimmed == null) { - trimmed = listOf(caseInfoFat) + trimmed.takeLast(KnownDevice.MAX_HISTORY - 1) - } - - return trimmed + return pods.takeLast(KnownDevice.MAX_HISTORY) } internal open fun searchHistory(current: PodType): KnownDevice? { @@ -151,18 +144,22 @@ abstract class ApplePodsFactory(private val tag: String) { knownDevices[device.identifier] = when { existing != null -> { + val history = existing.history.plus(device) existing.copy( seenCounter = existing.seenCounter + 1, - history = existing.history.plus(device) + history = history, + lastCaseBattery = history.determineLatestCaseBattery() ?: existing.lastCaseBattery ) } else -> { log(tag) { "searchHistory1: Creating new history for $device" } + val history = listOf(device) KnownDevice( id = device.identifier, seenFirstAt = device.seenFirstAt, seenCounter = 1, - history = listOf(device) + history = history, + lastCaseBattery = history.determineLatestCaseBattery() ) } }