]> git.basschouten.com Git - openhab-addons.git/blob
c6fd16e6b06cd2307d3e3aa597f793da0c94628d
[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     @Override
120     public void handleRemoval() {
121         EcowattRestApi localApi = api;
122         if (localApi != null) {
123             localApi.deleteServiceAndAccessToken();
124         }
125         super.handleRemoval();
126     }
127
128     /**
129      * Schedule the next update of channels.
130      *
131      * After this update is run, a new update will be rescheduled, either just after the API is reachable again or at
132      * the beginning of the following hour.
133      *
134      * @param delayInSeconds the delay in seconds before running the next update
135      * @param retryIfApiLimitReached true if a retry is expected when the update fails due to reached API limit
136      */
137     private void scheduleNextUpdate(long delayInSeconds, boolean retryIfApiLimitReached) {
138         logger.debug("scheduleNextUpdate delay={}s retryIfLimitReached={}", delayInSeconds, retryIfApiLimitReached);
139         updateJob = scheduler.schedule(() -> {
140             int retryDelay = updateChannels(retryIfApiLimitReached);
141             long delayNextUpdate;
142             if (retryDelay > 0) {
143                 // Schedule a new update just after the API is reachable again
144                 logger.debug("retryDelay {}", retryDelay);
145                 delayNextUpdate = retryDelay;
146             } else {
147                 // Schedule a new update at the beginning of the following hour
148                 final LocalDateTime now = LocalDateTime.now();
149                 final LocalDateTime beginningNextHour = now.plusHours(1).truncatedTo(ChronoUnit.HOURS);
150                 delayNextUpdate = ChronoUnit.SECONDS.between(now, beginningNextHour);
151             }
152             // Add 3s of additional delay for security...
153             delayNextUpdate += 3;
154             scheduleNextUpdate(delayNextUpdate, retryDelay == 0);
155         }, delayInSeconds, TimeUnit.SECONDS);
156     }
157
158     private void stopScheduledJob() {
159         ScheduledFuture<?> job = updateJob;
160         if (job != null) {
161             job.cancel(true);
162             updateJob = null;
163         }
164     }
165
166     private EcowattApiResponse getApiResponse() {
167         EcowattRestApi localApi = api;
168         if (localApi == null) {
169             return new EcowattApiResponse();
170         }
171
172         EcowattApiResponse response;
173         try {
174             response = localApi.getSignals();
175         } catch (CommunicationException e) {
176             Throwable cause = e.getCause();
177             if (cause != null) {
178                 logger.warn("{}: {}", e.getMessage(bundle, i18nProvider), cause.getMessage());
179             } else {
180                 logger.warn("{}", e.getMessage(bundle, i18nProvider));
181             }
182             response = new EcowattApiResponse(e);
183         }
184         return response;
185     }
186
187     private int updateChannels(boolean retryIfApiLimitReached) {
188         return updateChannel(null, retryIfApiLimitReached);
189     }
190
191     private void updateChannel(String channelId) {
192         updateChannel(channelId, false);
193     }
194
195     private synchronized int updateChannel(@Nullable String channelId, boolean retryIfApiLimitReached) {
196         logger.debug("updateChannel channelId={}, retryIfApiLimitReached={}", channelId, retryIfApiLimitReached);
197         int retryDelay = 0;
198         EcowattApiResponse response = cachedApiResponse.getValue();
199         if (response == null || !response.succeeded()) {
200             CommunicationException exception = response == null ? null : response.getException();
201             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
202                     exception == null ? null : exception.getRawMessage());
203
204             // Invalidate the cache to be sure the next request will trigger the API
205             cachedApiResponse.invalidateValue();
206
207             if (retryIfApiLimitReached && exception instanceof EcowattApiLimitException
208                     && ((EcowattApiLimitException) exception).getRetryAfter() > 0) {
209                 // Will retry when the API is available again (just after the limit expired)
210                 retryDelay = ((EcowattApiLimitException) exception).getRetryAfter();
211             }
212         } else {
213             updateStatus(ThingStatus.ONLINE);
214         }
215
216         ZonedDateTime now = ZonedDateTime.now(timeZoneProvider.getTimeZone());
217         logger.debug("now {}", now.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
218         if ((channelId == null || CHANNEL_TODAY_SIGNAL.equals(channelId)) && isLinked(CHANNEL_TODAY_SIGNAL)) {
219             updateState(CHANNEL_TODAY_SIGNAL, getDaySignalState(response, now));
220         }
221         if ((channelId == null || CHANNEL_TOMORROW_SIGNAL.equals(channelId)) && isLinked(CHANNEL_TOMORROW_SIGNAL)) {
222             updateState(CHANNEL_TOMORROW_SIGNAL, getDaySignalState(response, now.plusDays(1)));
223         }
224         if ((channelId == null || CHANNEL_IN_TWO_DAYS_SIGNAL.equals(channelId))
225                 && isLinked(CHANNEL_IN_TWO_DAYS_SIGNAL)) {
226             updateState(CHANNEL_IN_TWO_DAYS_SIGNAL, getDaySignalState(response, now.plusDays(2)));
227         }
228         if ((channelId == null || CHANNEL_IN_THREE_DAYS_SIGNAL.equals(channelId))
229                 && isLinked(CHANNEL_IN_THREE_DAYS_SIGNAL)) {
230             updateState(CHANNEL_IN_THREE_DAYS_SIGNAL, getDaySignalState(response, now.plusDays(3)));
231         }
232         if ((channelId == null || CHANNEL_CURRENT_HOUR_SIGNAL.equals(channelId))
233                 && isLinked(CHANNEL_CURRENT_HOUR_SIGNAL)) {
234             updateState(CHANNEL_CURRENT_HOUR_SIGNAL, getHourSignalState(response, now));
235         }
236
237         return retryDelay;
238     }
239
240     /**
241      * Get the signal applicable for a given day from the API response
242      *
243      * @param response the API response
244      * @param dateTime the date and time to consider
245      * @return the found valid signal as a channel state or UndefType.UNDEF if not found
246      */
247     public static State getDaySignalState(@Nullable EcowattApiResponse response, ZonedDateTime dateTime) {
248         EcowattDaySignals signals = response == null ? null : response.getDaySignals(dateTime);
249         return signals != null && signals.getDaySignal() >= 1 && signals.getDaySignal() <= 3
250                 ? new DecimalType(signals.getDaySignal())
251                 : UnDefType.UNDEF;
252     }
253
254     /**
255      * Get the signal applicable for a given day and hour from the API response
256      *
257      * @param response the API response
258      * @param dateTime the date and time to consider
259      * @return the found valid signal as a channel state or UndefType.UNDEF if not found
260      */
261     public static State getHourSignalState(@Nullable EcowattApiResponse response, ZonedDateTime dateTime) {
262         EcowattDaySignals signals = response == null ? null : response.getDaySignals(dateTime);
263         ZonedDateTime day = signals == null ? null : signals.getDay();
264         if (signals != null && day != null) {
265             // Move the current time to the same offset as the data returned by the API to get and use the right current
266             // hour index in these data
267             int hour = dateTime.withZoneSameInstant(day.getZone()).getHour();
268             int value = signals.getHourSignal(hour);
269             LoggerFactory.getLogger(EcowattHandler.class).debug("hour {} value {}", hour, value);
270             if (value >= 1 && value <= 3) {
271                 return new DecimalType(value);
272             }
273         }
274         return UnDefType.UNDEF;
275     }
276 }