]> git.basschouten.com Git - openhab-addons.git/blob
e4bed6eb1873cea5a490c61f0a2fd3a031b46fca
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.danfossairunit.internal;
14
15 import java.util.Calendar;
16 import java.util.HashMap;
17 import java.util.Map;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.openhab.core.types.State;
21
22 /**
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
25  * change.
26  *
27  * @author Robert Bach - Initial contribution
28  */
29 @NonNullByDefault
30 public class ValueCache {
31
32     private Map<String, StateWithTimestamp> stateByValue = new HashMap<>();
33
34     private final long durationMs;
35
36     public ValueCache(long durationMs) {
37         this.durationMs = durationMs;
38     }
39
40     /**
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
43      * the cache duration
44      */
45     public boolean updateValue(String channelId, State newState) {
46         long currentTimeMs = Calendar.getInstance().getTimeInMillis();
47         StateWithTimestamp oldState = stateByValue.get(channelId);
48         boolean writeToCache;
49         if (oldState == null) {
50             writeToCache = true;
51         } else {
52             writeToCache = !oldState.state.equals(newState) || oldState.timestamp < (currentTimeMs - durationMs);
53         }
54         if (writeToCache) {
55             stateByValue.put(channelId, new StateWithTimestamp(newState, currentTimeMs));
56         }
57         return writeToCache;
58     }
59
60     private static class StateWithTimestamp {
61         State state;
62         long timestamp;
63
64         public StateWithTimestamp(State state, long timestamp) {
65             this.state = state;
66             this.timestamp = timestamp;
67         }
68     }
69 }