2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.danfossairunit.internal;
15 import java.time.Instant;
16 import java.time.temporal.ChronoUnit;
17 import java.util.HashMap;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.openhab.core.types.State;
24 * The {@link ValueCache} is responsible for holding the last value of the channels for a
25 * certain amount of time {@link ValueCache#durationMillis} to prevent unnecessary event bus updates if the value didn't
28 * @author Robert Bach - Initial contribution
31 public class ValueCache {
33 private final Map<String, StateWithTimestamp> stateByValue = new HashMap<>();
35 private final long durationMillis;
37 public ValueCache(long durationMillis) {
38 this.durationMillis = durationMillis;
42 * Updates or inserts the given value into the value cache. Returns true if there was no value in the cache
43 * for the given channelId or if the value has updated to a different value or if the value is older than
46 * @param channelId the channel's id
47 * @param state new state
49 public boolean updateValue(String channelId, State state) {
50 Instant now = Instant.now();
51 StateWithTimestamp cachedValue = stateByValue.get(channelId);
52 if (cachedValue == null || !state.equals(cachedValue.state)
53 || cachedValue.timestamp.isBefore(now.minus(durationMillis, ChronoUnit.MILLIS))) {
54 stateByValue.put(channelId, new StateWithTimestamp(state, now));
60 private static class StateWithTimestamp {
64 public StateWithTimestamp(State state, Instant timestamp) {
66 this.timestamp = timestamp;