]> git.basschouten.com Git - openhab-addons.git/blob
1aaaf45be5d608f2e4cfce26645c184e4c459129
[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 || Objects.isNull(records.records())) {
126                 throw new DataServiceException("Error parsing response");
127             }
128
129             return Arrays.stream(records.records()).filter(Objects::nonNull).toArray(ElspotpriceRecord[]::new);
130         } catch (JsonSyntaxException e) {
131             throw new DataServiceException("Error parsing response", e);
132         } catch (TimeoutException | ExecutionException e) {
133             throw new DataServiceException(e);
134         }
135     }
136
137     private String sendRequest(Request request, Map<String, String> properties)
138             throws TimeoutException, ExecutionException, InterruptedException, DataServiceException {
139         logger.trace("GET request for {}", request.getURI());
140
141         ContentResponse response = request.send();
142
143         updatePropertiesFromResponse(response, properties);
144
145         int status = response.getStatus();
146         if (!HttpStatus.isSuccess(status)) {
147             throw new DataServiceException("The request failed with HTTP error " + status, status);
148         }
149         String responseContent = response.getContentAsString();
150         if (responseContent.isEmpty()) {
151             throw new DataServiceException("Empty response");
152         }
153         logger.trace("Response content: '{}'", responseContent);
154
155         return responseContent;
156     }
157
158     private void updatePropertiesFromResponse(ContentResponse response, Map<String, String> properties) {
159         HttpFields headers = response.getHeaders();
160         String remainingCalls = headers.get(HEADER_REMAINING_CALLS);
161         if (remainingCalls != null) {
162             properties.put(PROPERTY_REMAINING_CALLS, remainingCalls);
163         }
164         String totalCalls = headers.get(HEADER_TOTAL_CALLS);
165         if (totalCalls != null) {
166             properties.put(PROPERTY_TOTAL_CALLS, totalCalls);
167         }
168         DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PROPERTY_DATETIME_FORMAT);
169         properties.put(PROPERTY_LAST_CALL, LocalDateTime.now(timeZoneProvider.getTimeZone()).format(formatter));
170     }
171
172     /**
173      * Retrieve datahub pricelists for requested GLN and charge type/charge type code.
174      *
175      * @param globalLocationNumber Global Location Number of the Charge Owner
176      * @param chargeType Charge type (Subscription, Fee or Tariff).
177      * @param tariffFilter Tariff filter (charge type codes and notes).
178      * @param properties Map of properties which will be updated with metadata from headers
179      * @return Price list for requested GLN and note.
180      * @throws InterruptedException
181      * @throws DataServiceException
182      */
183     public Collection<DatahubPricelistRecord> getDatahubPriceLists(GlobalLocationNumber globalLocationNumber,
184             ChargeType chargeType, DatahubTariffFilter tariffFilter, Map<String, String> properties)
185             throws InterruptedException, DataServiceException {
186         String columns = "ValidFrom,ValidTo,ChargeTypeCode";
187         for (int i = 1; i < 25; i++) {
188             columns += ",Price" + i;
189         }
190
191         Map<String, Collection<String>> filterMap = new HashMap<>(Map.of( //
192                 FILTER_KEY_GLN_NUMBER, List.of(globalLocationNumber.toString()), //
193                 FILTER_KEY_CHARGE_TYPE, List.of(chargeType.toString())));
194
195         Collection<String> chargeTypeCodes = tariffFilter.getChargeTypeCodesAsStrings();
196         if (!chargeTypeCodes.isEmpty()) {
197             filterMap.put(FILTER_KEY_CHARGE_TYPE_CODE, chargeTypeCodes);
198         }
199
200         Collection<String> notes = tariffFilter.getNotes();
201         if (!notes.isEmpty()) {
202             filterMap.put(FILTER_KEY_NOTE, notes);
203         }
204
205         Request request = httpClient.newRequest(ENDPOINT + DATASET_PATH + Dataset.DatahubPricelist)
206                 .timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) //
207                 .param("filter", mapToFilter(filterMap)) //
208                 .param("columns", columns) //
209                 .agent(userAgent) //
210                 .method(HttpMethod.GET);
211
212         DateQueryParameter dateQueryParameter = tariffFilter.getDateQueryParameter();
213         if (!dateQueryParameter.isEmpty()) {
214             request = request.param("start", dateQueryParameter.toString());
215         }
216
217         try {
218             String responseContent = sendRequest(request, properties);
219             DatahubPricelistRecords records = gson.fromJson(responseContent, DatahubPricelistRecords.class);
220             if (records == null) {
221                 throw new DataServiceException("Error parsing response");
222             }
223
224             if (records.limit() > 0 && records.limit() < records.total()) {
225                 logger.warn("{} price list records available, but only {} returned.", records.total(), records.limit());
226             }
227
228             if (Objects.isNull(records.records())) {
229                 return List.of();
230             }
231
232             return Arrays.stream(records.records()).filter(Objects::nonNull).toList();
233         } catch (JsonSyntaxException e) {
234             throw new DataServiceException("Error parsing response", e);
235         } catch (TimeoutException | ExecutionException e) {
236             throw new DataServiceException(e);
237         }
238     }
239
240     private String mapToFilter(Map<String, Collection<String>> map) {
241         return "{" + map.entrySet().stream().map(
242                 e -> "\"" + e.getKey() + "\":[\"" + e.getValue().stream().collect(Collectors.joining("\",\"")) + "\"]")
243                 .collect(Collectors.joining(",")) + "}";
244     }
245
246     /**
247      * Retrieve CO2 emissions for requested area.
248      *
249      * @param dataset Dataset to obtain
250      * @param priceArea Usually DK1 or DK2
251      * @param start Specifies the start point of the period for the data request
252      * @param properties Map of properties which will be updated with metadata from headers
253      * @return Records with 5 minute periods and emissions in g/kWh.
254      * @throws InterruptedException
255      * @throws DataServiceException
256      */
257     public CO2EmissionRecord[] getCo2Emissions(Dataset dataset, String priceArea, DateQueryParameter start,
258             Map<String, String> properties) throws InterruptedException, DataServiceException {
259         if (dataset != Dataset.CO2Emission && dataset != Dataset.CO2EmissionPrognosis) {
260             throw new IllegalArgumentException("Invalid dataset " + dataset + " for getting CO2 emissions");
261         }
262         if (!"DK1".equals(priceArea) && !"DK2".equals(priceArea)) {
263             throw new IllegalArgumentException("Invalid price area " + priceArea + " for getting CO2 emissions");
264         }
265         Request request = httpClient.newRequest(ENDPOINT + DATASET_PATH + dataset)
266                 .timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS) //
267                 .param("start", start.toString()) //
268                 .param("filter", "{\"" + FILTER_KEY_PRICE_AREA + "\":\"" + priceArea + "\"}") //
269                 .param("columns", "Minutes5UTC,CO2Emission") //
270                 .param("sort", "Minutes5UTC DESC") //
271                 .agent(userAgent) //
272                 .method(HttpMethod.GET);
273
274         try {
275             String responseContent = sendRequest(request, properties);
276             CO2EmissionRecords records = gson.fromJson(responseContent, CO2EmissionRecords.class);
277             if (records == null) {
278                 throw new DataServiceException("Error parsing response");
279             }
280
281             if (records.total() == 0 || Objects.isNull(records.records()) || records.records().length == 0) {
282                 throw new DataServiceException("No records");
283             }
284
285             return Arrays.stream(records.records()).filter(Objects::nonNull).toArray(CO2EmissionRecord[]::new);
286         } catch (JsonSyntaxException e) {
287             throw new DataServiceException("Error parsing response", e);
288         } catch (TimeoutException | ExecutionException e) {
289             throw new DataServiceException(e);
290         }
291     }
292 }