]> git.basschouten.com Git - openhab-addons.git/blob
ca0e911942ba70c30d0f529da6cdfe65e386a66c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.awattar.internal.handler;
14
15 import static org.openhab.binding.awattar.internal.AwattarBindingConstants.BINDING_ID;
16 import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANNEL_ACTIVE;
17 import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANNEL_COUNTDOWN;
18 import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANNEL_END;
19 import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANNEL_HOURS;
20 import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANNEL_REMAINING;
21 import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANNEL_START;
22 import static org.openhab.binding.awattar.internal.AwattarUtil.getCalendarForHour;
23 import static org.openhab.binding.awattar.internal.AwattarUtil.getDateTimeType;
24 import static org.openhab.binding.awattar.internal.AwattarUtil.getDuration;
25 import static org.openhab.binding.awattar.internal.AwattarUtil.getMillisToNextMinute;
26
27 import java.time.Instant;
28 import java.time.ZoneId;
29 import java.time.ZonedDateTime;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.Comparator;
33 import java.util.List;
34 import java.util.SortedSet;
35 import java.util.concurrent.ScheduledFuture;
36 import java.util.concurrent.TimeUnit;
37
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.openhab.binding.awattar.internal.AwattarBestPriceConfiguration;
41 import org.openhab.binding.awattar.internal.AwattarBestPriceResult;
42 import org.openhab.binding.awattar.internal.AwattarConsecutiveBestPriceResult;
43 import org.openhab.binding.awattar.internal.AwattarNonConsecutiveBestPriceResult;
44 import org.openhab.binding.awattar.internal.AwattarPrice;
45 import org.openhab.core.i18n.TimeZoneProvider;
46 import org.openhab.core.library.types.OnOffType;
47 import org.openhab.core.library.types.StringType;
48 import org.openhab.core.thing.Bridge;
49 import org.openhab.core.thing.Channel;
50 import org.openhab.core.thing.ChannelUID;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatus;
53 import org.openhab.core.thing.ThingStatusDetail;
54 import org.openhab.core.thing.binding.BaseThingHandler;
55 import org.openhab.core.thing.type.ChannelKind;
56 import org.openhab.core.types.Command;
57 import org.openhab.core.types.RefreshType;
58 import org.openhab.core.types.State;
59 import org.openhab.core.types.UnDefType;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 /**
64  * The {@link AwattarBestPriceHandler} is responsible for computing the best prices for a given configuration.
65  *
66  * @author Wolfgang Klimt - Initial contribution
67  */
68 @NonNullByDefault
69 public class AwattarBestPriceHandler extends BaseThingHandler {
70     private static final int THING_REFRESH_INTERVAL = 60;
71
72     private final Logger logger = LoggerFactory.getLogger(AwattarBestPriceHandler.class);
73
74     private @Nullable ScheduledFuture<?> thingRefresher;
75
76     private final TimeZoneProvider timeZoneProvider;
77
78     public AwattarBestPriceHandler(Thing thing, TimeZoneProvider timeZoneProvider) {
79         super(thing);
80         this.timeZoneProvider = timeZoneProvider;
81     }
82
83     @Override
84     public void initialize() {
85         AwattarBestPriceConfiguration config = getConfigAs(AwattarBestPriceConfiguration.class);
86
87         if (config.length >= config.rangeDuration) {
88             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/error.length.value");
89             return;
90         }
91
92         synchronized (this) {
93             ScheduledFuture<?> localRefresher = thingRefresher;
94             if (localRefresher == null || localRefresher.isCancelled()) {
95                 /*
96                  * The scheduler is required to run exactly at minute borders, hence we can't use scheduleWithFixedDelay
97                  * here
98                  */
99                 thingRefresher = scheduler.scheduleAtFixedRate(this::refreshChannels,
100                         getMillisToNextMinute(1, timeZoneProvider), THING_REFRESH_INTERVAL * 1000,
101                         TimeUnit.MILLISECONDS);
102             }
103         }
104         updateStatus(ThingStatus.UNKNOWN);
105     }
106
107     @Override
108     public void dispose() {
109         ScheduledFuture<?> localRefresher = thingRefresher;
110         if (localRefresher != null) {
111             localRefresher.cancel(true);
112             thingRefresher = null;
113         }
114     }
115
116     public void refreshChannels() {
117         updateStatus(ThingStatus.ONLINE);
118         for (Channel channel : getThing().getChannels()) {
119             ChannelUID channelUID = channel.getUID();
120             if (ChannelKind.STATE.equals(channel.getKind()) && isLinked(channelUID)) {
121                 refreshChannel(channel.getUID());
122             }
123         }
124     }
125
126     public void refreshChannel(ChannelUID channelUID) {
127         State state = UnDefType.UNDEF;
128         Bridge bridge = getBridge();
129         if (bridge == null) {
130             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/error.bridge.missing");
131             updateState(channelUID, state);
132             return;
133         }
134         AwattarBridgeHandler bridgeHandler = (AwattarBridgeHandler) bridge.getHandler();
135         if (bridgeHandler == null || bridgeHandler.getPrices() == null) {
136             logger.debug("No prices available, so can't refresh channel.");
137             // no prices available, can't continue
138             updateState(channelUID, state);
139             return;
140         }
141         AwattarBestPriceConfiguration config = getConfigAs(AwattarBestPriceConfiguration.class);
142         TimeRange timerange = getRange(config.rangeStart, config.rangeDuration, bridgeHandler.getTimeZone());
143         if (!(bridgeHandler.containsPriceFor(timerange.start()) && bridgeHandler.containsPriceFor(timerange.end()))) {
144             updateState(channelUID, state);
145             return;
146         }
147
148         AwattarBestPriceResult result;
149         List<AwattarPrice> range = getPriceRange(bridgeHandler, timerange);
150
151         if (config.consecutive) {
152             range.sort(Comparator.comparing(AwattarPrice::timerange));
153             AwattarConsecutiveBestPriceResult res = new AwattarConsecutiveBestPriceResult(
154                     range.subList(0, config.length), bridgeHandler.getTimeZone());
155
156             for (int i = 1; i <= range.size() - config.length; i++) {
157                 AwattarConsecutiveBestPriceResult res2 = new AwattarConsecutiveBestPriceResult(
158                         range.subList(i, i + config.length), bridgeHandler.getTimeZone());
159                 if (res2.getPriceSum() < res.getPriceSum()) {
160                     res = res2;
161                 }
162             }
163             result = res;
164         } else {
165             range.sort(Comparator.naturalOrder());
166
167             // sort in descending order when inverted
168             if (config.inverted) {
169                 Collections.reverse(range);
170             }
171
172             AwattarNonConsecutiveBestPriceResult res = new AwattarNonConsecutiveBestPriceResult(
173                     bridgeHandler.getTimeZone());
174
175             // take up to config.length prices
176             for (int i = 0; i < Math.min(config.length, range.size()); i++) {
177                 res.addMember(range.get(i));
178             }
179
180             result = res;
181         }
182         String channelId = channelUID.getIdWithoutGroup();
183         long diff;
184         switch (channelId) {
185             case CHANNEL_ACTIVE:
186                 state = OnOffType.from(result.isActive());
187                 break;
188             case CHANNEL_START:
189                 state = getDateTimeType(result.getStart(), timeZoneProvider);
190                 break;
191             case CHANNEL_END:
192                 state = getDateTimeType(result.getEnd(), timeZoneProvider);
193                 break;
194             case CHANNEL_COUNTDOWN:
195                 diff = result.getStart() - Instant.now().toEpochMilli();
196                 if (diff >= 0) {
197                     state = getDuration(diff);
198                 }
199                 break;
200             case CHANNEL_REMAINING:
201                 diff = result.getEnd() - Instant.now().toEpochMilli();
202                 if (result.isActive()) {
203                     state = getDuration(diff);
204                 }
205                 break;
206             case CHANNEL_HOURS:
207                 state = new StringType(result.getHours());
208                 break;
209             default:
210                 logger.warn("Unknown channel id {} for Thing type {}", channelUID, getThing().getThingTypeUID());
211         }
212         updateState(channelUID, state);
213     }
214
215     @Override
216     public void handleCommand(ChannelUID channelUID, Command command) {
217         if (command instanceof RefreshType) {
218             refreshChannel(channelUID);
219         } else {
220             logger.debug("Binding {} only supports refresh command", BINDING_ID);
221         }
222     }
223
224     private List<AwattarPrice> getPriceRange(AwattarBridgeHandler bridgeHandler, TimeRange range) {
225         List<AwattarPrice> result = new ArrayList<>();
226         SortedSet<AwattarPrice> prices = bridgeHandler.getPrices();
227         if (prices == null) {
228             logger.debug("No prices available, can't compute ranges");
229             return result;
230         }
231         result.addAll(prices.stream().filter(x -> range.contains(x.timerange())).toList());
232         return result;
233     }
234
235     protected TimeRange getRange(int start, int duration, ZoneId zoneId) {
236         ZonedDateTime startCal = getCalendarForHour(start, zoneId);
237         ZonedDateTime endCal = startCal.plusHours(duration);
238         ZonedDateTime now = ZonedDateTime.now(zoneId);
239         if (now.getHour() < start) {
240             // we are before the range, so we might be still within the last range
241             startCal = startCal.minusDays(1);
242             endCal = endCal.minusDays(1);
243         }
244         if (endCal.toInstant().toEpochMilli() < Instant.now().toEpochMilli()) {
245             // span is in the past, add one day
246             startCal = startCal.plusDays(1);
247             endCal = endCal.plusDays(1);
248         }
249         return new TimeRange(startCal.toInstant().toEpochMilli(), endCal.toInstant().toEpochMilli());
250     }
251 }