]> git.basschouten.com Git - openhab-addons.git/blob
ee80274a59e64f3573d56f42ac5f7e7afbc56f0e
[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             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         try {
123             String responseContent = sendRequest(request, properties);
124             ElspotpriceRecords records = gson.fromJson(responseContent, ElspotpriceRecords.class);
125             if (records == null) {
126                 throw new DataServiceException("Error parsing response");
127             }
128
129             if (records.total() == 0 || Objects.isNull(records.records()) || records.records().length == 0) {
130                 throw new DataServiceException("No records");
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 dateQueryParameter = tariffFilter.getDateQueryParameter();
217         if (!dateQueryParameter.isEmpty()) {
218             request = request.param("start", dateQueryParameter.toString());
219         }
220
221         try {
222             String responseContent = sendRequest(request, properties);
223             DatahubPricelistRecords records = gson.fromJson(responseContent, DatahubPricelistRecords.class);
224             if (records == null) {
225                 throw new DataServiceException("Error parsing response");
226             }
227
228             if (records.limit() > 0 && records.limit() < records.total()) {
229                 logger.warn("{} price list records available, but only {} returned.", records.total(), records.limit());
230             }
231
232             if (Objects.isNull(records.records())) {
233                 return List.of();
234             }
235
236             return Arrays.stream(records.records()).filter(Objects::nonNull).toList();
237         } catch (JsonSyntaxException e) {
238             throw new DataServiceException("Error parsing response", e);
239         } catch (TimeoutException | ExecutionException e) {
240             throw new DataServiceException(e);
241         }
242     }
243
244     private String mapToFilter(Map<String, Collection<String>> map) {
245         return "{" + map.entrySet().stream().map(
246                 e -> "\"" + e.getKey() + "\":[\"" + e.getValue().stream().collect(Collectors.joining("\",\"")) + "\"]")
247                 .collect(Collectors.joining(",")) + "}";
248     }
249
250     /**
251      * Retrieve CO2 emissions for requested area.
252      *
253      * @param dataset Dataset to obtain
254      * @param priceArea Usually DK1 or DK2
255      * @param start Specifies the start point of the period for the data request
256      * @param properties Map of properties which will be updated with metadata from headers
257      * @return Records with 5 minute periods and emissions in g/kWh.
258      * @throws InterruptedException
259      * @throws DataServiceException
260      */
261     public CO2EmissionRecord[] getCo2Emissions(Dataset dataset, String priceArea, DateQueryParameter start,
262             Map<String, String> properties) throws InterruptedException, DataServiceException {
263         if (dataset != Dataset.CO2Emission && dataset != Dataset.CO2EmissionPrognosis) {
264             throw new IllegalArgumentException("Invalid dataset " + dataset + " for getting CO2 emissions");
265         }
266         Request request = httpClient.newRequest(ENDPOINT + DATASET_PATH + dataset)
267                 .timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) //
268                 .param("start", start.toString()) //
269                 .param("filter", "{\"" + FILTER_KEY_PRICE_AREA + "\":\"" + priceArea + "\"}") //
270                 .param("columns", "Minutes5UTC,CO2Emission") //
271                 .param("sort", "Minutes5UTC DESC") //
272                 .agent(userAgent) //
273                 .method(HttpMethod.GET);
274
275         try {
276             String responseContent = sendRequest(request, properties);
277             CO2EmissionRecords records = gson.fromJson(responseContent, CO2EmissionRecords.class);
278             if (records == null) {
279                 throw new DataServiceException("Error parsing response");
280             }
281
282             if (records.total() == 0 || Objects.isNull(records.records()) || records.records().length == 0) {
283                 throw new DataServiceException("No records");
284             }
285
286             return Arrays.stream(records.records()).filter(Objects::nonNull).toArray(CO2EmissionRecord[]::new);
287         } catch (JsonSyntaxException e) {
288             throw new DataServiceException("Error parsing response", e);
289         } catch (TimeoutException | ExecutionException e) {
290             throw new DataServiceException(e);
291         }
292     }
293 }