]> git.basschouten.com Git - openhab-addons.git/blob
42f0cfeda98abde8e2c45ad7ad92ceecfab51e96
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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     public void handleCommand(ChannelUID channelUID, Command command) {
84         if (RefreshType.REFRESH == command) {
85             ScheduledFuture<?> prevFuture = updateChannelsFutureRef.get();
86             ScheduledFuture<?> newFuture = updateChannelsFutureRef
87                     .updateAndGet(fut -> fut == null || fut.isDone() ? submitUpdateChannelsThrottled() : fut);
88             assert newFuture != null; // invariant
89             if (logger.isTraceEnabled()) {
90                 long delayRemainingMillis = newFuture.getDelay(TimeUnit.MILLISECONDS);
91                 if (delayRemainingMillis <= 0) {
92                     logger.trace("REFRESH received. Channels are updated");
93                 } else {
94                     logger.trace("REFRESH received. Delaying by {} ms to avoid throttle excessive REFRESH",
95                             delayRemainingMillis);
96                 }
97                 if (prevFuture == newFuture) {
98                     logger.trace("REFRESH received. Previous refresh ongoing, will wait for it to complete in {} ms",
99                             lastRefreshMillis + REFRESH_THROTTLE_MILLIS - System.currentTimeMillis());
100                 }
101             }
102         }
103     }
104
105     @Override
106     public void initialize() {
107         client = new Client();
108         updateStatus(ThingStatus.UNKNOWN);
109         rescheduleUpdate(0, false);
110     }
111
112     /**
113      * Call updateChannels asynchronously, possibly in a delayed fashion to throttle updates. This protects against a
114      * situation where many channels receive REFRESH command, e.g. when openHAB is requesting to update channels
115      *
116      * @return scheduled future
117      */
118     private ScheduledFuture<?> submitUpdateChannelsThrottled() {
119         long now = System.currentTimeMillis();
120         long nextRefresh = lastRefreshMillis + REFRESH_THROTTLE_MILLIS;
121         lastRefreshMillis = now;
122         if (now > nextRefresh) {
123             return scheduler.schedule(this::updateChannels, 0, TimeUnit.MILLISECONDS);
124         } else {
125             long delayMillis = nextRefresh - now;
126             return scheduler.schedule(this::updateChannels, delayMillis, TimeUnit.MILLISECONDS);
127         }
128     }
129
130     protected abstract void updateChannels();
131
132     protected abstract Request getRequest();
133
134     protected void update(int retry) {
135         if (retry < RETRIES) {
136             try {
137                 response = client.query(getRequest(), TIMEOUT_MILLIS);
138             } catch (FMIUnexpectedResponseException e) {
139                 handleError(e, retry);
140                 return;
141             } catch (FMIResponseException e) {
142                 handleError(e, retry);
143                 return;
144             }
145         } else {
146             logger.trace("Query failed. Retries exhausted, not trying again until next poll.");
147         }
148         // Update channel (if we have received a response)
149         updateChannels();
150         // Channels updated successfully or exhausted all retries. Reschedule new update
151         rescheduleUpdate(pollIntervalSeconds * 1000, false);
152     }
153
154     @Override
155     public void dispose() {
156         super.dispose();
157         response = null;
158         cancel(futureRef.getAndSet(null), true);
159         cancel(updateChannelsFutureRef.getAndSet(null), true);
160     }
161
162     protected static int lastValidIndex(Data data) {
163         if (data.values.length < 2) {
164             throw new IllegalStateException("Excepted at least two data items");
165         }
166         if (data.values[0] == null) {
167             return -1;
168         }
169         for (int i = 1; i < data.values.length; i++) {
170             if (data.values[i] == null) {
171                 return i - 1;
172             }
173         }
174         if (data.values[data.values.length - 1] == null) {
175             return -1;
176         }
177         return data.values.length - 1;
178     }
179
180     protected static long floorToEvenMinutes(long epochSeconds, int roundMinutes) {
181         long roundSecs = roundMinutes * 60;
182         return (epochSeconds / roundSecs) * roundSecs;
183     }
184
185     protected static long ceilToEvenMinutes(long epochSeconds, int roundMinutes) {
186         double epochDouble = epochSeconds;
187         long roundSecs = roundMinutes * 60;
188         double roundSecsDouble = (roundMinutes * 60);
189         return (long) Math.ceil(epochDouble / roundSecsDouble) * roundSecs;
190     }
191
192     /**
193      * Update QuantityType channel state
194      *
195      * @param channelUID channel UID
196      * @param epochSecond value to update
197      * @param unit unit associated with the value
198      */
199     protected <T extends Quantity<T>> void updateEpochSecondStateIfLinked(ChannelUID channelUID, long epochSecond) {
200         if (isLinked(channelUID)) {
201             updateState(channelUID, new DateTimeType(ZonedDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), UTC)
202                     .withZoneSameInstant(ZoneId.systemDefault())));
203         }
204     }
205
206     /**
207      * Update QuantityType or DecimalType channel state
208      *
209      * Updates UNDEF state when value is null
210      *
211      * @param channelUID channel UID
212      * @param value value to update
213      * @param unit unit associated with the value
214      */
215     protected void updateStateIfLinked(ChannelUID channelUID, @Nullable BigDecimal value, @Nullable Unit<?> unit) {
216         if (isLinked(channelUID)) {
217             if (value == null) {
218                 updateState(channelUID, UnDefType.UNDEF);
219             } else if (unit == null) {
220                 updateState(channelUID, new DecimalType(value));
221             } else {
222                 updateState(channelUID, new QuantityType<>(value, unit));
223             }
224         }
225     }
226
227     /**
228      * Unwrap optional value and log with ERROR if value is not present
229      *
230      * This should be used only when we expect value to be present, and the reason for missing value corresponds to
231      * description of {@link FMIUnexpectedResponseException}.
232      *
233      * @param optional optional to unwrap
234      * @param messageIfNotPresent logging message
235      * @param args arguments to logging
236      * @throws FMIUnexpectedResponseException when value is not present
237      * @return unwrapped value of the optional
238      */
239     protected <T> T unwrap(Optional<T> optional, String messageIfNotPresent, Object... args)
240             throws FMIUnexpectedResponseException {
241         if (optional.isPresent()) {
242             return optional.get();
243         } else {
244             // logger.error(messageIfNotPresent, args) avoided due to static analyzer
245             String formattedMessage = String.format(messageIfNotPresent, args);
246             throw new FMIUnexpectedResponseException(formattedMessage);
247         }
248     }
249
250     protected void handleError(FMIResponseException e, int retry) {
251         response = null;
252         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
253                 String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage()));
254         logger.trace("Query failed. Increase retry count {} and try again. Error: {} {}", retry, e.getClass().getName(),
255                 e.getMessage());
256         // Try again, with increased retry count
257         rescheduleUpdate(RETRY_DELAY_MILLIS, false, retry + 1);
258     }
259
260     protected void rescheduleUpdate(long delayMillis, boolean mayInterruptIfRunning) {
261         rescheduleUpdate(delayMillis, mayInterruptIfRunning, 0);
262     }
263
264     protected void rescheduleUpdate(long delayMillis, boolean mayInterruptIfRunning, int retry) {
265         cancel(futureRef.getAndSet(scheduler.schedule(() -> this.update(retry), delayMillis, TimeUnit.MILLISECONDS)),
266                 mayInterruptIfRunning);
267     }
268
269     private static void cancel(@Nullable ScheduledFuture<?> future, boolean mayInterruptIfRunning) {
270         if (future != null) {
271             future.cancel(mayInterruptIfRunning);
272         }
273     }
274 }