]> git.basschouten.com Git - openhab-addons.git/blob
ad692ccd13f95dd9c412fda7c34f12cd9da9eece
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.time.Instant;
16 import java.time.temporal.ChronoUnit;
17 import java.util.HashMap;
18 import java.util.Map;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.openhab.core.types.State;
22
23 /**
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
26  * change.
27  *
28  * @author Robert Bach - Initial contribution
29  */
30 @NonNullByDefault
31 public class ValueCache {
32
33     private final Map<String, StateWithTimestamp> stateByValue = new HashMap<>();
34
35     private final long durationMillis;
36
37     public ValueCache(long durationMillis) {
38         this.durationMillis = durationMillis;
39     }
40
41     /**
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
44      * the cache duration.
45      *
46      * @param channelId the channel's id
47      * @param state new state
48      */
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));
55             return true;
56         }
57         return false;
58     }
59
60     private static class StateWithTimestamp {
61         State state;
62         Instant timestamp;
63
64         public StateWithTimestamp(State state, Instant timestamp) {
65             this.state = state;
66             this.timestamp = timestamp;
67         }
68     }
69 }