]> git.basschouten.com Git - openhab-addons.git/blob
063148bec6d5d0d240467de1b32f1482694d2ff0
[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.eclipse.jetty.http.HttpMethod.GET;
16 import static org.eclipse.jetty.http.HttpStatus.OK_200;
17 import static org.openhab.binding.awattar.internal.AwattarBindingConstants.BINDING_ID;
18
19 import java.time.Instant;
20 import java.time.LocalDate;
21 import java.time.ZoneId;
22 import java.time.ZonedDateTime;
23 import java.util.Comparator;
24 import java.util.SortedSet;
25 import java.util.TreeSet;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.eclipse.jetty.client.HttpClient;
34 import org.eclipse.jetty.client.api.ContentResponse;
35 import org.openhab.binding.awattar.internal.AwattarBridgeConfiguration;
36 import org.openhab.binding.awattar.internal.AwattarPrice;
37 import org.openhab.binding.awattar.internal.dto.AwattarApiData;
38 import org.openhab.binding.awattar.internal.dto.Datum;
39 import org.openhab.core.i18n.TimeZoneProvider;
40 import org.openhab.core.thing.Bridge;
41 import org.openhab.core.thing.ChannelUID;
42 import org.openhab.core.thing.ThingStatus;
43 import org.openhab.core.thing.ThingStatusDetail;
44 import org.openhab.core.thing.binding.BaseBridgeHandler;
45 import org.openhab.core.types.Command;
46 import org.openhab.core.types.RefreshType;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 import com.google.gson.Gson;
51 import com.google.gson.JsonSyntaxException;
52
53 /**
54  * The {@link AwattarBridgeHandler} is responsible for retrieving data from the aWATTar API.
55  *
56  * The API provides hourly prices for the current day and, starting from 14:00, hourly prices for the next day.
57  * Check the documentation at <a href="https://www.awattar.de/services/api" />
58  *
59  *
60  *
61  * @author Wolfgang Klimt - Initial contribution
62  */
63 @NonNullByDefault
64 public class AwattarBridgeHandler extends BaseBridgeHandler {
65     private static final int DATA_REFRESH_INTERVAL = 60;
66
67     private final Logger logger = LoggerFactory.getLogger(AwattarBridgeHandler.class);
68     private final HttpClient httpClient;
69     private @Nullable ScheduledFuture<?> dataRefresher;
70     private Instant lastRefresh = Instant.EPOCH;
71
72     private static final String URLDE = "https://api.awattar.de/v1/marketdata";
73     private static final String URLAT = "https://api.awattar.at/v1/marketdata";
74     private String url;
75
76     // This cache stores price data for up to two days
77     private @Nullable SortedSet<AwattarPrice> prices;
78     private double vatFactor = 0;
79     private double basePrice = 0;
80     private ZoneId zone;
81     private final TimeZoneProvider timeZoneProvider;
82
83     public AwattarBridgeHandler(Bridge thing, HttpClient httpClient, TimeZoneProvider timeZoneProvider) {
84         super(thing);
85         this.httpClient = httpClient;
86         url = URLDE;
87         this.timeZoneProvider = timeZoneProvider;
88         zone = timeZoneProvider.getTimeZone();
89     }
90
91     @Override
92     public void initialize() {
93         updateStatus(ThingStatus.UNKNOWN);
94         AwattarBridgeConfiguration config = getConfigAs(AwattarBridgeConfiguration.class);
95         vatFactor = 1 + (config.vatPercent / 100);
96         basePrice = config.basePrice;
97         zone = timeZoneProvider.getTimeZone();
98         switch (config.country) {
99             case "DE":
100                 url = URLDE;
101                 break;
102             case "AT":
103                 url = URLAT;
104                 break;
105             default:
106                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
107                         "@text/error.unsupported.country");
108                 return;
109         }
110
111         dataRefresher = scheduler.scheduleWithFixedDelay(this::refreshIfNeeded, 0, DATA_REFRESH_INTERVAL * 1000L,
112                 TimeUnit.MILLISECONDS);
113     }
114
115     @Override
116     public void dispose() {
117         ScheduledFuture<?> localRefresher = dataRefresher;
118         if (localRefresher != null) {
119             localRefresher.cancel(true);
120         }
121         dataRefresher = null;
122         prices = null;
123     }
124
125     void refreshIfNeeded() {
126         if (needRefresh()) {
127             refresh();
128         }
129     }
130
131     private void refresh() {
132         try {
133             // we start one day in the past to cover ranges that already started yesterday
134             ZonedDateTime zdt = LocalDate.now(zone).atStartOfDay(zone).minusDays(1);
135             long start = zdt.toInstant().toEpochMilli();
136             // Starting from midnight yesterday we add three days so that the range covers the whole next day.
137             zdt = zdt.plusDays(3);
138             long end = zdt.toInstant().toEpochMilli();
139
140             StringBuilder request = new StringBuilder(url);
141             request.append("?start=").append(start).append("&end=").append(end);
142
143             logger.trace("aWATTar API request: = '{}'", request);
144             ContentResponse contentResponse = httpClient.newRequest(request.toString()).method(GET)
145                     .timeout(10, TimeUnit.SECONDS).send();
146             int httpStatus = contentResponse.getStatus();
147             String content = contentResponse.getContentAsString();
148             logger.trace("aWATTar API response: status = {}, content = '{}'", httpStatus, content);
149
150             if (httpStatus == OK_200) {
151                 Gson gson = new Gson();
152                 SortedSet<AwattarPrice> result = new TreeSet<>(Comparator.comparing(AwattarPrice::timerange));
153                 AwattarApiData apiData = gson.fromJson(content, AwattarApiData.class);
154                 if (apiData != null) {
155                     for (Datum d : apiData.data) {
156                         double netPrice = d.marketprice / 10.0;
157                         TimeRange timerange = new TimeRange(d.startTimestamp, d.endTimestamp);
158                         result.add(new AwattarPrice(netPrice, netPrice * vatFactor, netPrice + basePrice,
159                                 (netPrice + basePrice) * vatFactor, timerange));
160                     }
161                     prices = result;
162                     updateStatus(ThingStatus.ONLINE);
163                 } else {
164                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
165                             "@text/error.invalid.data");
166                 }
167             } else {
168                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
169                         "@text/warn.awattar.statuscode");
170             }
171         } catch (JsonSyntaxException e) {
172             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "@text/error.json");
173         } catch (InterruptedException e) {
174             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "@text/error.interrupted");
175         } catch (ExecutionException e) {
176             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "@text/error.execution");
177         } catch (TimeoutException e) {
178             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "@text/error.timeout");
179         }
180     }
181
182     /**
183      * Check if the data needs to be refreshed.
184      *
185      * The data is refreshed if:
186      * - the thing is offline
187      * - the local cache is empty
188      * - the current time is after 15:00 and the last refresh was more than an hour ago
189      * - the current time is after 18:00 and the last refresh was more than an hour ago
190      * - the current time is after 21:00 and the last refresh was more than an hour ago
191      *
192      * @return true if the data needs to be refreshed
193      */
194     private boolean needRefresh() {
195         // if the thing is offline, we need to refresh
196         if (getThing().getStatus() != ThingStatus.ONLINE) {
197             return true;
198         }
199
200         // if the local cache is empty, we need to refresh
201         if (prices == null) {
202             return true;
203         }
204
205         // Note: all this magic is made to avoid refreshing the data too often, since the API is rate-limited
206         // to 100 requests per day.
207
208         // do not refresh before 15:00, since the prices for the next day are available only after 14:00
209         ZonedDateTime now = ZonedDateTime.now(zone);
210         if (now.getHour() < 15) {
211             return false;
212         }
213
214         // refresh then every 3 hours, if the last refresh was more than an hour ago
215         if (now.getHour() % 3 == 0 && lastRefresh.getEpochSecond() < now.minusHours(1).toEpochSecond()) {
216
217             // update the last refresh time
218             lastRefresh = Instant.now();
219
220             // return true to indicate an update is needed
221             return true;
222         }
223
224         return false;
225     }
226
227     public ZoneId getTimeZone() {
228         return zone;
229     }
230
231     @Nullable
232     public synchronized SortedSet<AwattarPrice> getPrices() {
233         if (prices == null) {
234             refresh();
235         }
236         return prices;
237     }
238
239     public @Nullable AwattarPrice getPriceFor(long timestamp) {
240         SortedSet<AwattarPrice> localPrices = getPrices();
241         if (localPrices == null || !containsPriceFor(timestamp)) {
242             return null;
243         }
244         return localPrices.stream().filter(e -> e.timerange().contains(timestamp)).findAny().orElse(null);
245     }
246
247     public boolean containsPriceFor(long timestamp) {
248         SortedSet<AwattarPrice> localPrices = getPrices();
249         return localPrices != null && localPrices.first().timerange().start() <= timestamp
250                 && localPrices.last().timerange().end() > timestamp;
251     }
252
253     @Override
254     public void handleCommand(ChannelUID channelUID, Command command) {
255         if (command instanceof RefreshType) {
256             refresh();
257         } else {
258             logger.debug("Binding {} only supports refresh command", BINDING_ID);
259         }
260     }
261 }