]> git.basschouten.com Git - openhab-addons.git/blob
258f10748eb476ac4ecae67831297751b9170317
[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.netatmo.internal.handler.capability;
14
15 import static java.time.temporal.ChronoUnit.*;
16
17 import java.time.Duration;
18 import java.time.Instant;
19 import java.time.ZonedDateTime;
20 import java.util.Optional;
21 import java.util.concurrent.ScheduledExecutorService;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.openhab.binding.netatmo.internal.api.dto.NAThing;
27 import org.openhab.binding.netatmo.internal.handler.CommonInterface;
28 import org.openhab.core.thing.ThingStatus;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * {@link RefreshCapability} is the class used to embed the refreshing needs calculation for devices
34  *
35  * @author GaĆ«l L'hopital - Initial contribution
36  *
37  */
38 @NonNullByDefault
39 public class RefreshCapability extends Capability {
40     private static final Duration DEFAULT_DELAY = Duration.of(20, SECONDS);
41     private static final Duration PROBING_INTERVAL = Duration.of(120, SECONDS);
42     private static final Duration OFFLINE_INTERVAL = Duration.of(15, MINUTES);
43
44     private final Logger logger = LoggerFactory.getLogger(RefreshCapability.class);
45     private final ScheduledExecutorService scheduler;
46
47     private Duration dataValidity;
48     private Instant dataTimeStamp = Instant.now();
49     private Instant dataTimeStamp0 = Instant.MIN;
50     private Optional<ScheduledFuture<?>> refreshJob = Optional.empty();
51     private boolean refreshConfigured;
52
53     public RefreshCapability(CommonInterface handler, ScheduledExecutorService scheduler, int refreshInterval) {
54         super(handler);
55         this.scheduler = scheduler;
56         this.dataValidity = Duration.ofSeconds(Math.max(0, refreshInterval));
57         this.refreshConfigured = !probing();
58         freeJobAndReschedule(2);
59     }
60
61     @Override
62     public void dispose() {
63         freeJobAndReschedule(0);
64         super.dispose();
65     }
66
67     @Override
68     public void expireData() {
69         dataTimeStamp = Instant.now().minus(dataValidity);
70         freeJobAndReschedule(1);
71     }
72
73     private Duration dataAge() {
74         return Duration.between(dataTimeStamp, Instant.now());
75     }
76
77     private boolean probing() {
78         return dataValidity.getSeconds() <= 0;
79     }
80
81     private void proceedWithUpdate() {
82         handler.proceedWithUpdate();
83         long delay;
84         if (!ThingStatus.ONLINE.equals(handler.getThing().getStatus())) {
85             logger.debug("Module is not ONLINE; special refresh interval is used");
86             delay = OFFLINE_INTERVAL.toSeconds();
87             if (probing()) {
88                 dataTimeStamp0 = Instant.MIN;
89             }
90         } else {
91             delay = refreshConfigured ? dataValidity.getSeconds()
92                     : (probing() ? PROBING_INTERVAL : dataValidity.minus(dataAge()).plus(DEFAULT_DELAY)).toSeconds();
93         }
94         delay = delay < 2 ? PROBING_INTERVAL.toSeconds() : delay;
95         logger.debug("Module refreshed, next one in {}s", delay);
96         freeJobAndReschedule(delay);
97     }
98
99     @Override
100     protected void updateNAThing(NAThing newData) {
101         super.updateNAThing(newData);
102         newData.getLastSeen().map(ZonedDateTime::toInstant).ifPresent(tsInstant -> {
103             if (probing()) {
104                 if (Instant.MIN.equals(dataTimeStamp0)) {
105                     dataTimeStamp0 = tsInstant;
106                     logger.debug("First data timestamp is {}", dataTimeStamp0);
107                 } else if (tsInstant.isAfter(dataTimeStamp0)) {
108                     dataValidity = Duration.between(dataTimeStamp0, tsInstant);
109                     refreshConfigured = true;
110                     logger.debug("Data validity period identified to be {}", dataValidity);
111                 } else {
112                     logger.debug("Data validity period not yet found - data timestamp unchanged");
113                 }
114             }
115             dataTimeStamp = tsInstant;
116         });
117     }
118
119     private void freeJobAndReschedule(long delay) {
120         refreshJob.ifPresent(job -> job.cancel(false));
121         refreshJob = Optional
122                 .ofNullable(delay == 0 ? null : scheduler.schedule(() -> proceedWithUpdate(), delay, TimeUnit.SECONDS));
123     }
124 }