]> git.basschouten.com Git - openhab-addons.git/blob
d230df57f202ae6e3ea5a9e6e72a36bc0c5574e5
[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.time.ZonedDateTime;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.binding.netatmo.internal.api.dto.NAObject;
22 import org.openhab.binding.netatmo.internal.api.dto.NAThing;
23 import org.openhab.binding.netatmo.internal.handler.CommonInterface;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * {@link RefreshAutoCapability} implements probing and auto-adjusting refresh strategy
29  *
30  * @author GaĆ«l L'hopital - Initial contribution
31  *
32  */
33 @NonNullByDefault
34 public class RefreshAutoCapability extends RefreshCapability {
35     private static final Duration DEFAULT_DELAY = Duration.ofSeconds(15);
36
37     private final Logger logger = LoggerFactory.getLogger(RefreshAutoCapability.class);
38
39     private Instant dataTimeStamp = Instant.MIN;
40
41     public RefreshAutoCapability(CommonInterface handler) {
42         super(handler);
43     }
44
45     @Override
46     public void expireData() {
47         dataTimeStamp = Instant.MIN;
48         super.expireData();
49     }
50
51     @Override
52     protected Duration calcDelay() {
53         if (Instant.MIN.equals(dataTimeStamp)) {
54             return PROBING_INTERVAL;
55         }
56
57         Duration dataAge = Duration.between(dataTimeStamp, Instant.now());
58
59         Duration delay = dataValidity.minus(dataAge);
60         if (delay.isNegative() || delay.isZero()) {
61             logger.debug("{} did not update data in expected time, return to probing", thingUID);
62             dataTimeStamp = Instant.MIN;
63             return PROBING_INTERVAL;
64         }
65
66         return delay.plus(DEFAULT_DELAY);
67     }
68
69     @Override
70     protected void updateNAThing(NAThing newData) {
71         super.updateNAThing(newData);
72         dataTimeStamp = newData.getLastSeen().map(ZonedDateTime::toInstant).orElse(Instant.MIN);
73     }
74
75     @Override
76     protected void afterNewData(@Nullable NAObject newData) {
77         properties.put("probing", Boolean.valueOf(Instant.MIN.equals(dataTimeStamp)).toString());
78         super.afterNewData(newData);
79     }
80 }