2 * Copyright (c) 2010-2023 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.ecowatt.internal.handler;
15 import static org.openhab.binding.ecowatt.internal.EcowattBindingConstants.*;
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;
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;
54 * The {@link EcowattHandler} is responsible for updating the state of the channels
56 * @author Laurent Garnier - Initial contribution
59 public class EcowattHandler extends BaseThingHandler {
61 private final Logger logger = LoggerFactory.getLogger(EcowattHandler.class);
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;
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
73 private @Nullable ScheduledFuture<?> updateJob;
75 public EcowattHandler(Thing thing, OAuthFactory oAuthFactory, HttpClient httpClient,
76 TranslationProvider i18nProvider, TimeZoneProvider timeZoneProvider) {
78 this.oAuthFactory = oAuthFactory;
79 this.httpClient = httpClient;
80 this.i18nProvider = i18nProvider;
81 this.timeZoneProvider = timeZoneProvider;
82 this.bundle = FrameworkUtil.getBundle(this.getClass());
86 public void handleCommand(ChannelUID channelUID, Command command) {
87 if (command == RefreshType.REFRESH) {
88 updateChannel(channelUID.getId());
93 public void initialize() {
94 EcowattConfiguration config = getConfigAs(EcowattConfiguration.class);
96 final String idClient = config.idClient;
97 final String idSecret = config.idSecret;
99 if (idClient.isBlank() || idSecret.isBlank()) {
100 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
101 "@text/offline.config-error-unset-parameters");
103 api = new EcowattRestApi(oAuthFactory, httpClient, thing.getUID().getAsString(), idClient, idSecret);
104 updateStatus(ThingStatus.UNKNOWN);
105 scheduleNextUpdate(0, true);
110 public void dispose() {
112 EcowattRestApi localApi = api;
113 if (localApi != null) {
120 public void handleRemoval() {
121 EcowattRestApi localApi = api;
122 if (localApi != null) {
123 localApi.deleteServiceAndAccessToken();
125 super.handleRemoval();
129 * Schedule the next update of channels.
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.
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
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;
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);
152 // Add 3s of additional delay for security...
153 delayNextUpdate += 3;
154 scheduleNextUpdate(delayNextUpdate, retryDelay == 0);
155 }, delayInSeconds, TimeUnit.SECONDS);
158 private void stopScheduledJob() {
159 ScheduledFuture<?> job = updateJob;
166 private EcowattApiResponse getApiResponse() {
167 EcowattRestApi localApi = api;
168 if (localApi == null) {
169 return new EcowattApiResponse();
172 EcowattApiResponse response;
174 response = localApi.getSignals();
175 } catch (CommunicationException e) {
176 Throwable cause = e.getCause();
178 logger.warn("{}: {}", e.getMessage(bundle, i18nProvider), cause.getMessage());
180 logger.warn("{}", e.getMessage(bundle, i18nProvider));
182 response = new EcowattApiResponse(e);
187 private int updateChannels(boolean retryIfApiLimitReached) {
188 return updateChannel(null, retryIfApiLimitReached);
191 private void updateChannel(String channelId) {
192 updateChannel(channelId, false);
195 private synchronized int updateChannel(@Nullable String channelId, boolean retryIfApiLimitReached) {
196 logger.debug("updateChannel channelId={}, retryIfApiLimitReached={}", channelId, retryIfApiLimitReached);
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());
204 // Invalidate the cache to be sure the next request will trigger the API
205 cachedApiResponse.invalidateValue();
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();
213 updateStatus(ThingStatus.ONLINE);
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));
221 if ((channelId == null || CHANNEL_TOMORROW_SIGNAL.equals(channelId)) && isLinked(CHANNEL_TOMORROW_SIGNAL)) {
222 updateState(CHANNEL_TOMORROW_SIGNAL, getDaySignalState(response, now.plusDays(1)));
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)));
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)));
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));
241 * Get the signal applicable for a given day from the API response
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
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())
255 * Get the signal applicable for a given day and hour from the API response
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
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);
274 return UnDefType.UNDEF;