]> git.basschouten.com Git - openhab-addons.git/blob
0201bba12f39ccd10c0bf3af5761672a36029092
[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.energidataservice.internal;
14
15 import static org.openhab.binding.energidataservice.internal.EnergiDataServiceBindingConstants.*;
16
17 import java.time.Instant;
18 import java.time.LocalDateTime;
19 import java.time.format.DateTimeFormatter;
20 import java.util.Arrays;
21 import java.util.Collection;
22 import java.util.Currency;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Objects;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import java.util.stream.Collectors;
31
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jetty.client.HttpClient;
34 import org.eclipse.jetty.client.api.ContentResponse;
35 import org.eclipse.jetty.client.api.Request;
36 import org.eclipse.jetty.http.HttpFields;
37 import org.eclipse.jetty.http.HttpMethod;
38 import org.eclipse.jetty.http.HttpStatus;
39 import org.openhab.binding.energidataservice.internal.api.ChargeType;
40 import org.openhab.binding.energidataservice.internal.api.DatahubTariffFilter;
41 import org.openhab.binding.energidataservice.internal.api.Dataset;
42 import org.openhab.binding.energidataservice.internal.api.DateQueryParameter;
43 import org.openhab.binding.energidataservice.internal.api.GlobalLocationNumber;
44 import org.openhab.binding.energidataservice.internal.api.dto.CO2EmissionRecord;
45 import org.openhab.binding.energidataservice.internal.api.dto.CO2EmissionRecords;
46 import org.openhab.binding.energidataservice.internal.api.dto.DatahubPricelistRecord;
47 import org.openhab.binding.energidataservice.internal.api.dto.DatahubPricelistRecords;
48 import org.openhab.binding.energidataservice.internal.api.dto.ElspotpriceRecord;
49 import org.openhab.binding.energidataservice.internal.api.dto.ElspotpriceRecords;
50 import org.openhab.binding.energidataservice.internal.api.serialization.InstantDeserializer;
51 import org.openhab.binding.energidataservice.internal.api.serialization.LocalDateTimeDeserializer;
52 import org.openhab.binding.energidataservice.internal.exception.DataServiceException;
53 import org.openhab.core.i18n.TimeZoneProvider;
54 import org.osgi.framework.FrameworkUtil;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 import com.google.gson.Gson;
59 import com.google.gson.GsonBuilder;
60 import com.google.gson.JsonSyntaxException;
61
62 /**
63  * The {@link ApiController} is responsible for interacting with Energi Data Service.
64  *
65  * @author Jacob Laursen - Initial contribution
66  */
67 @NonNullByDefault
68 public class ApiController {
69     private static final String ENDPOINT = "https://api.energidataservice.dk/";
70     private static final String DATASET_PATH = "dataset/";
71
72     private static final String FILTER_KEY_PRICE_AREA = "PriceArea";
73     private static final String FILTER_KEY_CHARGE_TYPE = "ChargeType";
74     private static final String FILTER_KEY_CHARGE_TYPE_CODE = "ChargeTypeCode";
75     private static final String FILTER_KEY_GLN_NUMBER = "GLN_Number";
76     private static final String FILTER_KEY_NOTE = "Note";
77
78     private static final String HEADER_REMAINING_CALLS = "RemainingCalls";
79     private static final String HEADER_TOTAL_CALLS = "TotalCalls";
80     private static final int REQUEST_TIMEOUT_SECONDS = 30;
81
82     private final Logger logger = LoggerFactory.getLogger(ApiController.class);
83     private final Gson gson = new GsonBuilder() //
84             .registerTypeAdapter(Instant.class, new InstantDeserializer()) //
85             .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer()) //
86             .create();
87     private final HttpClient httpClient;
88     private final TimeZoneProvider timeZoneProvider;
89     private final String userAgent;
90
91     public ApiController(HttpClient httpClient, TimeZoneProvider timeZoneProvider) {
92         this.httpClient = httpClient;
93         this.timeZoneProvider = timeZoneProvider;
94         userAgent = "openHAB/" + FrameworkUtil.getBundle(this.getClass()).getVersion().toString();
95     }
96
97     /**
98      * Retrieve spot prices for requested area and in requested {@link Currency}.
99      *
100      * @param priceArea Usually DK1 or DK2
101      * @param currency DKK or EUR
102      * @param start Specifies the start point of the period for the data request
103      * @param properties Map of properties which will be updated with metadata from headers
104      * @return Records with pairs of hour start and price in requested currency.
105      * @throws InterruptedException
106      * @throws DataServiceException
107      */
108     public ElspotpriceRecord[] getSpotPrices(String priceArea, Currency currency, DateQueryParameter start,
109             DateQueryParameter end, Map<String, String> properties) throws InterruptedException, DataServiceException {
110         if (!SUPPORTED_CURRENCIES.contains(currency)) {
111             throw new IllegalArgumentException("Invalid currency " + currency.getCurrencyCode());
112         }
113
114         Request request = httpClient.newRequest(ENDPOINT + DATASET_PATH + Dataset.SpotPrices)
115                 .timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) //
116                 .param("start", start.toString()) //
117                 .param("filter", "{\"" + FILTER_KEY_PRICE_AREA + "\":\"" + priceArea + "\"}") //
118                 .param("columns", "HourUTC,SpotPrice" + currency) //
119                 .agent(userAgent) //
120                 .method(HttpMethod.GET);
121
122         if (!end.isEmpty()) {
123             request = request.param("end", end.toString());
124         }
125
126         try {
127             String responseContent = sendRequest(request, properties);
128             ElspotpriceRecords records = gson.fromJson(responseContent, ElspotpriceRecords.class);
129             if (records == null || Objects.isNull(records.records())) {
130                 throw new DataServiceException("Error parsing response");
131             }
132
133             return Arrays.stream(records.records()).filter(Objects::nonNull).toArray(ElspotpriceRecord[]::new);
134         } catch (JsonSyntaxException e) {
135             throw new DataServiceException("Error parsing response", e);
136         } catch (TimeoutException | ExecutionException e) {
137             throw new DataServiceException(e);
138         }
139     }
140
141     private String sendRequest(Request request, Map<String, String> properties)
142             throws TimeoutException, ExecutionException, InterruptedException, DataServiceException {
143         logger.trace("GET request for {}", request.getURI());
144
145         ContentResponse response = request.send();
146
147         updatePropertiesFromResponse(response, properties);
148
149         int status = response.getStatus();
150         if (!HttpStatus.isSuccess(status)) {
151             throw new DataServiceException("The request failed with HTTP error " + status, status);
152         }
153         String responseContent = response.getContentAsString();
154         if (responseContent.isEmpty()) {
155             throw new DataServiceException("Empty response");
156         }
157         logger.trace("Response content: '{}'", responseContent);
158
159         return responseContent;
160     }
161
162     private void updatePropertiesFromResponse(ContentResponse response, Map<String, String> properties) {
163         HttpFields headers = response.getHeaders();
164         String remainingCalls = headers.get(HEADER_REMAINING_CALLS);
165         if (remainingCalls != null) {
166             properties.put(PROPERTY_REMAINING_CALLS, remainingCalls);
167         }
168         String totalCalls = headers.get(HEADER_TOTAL_CALLS);
169         if (totalCalls != null) {
170             properties.put(PROPERTY_TOTAL_CALLS, totalCalls);
171         }
172         DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PROPERTY_DATETIME_FORMAT);
173         properties.put(PROPERTY_LAST_CALL, LocalDateTime.now(timeZoneProvider.getTimeZone()).format(formatter));
174     }
175
176     /**
177      * Retrieve datahub pricelists for requested GLN and charge type/charge type code.
178      *
179      * @param globalLocationNumber Global Location Number of the Charge Owner
180      * @param chargeType Charge type (Subscription, Fee or Tariff).
181      * @param tariffFilter Tariff filter (charge type codes and notes).
182      * @param properties Map of properties which will be updated with metadata from headers
183      * @return Price list for requested GLN and note.
184      * @throws InterruptedException
185      * @throws DataServiceException
186      */
187     public Collection<DatahubPricelistRecord> getDatahubPriceLists(GlobalLocationNumber globalLocationNumber,
188             ChargeType chargeType, DatahubTariffFilter tariffFilter, Map<String, String> properties)
189             throws InterruptedException, DataServiceException {
190         String columns = "ValidFrom,ValidTo,ChargeTypeCode";
191         for (int i = 1; i < 25; i++) {
192             columns += ",Price" + i;
193         }
194
195         Map<String, Collection<String>> filterMap = new HashMap<>(Map.of( //
196                 FILTER_KEY_GLN_NUMBER, List.of(globalLocationNumber.toString()), //
197                 FILTER_KEY_CHARGE_TYPE, List.of(chargeType.toString())));
198
199         Collection<String> chargeTypeCodes = tariffFilter.getChargeTypeCodesAsStrings();
200         if (!chargeTypeCodes.isEmpty()) {
201             filterMap.put(FILTER_KEY_CHARGE_TYPE_CODE, chargeTypeCodes);
202         }
203
204         Collection<String> notes = tariffFilter.getNotes();
205         if (!notes.isEmpty()) {
206             filterMap.put(FILTER_KEY_NOTE, notes);
207         }
208
209         Request request = httpClient.newRequest(ENDPOINT + DATASET_PATH + Dataset.DatahubPricelist)
210                 .timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) //
211                 .param("filter", mapToFilter(filterMap)) //
212                 .param("columns", columns) //
213                 .agent(userAgent) //
214                 .method(HttpMethod.GET);
215
216         DateQueryParameter start = tariffFilter.getStart();
217         if (!start.isEmpty()) {
218             request = request.param("start", start.toString());
219         }
220
221         DateQueryParameter end = tariffFilter.getEnd();
222         if (!end.isEmpty()) {
223             request = request.param("end", end.toString());
224         }
225
226         try {
227             String responseContent = sendRequest(request, properties);
228             DatahubPricelistRecords records = gson.fromJson(responseContent, DatahubPricelistRecords.class);
229             if (records == null) {
230                 throw new DataServiceException("Error parsing response");
231             }
232
233             if (records.limit() > 0 && records.limit() < records.total()) {
234                 logger.warn("{} price list records available, but only {} returned.", records.total(), records.limit());
235             }
236
237             if (Objects.isNull(records.records())) {
238                 return List.of();
239             }
240
241             return Arrays.stream(records.records()).filter(Objects::nonNull).toList();
242         } catch (JsonSyntaxException e) {
243             throw new DataServiceException("Error parsing response", e);
244         } catch (TimeoutException | ExecutionException e) {
245             throw new DataServiceException(e);
246         }
247     }
248
249     private String mapToFilter(Map<String, Collection<String>> map) {
250         return "{" + map.entrySet().stream().map(
251                 e -> "\"" + e.getKey() + "\":[\"" + e.getValue().stream().collect(Collectors.joining("\",\"")) + "\"]")
252                 .collect(Collectors.joining(",")) + "}";
253     }
254
255     /**
256      * Retrieve CO2 emissions for requested area.
257      *
258      * @param dataset Dataset to obtain
259      * @param priceArea Usually DK1 or DK2
260      * @param start Specifies the start point of the period for the data request
261      * @param properties Map of properties which will be updated with metadata from headers
262      * @return Records with 5 minute periods and emissions in g/kWh.
263      * @throws InterruptedException
264      * @throws DataServiceException
265      */
266     public CO2EmissionRecord[] getCo2Emissions(Dataset dataset, String priceArea, DateQueryParameter start,
267             Map<String, String> properties) throws InterruptedException, DataServiceException {
268         if (dataset != Dataset.CO2Emission && dataset != Dataset.CO2EmissionPrognosis) {
269             throw new IllegalArgumentException("Invalid dataset " + dataset + " for getting CO2 emissions");
270         }
271         if (!"DK1".equals(priceArea) && !"DK2".equals(priceArea)) {
272             throw new IllegalArgumentException("Invalid price area " + priceArea + " for getting CO2 emissions");
273         }
274         Request request = httpClient.newRequest(ENDPOINT + DATASET_PATH + dataset)
275                 .timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) //
276                 .param("start", start.toString()) //
277                 .param("filter", "{\"" + FILTER_KEY_PRICE_AREA + "\":\"" + priceArea + "\"}") //
278                 .param("columns", "Minutes5UTC,CO2Emission") //
279                 .param("sort", "Minutes5UTC DESC") //
280                 .agent(userAgent) //
281                 .method(HttpMethod.GET);
282
283         try {
284             String responseContent = sendRequest(request, properties);
285             CO2EmissionRecords records = gson.fromJson(responseContent, CO2EmissionRecords.class);
286             if (records == null) {
287                 throw new DataServiceException("Error parsing response");
288             }
289
290             if (records.total() == 0 || Objects.isNull(records.records()) || records.records().length == 0) {
291                 throw new DataServiceException("No records");
292             }
293
294             return Arrays.stream(records.records()).filter(Objects::nonNull).toArray(CO2EmissionRecord[]::new);
295         } catch (JsonSyntaxException e) {
296             throw new DataServiceException("Error parsing response", e);
297         } catch (TimeoutException | ExecutionException e) {
298             throw new DataServiceException(e);
299         }
300     }
301 }