]> git.basschouten.com Git - openhab-addons.git/blob
13cf7735b361d9b4ee8757e30f54ffd9ea7bcd9c
[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.ecowatt.internal.handler;
14
15 import static org.openhab.binding.ecowatt.internal.EcowattBindingConstants.*;
16
17 import java.time.Duration;
18 import java.time.LocalDateTime;
19 import java.time.ZonedDateTime;
20 import java.time.format.DateTimeFormatter;
21 import java.time.temporal.ChronoUnit;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.eclipse.jetty.client.HttpClient;
28 import org.openhab.binding.ecowatt.internal.configuration.EcowattConfiguration;
29 import org.openhab.binding.ecowatt.internal.exception.EcowattApiLimitException;
30 import org.openhab.binding.ecowatt.internal.restapi.EcowattApiResponse;
31 import org.openhab.binding.ecowatt.internal.restapi.EcowattDaySignals;
32 import org.openhab.binding.ecowatt.internal.restapi.EcowattRestApi;
33 import org.openhab.core.auth.client.oauth2.OAuthFactory;
34 import org.openhab.core.cache.ExpiringCache;
35 import org.openhab.core.i18n.CommunicationException;
36 import org.openhab.core.i18n.TimeZoneProvider;
37 import org.openhab.core.i18n.TranslationProvider;
38 import org.openhab.core.library.types.DecimalType;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.thing.ThingStatus;
42 import org.openhab.core.thing.ThingStatusDetail;
43 import org.openhab.core.thing.binding.BaseThingHandler;
44 import org.openhab.core.types.Command;
45 import org.openhab.core.types.RefreshType;
46 import org.openhab.core.types.State;
47 import org.openhab.core.types.UnDefType;
48 import org.osgi.framework.Bundle;
49 import org.osgi.framework.FrameworkUtil;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * The {@link EcowattHandler} is responsible for updating the state of the channels
55  *
56  * @author Laurent Garnier - Initial contribution
57  */
58 @NonNullByDefault
59 public class EcowattHandler extends BaseThingHandler {
60
61     private final Logger logger = LoggerFactory.getLogger(EcowattHandler.class);
62
63     private final OAuthFactory oAuthFactory;
64     private final HttpClient httpClient;
65     private final TranslationProvider i18nProvider;
66     private final TimeZoneProvider timeZoneProvider;
67     private final Bundle bundle;
68
69     private @Nullable EcowattRestApi api;
70     private ExpiringCache<EcowattApiResponse> cachedApiResponse = new ExpiringCache<>(Duration.ofHours(4),
71             this::getApiResponse); // cache the API response during 4 hours
72
73     private @Nullable ScheduledFuture<?> updateJob;
74
75     public EcowattHandler(Thing thing, OAuthFactory oAuthFactory, HttpClient httpClient,
76             TranslationProvider i18nProvider, TimeZoneProvider timeZoneProvider) {
77         super(thing);
78         this.oAuthFactory = oAuthFactory;
79         this.httpClient = httpClient;
80         this.i18nProvider = i18nProvider;
81         this.timeZoneProvider = timeZoneProvider;
82         this.bundle = FrameworkUtil.getBundle(this.getClass());
83     }
84
85     @Override
86     public void handleCommand(ChannelUID channelUID, Command command) {
87         if (command == RefreshType.REFRESH) {
88             updateChannel(channelUID.getId());
89         }
90     }
91
92     @Override
93     public void initialize() {
94         EcowattConfiguration config = getConfigAs(EcowattConfiguration.class);
95
96         final String idClient = config.idClient;
97         final String idSecret = config.idSecret;
98
99         if (idClient.isBlank() || idSecret.isBlank()) {
100             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
101                     "@text/offline.config-error-unset-parameters");
102         } else {
103             api = new EcowattRestApi(oAuthFactory, httpClient, thing.getUID().getAsString(), idClient, idSecret);
104             updateStatus(ThingStatus.UNKNOWN);
105             scheduleNextUpdate(0, true);
106         }
107     }
108
109     @Override
110     public void dispose() {
111         stopScheduledJob();
112         EcowattRestApi localApi = api;
113         if (localApi != null) {
114             localApi.dispose();
115             api = null;
116         }
117     }
118
119     /**
120      * Schedule the next update of channels.
121      *
122      * After this update is run, a new update will be rescheduled, either just after the API is reachable again or at
123      * the beginning of the following hour.
124      *
125      * @param delayInSeconds the delay in seconds before running the next update
126      * @param retryIfApiLimitReached true if a retry is expected when the update fails due to reached API limit
127      */
128     private void scheduleNextUpdate(long delayInSeconds, boolean retryIfApiLimitReached) {
129         logger.debug("scheduleNextUpdate delay={}s retryIfLimitReached={}", delayInSeconds, retryIfApiLimitReached);
130         updateJob = scheduler.schedule(() -> {
131             int retryDelay = updateChannels(retryIfApiLimitReached);
132             long delayNextUpdate;
133             if (retryDelay > 0) {
134                 // Schedule a new update just after the API is reachable again
135                 logger.debug("retryDelay {}", retryDelay);
136                 delayNextUpdate = retryDelay;
137             } else {
138                 // Schedule a new update at the beginning of the following hour
139                 final LocalDateTime now = LocalDateTime.now();
140                 final LocalDateTime beginningNextHour = now.plusHours(1).truncatedTo(ChronoUnit.HOURS);
141                 delayNextUpdate = ChronoUnit.SECONDS.between(now, beginningNextHour);
142             }
143             // Add 3s of additional delay for security...
144             delayNextUpdate += 3;
145             scheduleNextUpdate(delayNextUpdate, retryDelay == 0);
146         }, delayInSeconds, TimeUnit.SECONDS);
147     }
148
149     private void stopScheduledJob() {
150         ScheduledFuture<?> job = updateJob;
151         if (job != null) {
152             job.cancel(true);
153             updateJob = null;
154         }
155     }
156
157     private EcowattApiResponse getApiResponse() {
158         EcowattRestApi localApi = api;
159         if (localApi == null) {
160             return new EcowattApiResponse();
161         }
162
163         EcowattApiResponse response;
164         try {
165             response = localApi.getSignals();
166         } catch (CommunicationException e) {
167             Throwable cause = e.getCause();
168             if (cause != null) {
169                 logger.warn("{}: {}", e.getMessage(bundle, i18nProvider), cause.getMessage());
170             } else {
171                 logger.warn("{}", e.getMessage(bundle, i18nProvider));
172             }
173             response = new EcowattApiResponse(e);
174         }
175         return response;
176     }
177
178     private int updateChannels(boolean retryIfApiLimitReached) {
179         return updateChannel(null, retryIfApiLimitReached);
180     }
181
182     private void updateChannel(String channelId) {
183         updateChannel(channelId, false);
184     }
185
186     private synchronized int updateChannel(@Nullable String channelId, boolean retryIfApiLimitReached) {
187         logger.debug("updateChannel channelId={}, retryIfApiLimitReached={}", channelId, retryIfApiLimitReached);
188         int retryDelay = 0;
189         EcowattApiResponse response = cachedApiResponse.getValue();
190         if (response == null || !response.succeeded()) {
191             CommunicationException exception = response == null ? null : response.getException();
192             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
193                     exception == null ? null : exception.getRawMessage());
194
195             // Invalidate the cache to be sure the next request will trigger the API
196             cachedApiResponse.invalidateValue();
197
198             if (retryIfApiLimitReached && exception instanceof EcowattApiLimitException
199                     && ((EcowattApiLimitException) exception).getRetryAfter() > 0) {
200                 // Will retry when the API is available again (just after the limit expired)
201                 retryDelay = ((EcowattApiLimitException) exception).getRetryAfter();
202             }
203         } else {
204             updateStatus(ThingStatus.ONLINE);
205         }
206
207         ZonedDateTime now = ZonedDateTime.now(timeZoneProvider.getTimeZone());
208         logger.debug("now {}", now.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
209         if ((channelId == null || CHANNEL_TODAY_SIGNAL.equals(channelId)) && isLinked(CHANNEL_TODAY_SIGNAL)) {
210             updateState(CHANNEL_TODAY_SIGNAL, getDaySignalState(response, now));
211         }
212         if ((channelId == null || CHANNEL_TOMORROW_SIGNAL.equals(channelId)) && isLinked(CHANNEL_TOMORROW_SIGNAL)) {
213             updateState(CHANNEL_TOMORROW_SIGNAL, getDaySignalState(response, now.plusDays(1)));
214         }
215         if ((channelId == null || CHANNEL_IN_TWO_DAYS_SIGNAL.equals(channelId))
216                 && isLinked(CHANNEL_IN_TWO_DAYS_SIGNAL)) {
217             updateState(CHANNEL_IN_TWO_DAYS_SIGNAL, getDaySignalState(response, now.plusDays(2)));
218         }
219         if ((channelId == null || CHANNEL_IN_THREE_DAYS_SIGNAL.equals(channelId))
220                 && isLinked(CHANNEL_IN_THREE_DAYS_SIGNAL)) {
221             updateState(CHANNEL_IN_THREE_DAYS_SIGNAL, getDaySignalState(response, now.plusDays(3)));
222         }
223         if ((channelId == null || CHANNEL_CURRENT_HOUR_SIGNAL.equals(channelId))
224                 && isLinked(CHANNEL_CURRENT_HOUR_SIGNAL)) {
225             updateState(CHANNEL_CURRENT_HOUR_SIGNAL, getHourSignalState(response, now));
226         }
227
228         return retryDelay;
229     }
230
231     /**
232      * Get the signal applicable for a given day from the API response
233      *
234      * @param response the API response
235      * @param dateTime the date and time to consider
236      * @return the found valid signal as a channel state or UndefType.UNDEF if not found
237      */
238     public static State getDaySignalState(@Nullable EcowattApiResponse response, ZonedDateTime dateTime) {
239         EcowattDaySignals signals = response == null ? null : response.getDaySignals(dateTime);
240         return signals != null && signals.getDaySignal() >= 1 && signals.getDaySignal() <= 3
241                 ? new DecimalType(signals.getDaySignal())
242                 : UnDefType.UNDEF;
243     }
244
245     /**
246      * Get the signal applicable for a given day and hour from the API response
247      *
248      * @param response the API response
249      * @param dateTime the date and time to consider
250      * @return the found valid signal as a channel state or UndefType.UNDEF if not found
251      */
252     public static State getHourSignalState(@Nullable EcowattApiResponse response, ZonedDateTime dateTime) {
253         EcowattDaySignals signals = response == null ? null : response.getDaySignals(dateTime);
254         ZonedDateTime day = signals == null ? null : signals.getDay();
255         if (signals != null && day != null) {
256             // Move the current time to the same offset as the data returned by the API to get and use the right current
257             // hour index in these data
258             int hour = dateTime.withZoneSameInstant(day.getZone()).getHour();
259             int value = signals.getHourSignal(hour);
260             LoggerFactory.getLogger(EcowattHandler.class).debug("hour {} value {}", hour, value);
261             if (value >= 1 && value <= 3) {
262                 return new DecimalType(value);
263             }
264         }
265         return UnDefType.UNDEF;
266     }
267 }