]> git.basschouten.com Git - openhab-addons.git/blob
05593888b9f6a3fda81f244f9c70a79ba41271a9
[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.WeatherApi;
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 CacheWeatherCapability} give the ability to buffer weather related requests and reduce server requests
28  *
29  * @author GaĆ«l L'hopital - Initial contribution
30  *
31  */
32 @NonNullByDefault
33 public abstract class CacheWeatherCapability extends RestCapability<WeatherApi> {
34     private final Logger logger = LoggerFactory.getLogger(CacheWeatherCapability.class);
35     private final Duration validity;
36
37     private List<NAObject> lastResult = List.of();
38     private Instant requestTS = Instant.MIN;
39
40     public CacheWeatherCapability(CommonInterface handler, Duration validity) {
41         super(handler, WeatherApi.class);
42         this.validity = validity;
43     }
44
45     @Override
46     protected List<NAObject> updateReadings(WeatherApi api) {
47         Instant now = Instant.now();
48
49         if (requestTS.plus(validity).isBefore(now)) {
50             logger.debug("Requesting fresh data");
51             lastResult = getFreshData(api);
52             requestTS = now;
53         }
54
55         return lastResult;
56     }
57
58     protected abstract List<NAObject> getFreshData(WeatherApi api);
59 }