]> git.basschouten.com Git - openhab-addons.git/blob
b2ecd79482f907fa5a188098011cf3f5b68e4e8f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.netatmo.internal.handler.capability;
14
15 import java.time.Duration;
16 import java.time.Instant;
17 import java.util.List;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.openhab.binding.netatmo.internal.api.RestManager;
21 import org.openhab.binding.netatmo.internal.api.dto.NAObject;
22 import org.openhab.binding.netatmo.internal.handler.CommonInterface;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 /**
27  * {@link CacheCapability} give the ability to buffer RestManager related requests and reduce server requests
28  *
29  * @author GaĆ«l L'hopital - Initial contribution
30  *
31  */
32 @NonNullByDefault
33 public abstract class CacheCapability<T extends RestManager> extends RestCapability<T> {
34     private final Logger logger = LoggerFactory.getLogger(CacheCapability.class);
35     private final Duration validity;
36
37     private List<NAObject> lastResult = List.of();
38     private Instant requestTS = Instant.MIN;
39
40     public CacheCapability(CommonInterface handler, Duration validity, Class<T> restManagerClazz) {
41         super(handler, restManagerClazz);
42         this.validity = validity;
43     }
44
45     @Override
46     protected synchronized List<NAObject> updateReadings(T api) {
47         Instant now = Instant.now();
48
49         if (requestTS.plus(validity).isBefore(now)) {
50             logger.debug("{} requesting fresh data for {}", getClass().getSimpleName(), thingUID);
51             List<NAObject> result = getFreshData(api);
52             if (!result.isEmpty()) {
53                 lastResult = result;
54                 requestTS = now;
55             }
56         }
57
58         return lastResult;
59     }
60
61     protected abstract List<NAObject> getFreshData(T api);
62 }