]> git.basschouten.com Git - openhab-addons.git/blob
eb20e2cfc375a7881d50d14e83551054a40f3451
[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.fmiweather.internal;
14
15 import static org.openhab.binding.fmiweather.internal.BindingConstants.*;
16
17 import java.math.BigDecimal;
18 import java.time.Instant;
19 import java.time.ZoneId;
20 import java.time.ZonedDateTime;
21 import java.util.Optional;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.atomic.AtomicReference;
25
26 import javax.measure.Quantity;
27 import javax.measure.Unit;
28
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.openhab.binding.fmiweather.internal.client.Client;
32 import org.openhab.binding.fmiweather.internal.client.Data;
33 import org.openhab.binding.fmiweather.internal.client.FMIResponse;
34 import org.openhab.binding.fmiweather.internal.client.Request;
35 import org.openhab.binding.fmiweather.internal.client.exception.FMIResponseException;
36 import org.openhab.binding.fmiweather.internal.client.exception.FMIUnexpectedResponseException;
37 import org.openhab.core.library.types.DateTimeType;
38 import org.openhab.core.library.types.DecimalType;
39 import org.openhab.core.library.types.QuantityType;
40 import org.openhab.core.thing.ChannelUID;
41 import org.openhab.core.thing.Thing;
42 import org.openhab.core.thing.ThingStatus;
43 import org.openhab.core.thing.ThingStatusDetail;
44 import org.openhab.core.thing.binding.BaseThingHandler;
45 import org.openhab.core.types.Command;
46 import org.openhab.core.types.RefreshType;
47 import org.openhab.core.types.UnDefType;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * The {@link AbstractWeatherHandler} is responsible for handling commands, which are
53  * sent to one of the channels.
54  *
55  * @author Sami Salonen - Initial contribution
56  */
57 @NonNullByDefault
58 public abstract class AbstractWeatherHandler extends BaseThingHandler {
59
60     private static final ZoneId UTC = ZoneId.of("UTC");
61     protected static final String PROP_LONGITUDE = "longitude";
62     protected static final String PROP_LATITUDE = "latitude";
63     protected static final String PROP_NAME = "name";
64     protected static final String PROP_REGION = "region";
65     private static final long REFRESH_THROTTLE_MILLIS = 10_000;
66
67     protected static final int TIMEOUT_MILLIS = 10_000;
68     private final Logger logger = LoggerFactory.getLogger(AbstractWeatherHandler.class);
69
70     protected volatile @NonNullByDefault({}) Client client;
71     protected final AtomicReference<@Nullable ScheduledFuture<?>> futureRef = new AtomicReference<>();
72     protected volatile @Nullable FMIResponse response;
73     protected volatile int pollIntervalSeconds = 120; // reset by subclasses
74
75     private volatile long lastRefreshMillis = 0;
76     private final AtomicReference<@Nullable ScheduledFuture<?>> updateChannelsFutureRef = new AtomicReference<>();
77
78     public AbstractWeatherHandler(Thing thing) {
79         super(thing);
80     }
81
82     @Override
83     @SuppressWarnings("PMD.CompareObjectsWithEquals")
84     public void handleCommand(ChannelUID channelUID, Command command) {
85         if (RefreshType.REFRESH == command) {
86             ScheduledFuture<?> prevFuture = updateChannelsFutureRef.get();
87             ScheduledFuture<?> newFuture = updateChannelsFutureRef
88                     .updateAndGet(fut -> fut == null || fut.isDone() ? submitUpdateChannelsThrottled() : fut);
89             assert newFuture != null; // invariant
90             if (logger.isTraceEnabled()) {
91                 long delayRemainingMillis = newFuture.getDelay(TimeUnit.MILLISECONDS);
92                 if (delayRemainingMillis <= 0) {
93                     logger.trace("REFRESH received. Channels are updated");
94                 } else {
95                     logger.trace("REFRESH received. Delaying by {} ms to avoid throttle excessive REFRESH",
96                             delayRemainingMillis);
97                 }
98                 // Compare by reference to check if the future changed
99                 if (prevFuture == newFuture) {
100                     logger.trace("REFRESH received. Previous refresh ongoing, will wait for it to complete in {} ms",
101                             lastRefreshMillis + REFRESH_THROTTLE_MILLIS - System.currentTimeMillis());
102                 }
103             }
104         }
105     }
106
107     @Override
108     public void initialize() {
109         client = new Client();
110         updateStatus(ThingStatus.UNKNOWN);
111         rescheduleUpdate(0, false);
112     }
113
114     /**
115      * Call updateChannels asynchronously, possibly in a delayed fashion to throttle updates. This protects against a
116      * situation where many channels receive REFRESH command, e.g. when openHAB is requesting to update channels
117      *
118      * @return scheduled future
119      */
120     private ScheduledFuture<?> submitUpdateChannelsThrottled() {
121         long now = System.currentTimeMillis();
122         long nextRefresh = lastRefreshMillis + REFRESH_THROTTLE_MILLIS;
123         lastRefreshMillis = now;
124         if (now > nextRefresh) {
125             return scheduler.schedule(this::updateChannels, 0, TimeUnit.MILLISECONDS);
126         } else {
127             long delayMillis = nextRefresh - now;
128             return scheduler.schedule(this::updateChannels, delayMillis, TimeUnit.MILLISECONDS);
129         }
130     }
131
132     protected abstract void updateChannels();
133
134     protected abstract Request getRequest();
135
136     protected void update(int retry) {
137         if (retry < RETRIES) {
138             try {
139                 response = client.query(getRequest(), TIMEOUT_MILLIS);
140             } catch (FMIUnexpectedResponseException e) {
141                 handleError(e, retry);
142                 return;
143             } catch (FMIResponseException e) {
144                 handleError(e, retry);
145                 return;
146             }
147         } else {
148             logger.trace("Query failed. Retries exhausted, not trying again until next poll.");
149         }
150         // Update channel (if we have received a response)
151         updateChannels();
152         // Channels updated successfully or exhausted all retries. Reschedule new update
153         rescheduleUpdate(pollIntervalSeconds * 1000, false);
154     }
155
156     @Override
157     public void dispose() {
158         super.dispose();
159         response = null;
160         cancel(futureRef.getAndSet(null), true);
161         cancel(updateChannelsFutureRef.getAndSet(null), true);
162     }
163
164     protected static int lastValidIndex(Data data) {
165         if (data.values.length < 2) {
166             throw new IllegalStateException("Excepted at least two data items");
167         }
168         for (int i = data.values.length - 1; i >= 0; i--) {
169             if (data.values[i] != null) {
170                 return i;
171             }
172         }
173         // if we have reached here, it means that array was full of nulls
174         return -1;
175     }
176
177     protected static long floorToEvenMinutes(long epochSeconds, int roundMinutes) {
178         long roundSecs = roundMinutes * 60;
179         return (epochSeconds / roundSecs) * roundSecs;
180     }
181
182     protected static long ceilToEvenMinutes(long epochSeconds, int roundMinutes) {
183         double epochDouble = epochSeconds;
184         long roundSecs = roundMinutes * 60;
185         double roundSecsDouble = (roundMinutes * 60);
186         return (long) Math.ceil(epochDouble / roundSecsDouble) * roundSecs;
187     }
188
189     /**
190      * Update QuantityType channel state
191      *
192      * @param channelUID channel UID
193      * @param epochSecond value to update
194      */
195     protected <T extends Quantity<T>> void updateEpochSecondStateIfLinked(ChannelUID channelUID, long epochSecond) {
196         if (isLinked(channelUID)) {
197             updateState(channelUID, new DateTimeType(ZonedDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), UTC)
198                     .withZoneSameInstant(ZoneId.systemDefault())));
199         }
200     }
201
202     /**
203      * Update QuantityType or DecimalType channel state
204      *
205      * Updates UNDEF state when value is null
206      *
207      * @param channelUID channel UID
208      * @param value value to update
209      * @param unit unit associated with the value
210      */
211     protected void updateStateIfLinked(ChannelUID channelUID, @Nullable BigDecimal value, @Nullable Unit<?> unit) {
212         if (isLinked(channelUID)) {
213             if (value == null) {
214                 updateState(channelUID, UnDefType.UNDEF);
215             } else if (unit == null) {
216                 updateState(channelUID, new DecimalType(value));
217             } else {
218                 updateState(channelUID, new QuantityType<>(value, unit));
219             }
220         }
221     }
222
223     /**
224      * Unwrap optional value and log with ERROR if value is not present
225      *
226      * This should be used only when we expect value to be present, and the reason for missing value corresponds to
227      * description of {@link FMIUnexpectedResponseException}.
228      *
229      * @param optional optional to unwrap
230      * @param messageIfNotPresent logging message
231      * @param args arguments to logging
232      * @throws FMIUnexpectedResponseException when value is not present
233      * @return unwrapped value of the optional
234      */
235     protected <T> T unwrap(Optional<T> optional, String messageIfNotPresent, Object... args)
236             throws FMIUnexpectedResponseException {
237         if (optional.isPresent()) {
238             return optional.get();
239         } else {
240             // logger.error(messageIfNotPresent, args) avoided due to static analyzer
241             String formattedMessage = String.format(messageIfNotPresent, args);
242             throw new FMIUnexpectedResponseException(formattedMessage);
243         }
244     }
245
246     protected void handleError(FMIResponseException e, int retry) {
247         response = null;
248         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
249                 String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage()));
250         logger.trace("Query failed. Increase retry count {} and try again. Error: {} {}", retry, e.getClass().getName(),
251                 e.getMessage());
252         // Try again, with increased retry count
253         rescheduleUpdate(RETRY_DELAY_MILLIS, false, retry + 1);
254     }
255
256     protected void rescheduleUpdate(long delayMillis, boolean mayInterruptIfRunning) {
257         rescheduleUpdate(delayMillis, mayInterruptIfRunning, 0);
258     }
259
260     protected void rescheduleUpdate(long delayMillis, boolean mayInterruptIfRunning, int retry) {
261         cancel(futureRef.getAndSet(scheduler.schedule(() -> this.update(retry), delayMillis, TimeUnit.MILLISECONDS)),
262                 mayInterruptIfRunning);
263     }
264
265     private static void cancel(@Nullable ScheduledFuture<?> future, boolean mayInterruptIfRunning) {
266         if (future != null) {
267             future.cancel(mayInterruptIfRunning);
268         }
269     }
270 }