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 * Schedule the next update of channels.
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.
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
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;
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);
143 // Add 3s of additional delay for security...
144 delayNextUpdate += 3;
145 scheduleNextUpdate(delayNextUpdate, retryDelay == 0);
146 }, delayInSeconds, TimeUnit.SECONDS);
149 private void stopScheduledJob() {
150 ScheduledFuture<?> job = updateJob;
157 private EcowattApiResponse getApiResponse() {
158 EcowattRestApi localApi = api;
159 if (localApi == null) {
160 return new EcowattApiResponse();
163 EcowattApiResponse response;
165 response = localApi.getSignals();
166 } catch (CommunicationException e) {
167 Throwable cause = e.getCause();
169 logger.warn("{}: {}", e.getMessage(bundle, i18nProvider), cause.getMessage());
171 logger.warn("{}", e.getMessage(bundle, i18nProvider));
173 response = new EcowattApiResponse(e);
178 private int updateChannels(boolean retryIfApiLimitReached) {
179 return updateChannel(null, retryIfApiLimitReached);
182 private void updateChannel(String channelId) {
183 updateChannel(channelId, false);
186 private synchronized int updateChannel(@Nullable String channelId, boolean retryIfApiLimitReached) {
187 logger.debug("updateChannel channelId={}, retryIfApiLimitReached={}", channelId, retryIfApiLimitReached);
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());
195 // Invalidate the cache to be sure the next request will trigger the API
196 cachedApiResponse.invalidateValue();
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();
204 updateStatus(ThingStatus.ONLINE);
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));
212 if ((channelId == null || CHANNEL_TOMORROW_SIGNAL.equals(channelId)) && isLinked(CHANNEL_TOMORROW_SIGNAL)) {
213 updateState(CHANNEL_TOMORROW_SIGNAL, getDaySignalState(response, now.plusDays(1)));
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)));
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)));
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));
232 * Get the signal applicable for a given day from the API response
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
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())
246 * Get the signal applicable for a given day and hour from the API response
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
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);
265 return UnDefType.UNDEF;