diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index dcb6a9acd8da64..01f22543cde160 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -308,6 +308,13 @@ - (BOOL)isEqual:(id)object // happen more often than once every 10 minutes. #define MTRDEVICE_MIN_RESUBSCRIBE_DUE_TO_READ_INTERVAL_SECONDS (10 * 60) +// Weight of new data in determining subscription latencies. To avoid random +// outliers causing too much noise in the value, treat an existing value (if +// any) as having 2/3 weight and the new value as having 1/3 weight. These +// weights are subject to change, if it's determined that different ones give +// better behavior. +#define MTRDEVICE_SUBSCRIPTION_LATENCY_NEW_VALUE_WEIGHT (1.0 / 3.0) + @interface MTRDevice () @property (nonatomic, readonly) os_unfair_lock lock; // protects the caches and device state // protects against concurrent time updates by guarding timeUpdateScheduled flag which manages time updates scheduling, @@ -1014,7 +1021,12 @@ - (void)_handleSubscriptionEstablished // We want time interval from initialSubscribeStart to now, not the other // way around. NSTimeInterval subscriptionLatency = -[initialSubscribeStart timeIntervalSinceNow]; - _estimatedSubscriptionLatency = @(subscriptionLatency); + if (_estimatedSubscriptionLatency == nil) { + _estimatedSubscriptionLatency = @(subscriptionLatency); + } else { + NSTimeInterval newSubscriptionLatencyEstimate = MTRDEVICE_SUBSCRIPTION_LATENCY_NEW_VALUE_WEIGHT * subscriptionLatency + (1 - MTRDEVICE_SUBSCRIPTION_LATENCY_NEW_VALUE_WEIGHT) * _estimatedSubscriptionLatency.doubleValue; + _estimatedSubscriptionLatency = @(newSubscriptionLatencyEstimate); + } [self _storePersistedDeviceData]; }