2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.fmiweather.internal;
15 import static org.openhab.binding.fmiweather.internal.BindingConstants.*;
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;
26 import javax.measure.Quantity;
27 import javax.measure.Unit;
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;
52 * The {@link AbstractWeatherHandler} is responsible for handling commands, which are
53 * sent to one of the channels.
55 * @author Sami Salonen - Initial contribution
58 public abstract class AbstractWeatherHandler extends BaseThingHandler {
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;
67 protected static final int TIMEOUT_MILLIS = 10_000;
68 private final Logger logger = LoggerFactory.getLogger(AbstractWeatherHandler.class);
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
75 private volatile long lastRefreshMillis = 0;
76 private final AtomicReference<@Nullable ScheduledFuture<?>> updateChannelsFutureRef = new AtomicReference<>();
78 public AbstractWeatherHandler(Thing thing) {
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");
94 logger.trace("REFRESH received. Delaying by {} ms to avoid throttle excessive REFRESH",
95 delayRemainingMillis);
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());
106 public void initialize() {
107 client = new Client();
108 updateStatus(ThingStatus.UNKNOWN);
109 rescheduleUpdate(0, false);
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
116 * @return scheduled future
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);
125 long delayMillis = nextRefresh - now;
126 return scheduler.schedule(this::updateChannels, delayMillis, TimeUnit.MILLISECONDS);
130 protected abstract void updateChannels();
132 protected abstract Request getRequest();
134 protected void update(int retry) {
135 if (retry < RETRIES) {
137 response = client.query(getRequest(), TIMEOUT_MILLIS);
138 } catch (FMIUnexpectedResponseException e) {
139 handleError(e, retry);
141 } catch (FMIResponseException e) {
142 handleError(e, retry);
146 logger.trace("Query failed. Retries exhausted, not trying again until next poll.");
148 // Update channel (if we have received a response)
150 // Channels updated successfully or exhausted all retries. Reschedule new update
151 rescheduleUpdate(pollIntervalSeconds * 1000, false);
155 public void dispose() {
158 cancel(futureRef.getAndSet(null), true);
159 cancel(updateChannelsFutureRef.getAndSet(null), true);
162 protected static int lastValidIndex(Data data) {
163 if (data.values.length < 2) {
164 throw new IllegalStateException("Excepted at least two data items");
166 if (data.values[0] == null) {
169 for (int i = 1; i < data.values.length; i++) {
170 if (data.values[i] == null) {
174 if (data.values[data.values.length - 1] == null) {
177 return data.values.length - 1;
180 protected static long floorToEvenMinutes(long epochSeconds, int roundMinutes) {
181 long roundSecs = roundMinutes * 60;
182 return (epochSeconds / roundSecs) * roundSecs;
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;
193 * Update QuantityType channel state
195 * @param channelUID channel UID
196 * @param epochSecond value to update
197 * @param unit unit associated with the value
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())));
207 * Update QuantityType or DecimalType channel state
209 * Updates UNDEF state when value is null
211 * @param channelUID channel UID
212 * @param value value to update
213 * @param unit unit associated with the value
215 protected void updateStateIfLinked(ChannelUID channelUID, @Nullable BigDecimal value, @Nullable Unit<?> unit) {
216 if (isLinked(channelUID)) {
218 updateState(channelUID, UnDefType.UNDEF);
219 } else if (unit == null) {
220 updateState(channelUID, new DecimalType(value));
222 updateState(channelUID, new QuantityType<>(value, unit));
228 * Unwrap optional value and log with ERROR if value is not present
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}.
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
239 protected <T> T unwrap(Optional<T> optional, String messageIfNotPresent, Object... args)
240 throws FMIUnexpectedResponseException {
241 if (optional.isPresent()) {
242 return optional.get();
244 // logger.error(messageIfNotPresent, args) avoided due to static analyzer
245 String formattedMessage = String.format(messageIfNotPresent, args);
246 throw new FMIUnexpectedResponseException(formattedMessage);
250 protected void handleError(FMIResponseException e, int retry) {
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(),
256 // Try again, with increased retry count
257 rescheduleUpdate(RETRY_DELAY_MILLIS, false, retry + 1);
260 protected void rescheduleUpdate(long delayMillis, boolean mayInterruptIfRunning) {
261 rescheduleUpdate(delayMillis, mayInterruptIfRunning, 0);
264 protected void rescheduleUpdate(long delayMillis, boolean mayInterruptIfRunning, int retry) {
265 cancel(futureRef.getAndSet(scheduler.schedule(() -> this.update(retry), delayMillis, TimeUnit.MILLISECONDS)),
266 mayInterruptIfRunning);
269 private static void cancel(@Nullable ScheduledFuture<?> future, boolean mayInterruptIfRunning) {
270 if (future != null) {
271 future.cancel(mayInterruptIfRunning);