2 * Copyright (c) 2010-2024 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.awattar.internal.handler;
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;
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;
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.QuantityType;
48 import org.openhab.core.library.types.StringType;
49 import org.openhab.core.library.unit.Units;
50 import org.openhab.core.thing.Bridge;
51 import org.openhab.core.thing.Channel;
52 import org.openhab.core.thing.ChannelUID;
53 import org.openhab.core.thing.Thing;
54 import org.openhab.core.thing.ThingStatus;
55 import org.openhab.core.thing.ThingStatusDetail;
56 import org.openhab.core.thing.binding.BaseThingHandler;
57 import org.openhab.core.thing.type.ChannelKind;
58 import org.openhab.core.types.Command;
59 import org.openhab.core.types.RefreshType;
60 import org.openhab.core.types.State;
61 import org.openhab.core.types.UnDefType;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
66 * The {@link AwattarBestPriceHandler} is responsible for computing the best prices for a given configuration.
68 * @author Wolfgang Klimt - Initial contribution
71 public class AwattarBestPriceHandler extends BaseThingHandler {
72 private static final int THING_REFRESH_INTERVAL = 60;
74 private final Logger logger = LoggerFactory.getLogger(AwattarBestPriceHandler.class);
76 private @Nullable ScheduledFuture<?> thingRefresher;
78 private final TimeZoneProvider timeZoneProvider;
80 public AwattarBestPriceHandler(Thing thing, TimeZoneProvider timeZoneProvider) {
82 this.timeZoneProvider = timeZoneProvider;
86 public void initialize() {
87 AwattarBestPriceConfiguration config = getConfigAs(AwattarBestPriceConfiguration.class);
89 if (config.length >= config.rangeDuration) {
90 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/error.length.value");
95 ScheduledFuture<?> localRefresher = thingRefresher;
96 if (localRefresher == null || localRefresher.isCancelled()) {
98 * The scheduler is required to run exactly at minute borders, hence we can't use scheduleWithFixedDelay
101 thingRefresher = scheduler.scheduleAtFixedRate(this::refreshChannels,
102 getMillisToNextMinute(1, timeZoneProvider), THING_REFRESH_INTERVAL * 1000,
103 TimeUnit.MILLISECONDS);
106 updateStatus(ThingStatus.UNKNOWN);
110 public void dispose() {
111 ScheduledFuture<?> localRefresher = thingRefresher;
112 if (localRefresher != null) {
113 localRefresher.cancel(true);
114 thingRefresher = null;
118 public void refreshChannels() {
119 updateStatus(ThingStatus.ONLINE);
120 for (Channel channel : getThing().getChannels()) {
121 ChannelUID channelUID = channel.getUID();
122 if (ChannelKind.STATE.equals(channel.getKind()) && isLinked(channelUID)) {
123 refreshChannel(channel.getUID());
128 public void refreshChannel(ChannelUID channelUID) {
129 State state = UnDefType.UNDEF;
130 Bridge bridge = getBridge();
131 if (bridge == null) {
132 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "@text/error.bridge.missing");
133 updateState(channelUID, state);
136 AwattarBridgeHandler bridgeHandler = (AwattarBridgeHandler) bridge.getHandler();
137 if (bridgeHandler == null || bridgeHandler.getPrices() == null) {
138 logger.debug("No prices available, so can't refresh channel.");
139 // no prices available, can't continue
140 updateState(channelUID, state);
143 AwattarBestPriceConfiguration config = getConfigAs(AwattarBestPriceConfiguration.class);
144 TimeRange timerange = getRange(config.rangeStart, config.rangeDuration, bridgeHandler.getTimeZone());
145 if (!(bridgeHandler.containsPriceFor(timerange.start()) && bridgeHandler.containsPriceFor(timerange.end()))) {
146 updateState(channelUID, state);
150 AwattarBestPriceResult result;
151 List<AwattarPrice> range = getPriceRange(bridgeHandler, timerange);
153 if (config.consecutive) {
154 range.sort(Comparator.comparing(AwattarPrice::timerange));
155 AwattarConsecutiveBestPriceResult res = new AwattarConsecutiveBestPriceResult(
156 range.subList(0, config.length), bridgeHandler.getTimeZone());
158 for (int i = 1; i <= range.size() - config.length; i++) {
159 AwattarConsecutiveBestPriceResult res2 = new AwattarConsecutiveBestPriceResult(
160 range.subList(i, i + config.length), bridgeHandler.getTimeZone());
161 if (res2.getPriceSum() < res.getPriceSum()) {
167 range.sort(Comparator.naturalOrder());
169 // sort in descending order when inverted
170 if (config.inverted) {
171 Collections.reverse(range);
174 AwattarNonConsecutiveBestPriceResult res = new AwattarNonConsecutiveBestPriceResult(
175 bridgeHandler.getTimeZone());
177 // take up to config.length prices
178 for (int i = 0; i < Math.min(config.length, range.size()); i++) {
179 res.addMember(range.get(i));
184 String channelId = channelUID.getIdWithoutGroup();
188 state = OnOffType.from(result.isActive());
191 state = getDateTimeType(result.getStart(), timeZoneProvider);
194 state = getDateTimeType(result.getEnd(), timeZoneProvider);
196 case CHANNEL_COUNTDOWN:
197 diff = result.getStart() - Instant.now().toEpochMilli();
199 state = getDuration(diff);
201 state = QuantityType.valueOf(0, Units.MINUTE);
204 case CHANNEL_REMAINING:
205 if (result.isActive()) {
206 diff = result.getEnd() - Instant.now().toEpochMilli();
207 state = getDuration(diff);
209 state = QuantityType.valueOf(0, Units.MINUTE);
213 state = new StringType(result.getHours());
216 logger.warn("Unknown channel id {} for Thing type {}", channelUID, getThing().getThingTypeUID());
218 updateState(channelUID, state);
222 public void handleCommand(ChannelUID channelUID, Command command) {
223 if (command instanceof RefreshType) {
224 refreshChannel(channelUID);
226 logger.debug("Binding {} only supports refresh command", BINDING_ID);
230 private List<AwattarPrice> getPriceRange(AwattarBridgeHandler bridgeHandler, TimeRange range) {
231 List<AwattarPrice> result = new ArrayList<>();
232 SortedSet<AwattarPrice> prices = bridgeHandler.getPrices();
233 if (prices == null) {
234 logger.debug("No prices available, can't compute ranges");
237 result.addAll(prices.stream().filter(x -> range.contains(x.timerange())).toList());
241 protected TimeRange getRange(int start, int duration, ZoneId zoneId) {
242 ZonedDateTime startCal = getCalendarForHour(start, zoneId);
243 ZonedDateTime endCal = startCal.plusHours(duration);
244 ZonedDateTime now = ZonedDateTime.now(zoneId);
245 if (now.getHour() < start) {
246 // we are before the range, so we might be still within the last range
247 startCal = startCal.minusDays(1);
248 endCal = endCal.minusDays(1);
250 if (endCal.toInstant().toEpochMilli() < Instant.now().toEpochMilli()) {
251 // span is in the past, add one day
252 startCal = startCal.plusDays(1);
253 endCal = endCal.plusDays(1);
255 return new TimeRange(startCal.toInstant().toEpochMilli(), endCal.toInstant().toEpochMilli());