2 * Copyright (c) 2010-2022 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.util.Calendar;
16 import java.util.HashMap;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.openhab.core.types.State;
23 * The {@link ValueCache} is responsible for holding the last value of the channels for a
24 * certain amount of time {@link ValueCache#durationMs} to prevent unnecessary event bus updates if the value didn't
27 * @author Robert Bach - Initial contribution
30 public class ValueCache {
32 private Map<String, StateWithTimestamp> stateByValue = new HashMap<>();
34 private final long durationMs;
36 public ValueCache(long durationMs) {
37 this.durationMs = durationMs;
41 * Updates or inserts the given value into the value cache. Returns true if there was no value in the cache
42 * for the given channelId or if the value has updated to a different value or if the value is older than
45 public boolean updateValue(String channelId, State newState) {
46 long currentTimeMs = Calendar.getInstance().getTimeInMillis();
47 StateWithTimestamp oldState = stateByValue.get(channelId);
49 if (oldState == null) {
52 writeToCache = !oldState.state.equals(newState) || oldState.timestamp < (currentTimeMs - durationMs);
55 stateByValue.put(channelId, new StateWithTimestamp(newState, currentTimeMs));
60 private static class StateWithTimestamp {
64 public StateWithTimestamp(State state, long timestamp) {
66 this.timestamp = timestamp;