2 * Copyright (c) 2010-2023 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.energidataservice.internal.action;
15 import static org.hamcrest.CoreMatchers.*;
16 import static org.hamcrest.MatcherAssert.assertThat;
17 import static org.mockito.Mockito.when;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.math.BigDecimal;
22 import java.nio.charset.StandardCharsets;
23 import java.time.Clock;
24 import java.time.Duration;
25 import java.time.Instant;
26 import java.time.LocalDateTime;
27 import java.util.Arrays;
28 import java.util.List;
30 import java.util.Objects;
31 import java.util.stream.Collectors;
33 import javax.measure.quantity.Power;
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.junit.jupiter.api.BeforeEach;
37 import org.junit.jupiter.api.Test;
38 import org.junit.jupiter.api.extension.ExtendWith;
39 import org.mockito.Mock;
40 import org.mockito.junit.jupiter.MockitoExtension;
41 import org.mockito.junit.jupiter.MockitoSettings;
42 import org.mockito.quality.Strictness;
43 import org.openhab.binding.energidataservice.internal.DatahubTariff;
44 import org.openhab.binding.energidataservice.internal.EnergiDataServiceBindingConstants;
45 import org.openhab.binding.energidataservice.internal.PriceListParser;
46 import org.openhab.binding.energidataservice.internal.api.dto.DatahubPricelistRecords;
47 import org.openhab.binding.energidataservice.internal.api.serialization.InstantDeserializer;
48 import org.openhab.binding.energidataservice.internal.api.serialization.LocalDateTimeDeserializer;
49 import org.openhab.binding.energidataservice.internal.handler.EnergiDataServiceHandler;
50 import org.openhab.core.library.types.QuantityType;
51 import org.openhab.core.library.unit.Units;
52 import org.slf4j.LoggerFactory;
54 import com.google.gson.Gson;
55 import com.google.gson.GsonBuilder;
57 import ch.qos.logback.classic.Level;
58 import ch.qos.logback.classic.Logger;
61 * Tests for {@link EnergiDataServiceActions}.
63 * @author Jacob Laursen - Initial contribution
66 @ExtendWith(MockitoExtension.class)
67 @MockitoSettings(strictness = Strictness.LENIENT)
68 public class EnergiDataServiceActionsTest {
70 private @NonNullByDefault({}) @Mock EnergiDataServiceHandler handler;
71 private EnergiDataServiceActions actions = new EnergiDataServiceActions();
73 private Gson gson = new GsonBuilder().registerTypeAdapter(Instant.class, new InstantDeserializer())
74 .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer()).create();
76 private record SpotPrice(Instant hourStart, BigDecimal spotPrice) {
79 private <T> T getObjectFromJson(String filename, Class<T> clazz) throws IOException {
80 try (InputStream inputStream = EnergiDataServiceActionsTest.class.getResourceAsStream(filename)) {
81 if (inputStream == null) {
82 throw new IOException("Input stream is null");
84 byte[] bytes = inputStream.readAllBytes();
86 throw new IOException("Resulting byte-array empty");
88 String json = new String(bytes, StandardCharsets.UTF_8);
89 return Objects.requireNonNull(gson.fromJson(json, clazz));
95 final Logger logger = (Logger) LoggerFactory.getLogger(EnergiDataServiceActions.class);
96 logger.setLevel(Level.OFF);
98 actions = new EnergiDataServiceActions();
102 void getPricesSpotPrice() throws IOException {
103 mockCommonDatasets(actions);
105 Map<Instant, BigDecimal> actual = actions.getPrices("SpotPrice");
106 assertThat(actual.size(), is(35));
107 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("0.992840027"))));
108 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("1.267680054"))));
112 void getPricesNetTariff() throws IOException {
113 mockCommonDatasets(actions);
115 Map<Instant, BigDecimal> actual = actions.getPrices("NetTariff");
116 assertThat(actual.size(), is(60));
117 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("0.432225"))));
118 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("1.05619"))));
122 void getPricesSystemTariff() throws IOException {
123 mockCommonDatasets(actions);
125 Map<Instant, BigDecimal> actual = actions.getPrices("SystemTariff");
126 assertThat(actual.size(), is(60));
127 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("0.054"))));
128 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("0.054"))));
132 void getPricesElectricityTax() throws IOException {
133 mockCommonDatasets(actions);
135 Map<Instant, BigDecimal> actual = actions.getPrices("ElectricityTax");
136 assertThat(actual.size(), is(60));
137 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("0.008"))));
138 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("0.008"))));
142 void getPricesTransmissionNetTariff() throws IOException {
143 mockCommonDatasets(actions);
145 Map<Instant, BigDecimal> actual = actions.getPrices("TransmissionNetTariff");
146 assertThat(actual.size(), is(60));
147 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("0.058"))));
148 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("0.058"))));
152 void getPricesSpotPriceNetTariff() throws IOException {
153 mockCommonDatasets(actions);
155 Map<Instant, BigDecimal> actual = actions.getPrices("SpotPrice,NetTariff");
156 assertThat(actual.size(), is(35));
157 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("1.425065027"))));
158 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("2.323870054"))));
162 void getPricesSpotPriceNetTariffElectricityTax() throws IOException {
163 mockCommonDatasets(actions);
165 Map<Instant, BigDecimal> actual = actions.getPrices("SpotPrice,NetTariff,ElectricityTax");
166 assertThat(actual.size(), is(35));
167 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("1.433065027"))));
168 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("2.331870054"))));
172 void getPricesTotal() throws IOException {
173 mockCommonDatasets(actions);
175 Map<Instant, BigDecimal> actual = actions.getPrices();
176 assertThat(actual.size(), is(35));
177 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("1.545065027"))));
178 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("2.443870054"))));
182 void getPricesTotalAllElements() throws IOException {
183 mockCommonDatasets(actions);
185 Map<Instant, BigDecimal> actual = actions
186 .getPrices("spotprice,nettariff,systemtariff,electricitytax,transmissionnettariff");
187 assertThat(actual.size(), is(35));
188 assertThat(actual.get(Instant.parse("2023-02-04T12:00:00Z")), is(equalTo(new BigDecimal("1.545065027"))));
189 assertThat(actual.get(Instant.parse("2023-02-04T15:00:00Z")), is(equalTo(new BigDecimal("1.708765039"))));
190 assertThat(actual.get(Instant.parse("2023-02-04T16:00:00Z")), is(equalTo(new BigDecimal("2.443870054"))));
194 void getPricesInvalidPriceElement() throws IOException {
195 mockCommonDatasets(actions);
197 Map<Instant, BigDecimal> actual = actions.getPrices("spotprice,nettarif");
198 assertThat(actual.size(), is(0));
202 void getPricesMixedCurrencies() throws IOException {
203 mockCommonDatasets(actions);
204 when(handler.getCurrency()).thenReturn(EnergiDataServiceBindingConstants.CURRENCY_EUR);
206 Map<Instant, BigDecimal> actual = actions.getPrices("spotprice,nettariff");
207 assertThat(actual.size(), is(0));
211 * Calculate price in period 15:30-16:30 (UTC) with consumption 150 W and the following total prices:
212 * 15:00:00: 1.708765039
213 * 16:00:00: 2.443870054
215 * Result = (1.708765039 / 2) + (2.443870054 / 2) * 0.150
217 * @throws IOException
220 void calculatePriceSimple() throws IOException {
221 mockCommonDatasets(actions);
223 BigDecimal actual = actions.calculatePrice(Instant.parse("2023-02-04T15:30:00Z"),
224 Instant.parse("2023-02-04T16:30:00Z"), new QuantityType<>(150, Units.WATT));
225 assertThat(actual, is(equalTo(new BigDecimal("0.311447631975000000")))); // 0.3114476319750
229 * Calculate price in period 15:00-17:00 (UTC) with consumption 1000 W and the following total prices:
230 * 15:00:00: 1.708765039
231 * 16:00:00: 2.443870054
233 * Result = 1.708765039 + 2.443870054
235 * @throws IOException
238 void calculatePriceFullHours() throws IOException {
239 mockCommonDatasets(actions);
241 BigDecimal actual = actions.calculatePrice(Instant.parse("2023-02-04T15:00:00Z"),
242 Instant.parse("2023-02-04T17:00:00Z"), new QuantityType<>(1, Units.KILOVAR));
243 assertThat(actual, is(equalTo(new BigDecimal("4.152635093000000000")))); // 4.152635093
247 void calculatePriceOutOfRangeStart() throws IOException {
248 mockCommonDatasets(actions);
250 BigDecimal actual = actions.calculatePrice(Instant.parse("2023-02-03T23:59:00Z"),
251 Instant.parse("2023-02-04T12:30:00Z"), new QuantityType<>(1000, Units.WATT));
252 assertThat(actual, is(equalTo(BigDecimal.ZERO)));
256 void calculatePriceOutOfRangeEnd() throws IOException {
257 mockCommonDatasets(actions);
259 BigDecimal actual = actions.calculatePrice(Instant.parse("2023-02-05T22:00:00Z"),
260 Instant.parse("2023-02-05T23:01:00Z"), new QuantityType<>(1000, Units.WATT));
261 assertThat(actual, is(equalTo(BigDecimal.ZERO)));
265 * Miele G 6895 SCVi XXL K2O dishwasher, program ECO.
267 * @throws IOException
270 void calculateCheapestPeriodWithPowerDishwasher() throws IOException {
271 mockCommonDatasets(actions, "SpotPrices20230205.json");
273 List<Duration> durations = List.of(Duration.ofMinutes(37), Duration.ofMinutes(8), Duration.ofMinutes(4),
274 Duration.ofMinutes(2), Duration.ofMinutes(4), Duration.ofMinutes(36), Duration.ofMinutes(41),
275 Duration.ofMinutes(104));
276 List<QuantityType<Power>> consumptions = List.of(QuantityType.valueOf(162.162162, Units.WATT),
277 QuantityType.valueOf(750, Units.WATT), QuantityType.valueOf(1500, Units.WATT),
278 QuantityType.valueOf(3000, Units.WATT), QuantityType.valueOf(1500, Units.WATT),
279 QuantityType.valueOf(166.666666, Units.WATT), QuantityType.valueOf(146.341463, Units.WATT),
280 QuantityType.valueOf(0, Units.WATT));
281 Map<String, Object> actual = actions.calculateCheapestPeriod(Instant.parse("2023-02-05T16:00:00Z"),
282 Instant.parse("2023-02-06T06:00:00Z"), durations, consumptions);
283 assertThat(actual.get("LowestPrice"), is(equalTo(new BigDecimal("1.024218147103792520"))));
284 assertThat(actual.get("CheapestStart"), is(equalTo(Instant.parse("2023-02-05T19:23:00Z"))));
285 assertThat(actual.get("HighestPrice"), is(equalTo(new BigDecimal("1.530671034828983196"))));
286 assertThat(actual.get("MostExpensiveStart"), is(equalTo(Instant.parse("2023-02-05T16:00:00Z"))));
290 void calculateCheapestPeriodWithPowerOutOfRange() throws IOException {
291 mockCommonDatasets(actions);
293 List<Duration> durations = List.of(Duration.ofMinutes(61));
294 List<QuantityType<Power>> consumptions = List.of(QuantityType.valueOf(1000, Units.WATT));
295 Map<String, Object> actual = actions.calculateCheapestPeriod(Instant.parse("2023-02-04T12:00:00Z"),
296 Instant.parse("2023-02-06T00:01:00Z"), durations, consumptions);
297 assertThat(actual.size(), is(equalTo(0)));
301 * Miele G 6895 SCVi XXL K2O dishwasher, program ECO.
303 * @throws IOException
306 void calculateCheapestPeriodWithEnergyDishwasher() throws IOException {
307 mockCommonDatasets(actions, "SpotPrices20230205.json");
309 List<Duration> durations = List.of(Duration.ofMinutes(37), Duration.ofMinutes(8), Duration.ofMinutes(4),
310 Duration.ofMinutes(2), Duration.ofMinutes(4), Duration.ofMinutes(36), Duration.ofMinutes(41));
311 Map<String, Object> actual = actions.calculateCheapestPeriod(Instant.parse("2023-02-05T16:00:00Z"),
312 Instant.parse("2023-02-06T06:00:00Z"), Duration.ofMinutes(236), durations,
313 QuantityType.valueOf(0.1, Units.KILOWATT_HOUR));
314 assertThat(actual.get("LowestPrice"), is(equalTo(new BigDecimal("1.024218147103792520"))));
315 assertThat(actual.get("CheapestStart"), is(equalTo(Instant.parse("2023-02-05T19:23:00Z"))));
316 assertThat(actual.get("HighestPrice"), is(equalTo(new BigDecimal("1.530671034828983196"))));
317 assertThat(actual.get("MostExpensiveStart"), is(equalTo(Instant.parse("2023-02-05T16:00:00Z"))));
321 void calculateCheapestPeriodWithEnergyTotalDurationIsExactSum() throws IOException {
322 mockCommonDatasets(actions, "SpotPrices20230205.json");
324 List<Duration> durations = List.of(Duration.ofMinutes(60), Duration.ofMinutes(60));
325 Map<String, Object> actual = actions.calculateCheapestPeriod(Instant.parse("2023-02-05T16:00:00Z"),
326 Instant.parse("2023-02-06T06:00:00Z"), Duration.ofMinutes(120), durations,
327 QuantityType.valueOf(100, Units.WATT_HOUR));
328 assertThat(actual.get("LowestPrice"), is(equalTo(new BigDecimal("0.293540001200000000"))));
329 assertThat(actual.get("CheapestStart"), is(equalTo(Instant.parse("2023-02-05T19:00:00Z"))));
333 void calculateCheapestPeriodWithEnergyTotalDurationInvalid() throws IOException {
334 mockCommonDatasets(actions, "SpotPrices20230205.json");
336 List<Duration> durations = List.of(Duration.ofMinutes(60), Duration.ofMinutes(60));
337 Map<String, Object> actual = actions.calculateCheapestPeriod(Instant.parse("2023-02-05T16:00:00Z"),
338 Instant.parse("2023-02-06T06:00:00Z"), Duration.ofMinutes(119), durations,
339 QuantityType.valueOf(0.1, Units.KILOWATT_HOUR));
340 assertThat(actual.size(), is(equalTo(0)));
344 * Like {@link #calculateCheapestPeriodWithEnergyDishwasher} but with unknown consumption/timetable map.
346 * @throws IOException
349 void calculateCheapestPeriodAssumingLinearUnknownConsumption() throws IOException {
350 mockCommonDatasets(actions, "SpotPrices20230205.json");
352 Map<String, Object> actual = actions.calculateCheapestPeriod(Instant.parse("2023-02-05T16:00:00Z"),
353 Instant.parse("2023-02-06T06:00:00Z"), Duration.ofMinutes(236));
354 assertThat(actual.get("LowestPrice"), is(nullValue()));
355 assertThat(actual.get("CheapestStart"), is(equalTo(Instant.parse("2023-02-05T19:00:00Z"))));
356 assertThat(actual.get("HighestPrice"), is(nullValue()));
357 assertThat(actual.get("MostExpensiveStart"), is(equalTo(Instant.parse("2023-02-05T16:00:00Z"))));
361 void calculateCheapestPeriodForLinearPowerUsage() throws IOException {
362 mockCommonDatasets(actions);
364 Map<String, Object> actual = actions.calculateCheapestPeriod(Instant.parse("2023-02-04T12:00:00Z"),
365 Instant.parse("2023-02-05T23:00:00Z"), Duration.ofMinutes(61), QuantityType.valueOf(1000, Units.WATT));
366 assertThat(actual.get("LowestPrice"), is(equalTo(new BigDecimal("1.323990859575000000"))));
367 assertThat(actual.get("CheapestStart"), is(equalTo(Instant.parse("2023-02-05T12:00:00Z"))));
368 assertThat(actual.get("HighestPrice"), is(equalTo(new BigDecimal("2.589061780353348000"))));
369 assertThat(actual.get("MostExpensiveStart"), is(equalTo(Instant.parse("2023-02-04T17:00:00Z"))));
372 private void mockCommonDatasets(EnergiDataServiceActions actions) throws IOException {
373 mockCommonDatasets(actions, "SpotPrices20230204.json");
376 private void mockCommonDatasets(EnergiDataServiceActions actions, String spotPricesFilename) throws IOException {
377 SpotPrice[] spotPriceRecords = getObjectFromJson(spotPricesFilename, SpotPrice[].class);
378 Map<Instant, BigDecimal> spotPrices = Arrays.stream(spotPriceRecords)
379 .collect(Collectors.toMap(SpotPrice::hourStart, SpotPrice::spotPrice));
381 PriceListParser priceListParser = new PriceListParser(
382 Clock.fixed(spotPriceRecords[0].hourStart, EnergiDataServiceBindingConstants.DATAHUB_TIMEZONE));
383 DatahubPricelistRecords datahubRecords = getObjectFromJson("NetTariffs.json", DatahubPricelistRecords.class);
384 Map<Instant, BigDecimal> netTariffs = priceListParser
385 .toHourly(Arrays.stream(datahubRecords.records()).toList());
386 datahubRecords = getObjectFromJson("SystemTariffs.json", DatahubPricelistRecords.class);
387 Map<Instant, BigDecimal> systemTariffs = priceListParser
388 .toHourly(Arrays.stream(datahubRecords.records()).toList());
389 datahubRecords = getObjectFromJson("ElectricityTaxes.json", DatahubPricelistRecords.class);
390 Map<Instant, BigDecimal> electricityTaxes = priceListParser
391 .toHourly(Arrays.stream(datahubRecords.records()).toList());
392 datahubRecords = getObjectFromJson("TransmissionNetTariffs.json", DatahubPricelistRecords.class);
393 Map<Instant, BigDecimal> transmissionNetTariffs = priceListParser
394 .toHourly(Arrays.stream(datahubRecords.records()).toList());
396 when(handler.getSpotPrices()).thenReturn(spotPrices);
397 when(handler.getTariffs(DatahubTariff.NET_TARIFF)).thenReturn(netTariffs);
398 when(handler.getTariffs(DatahubTariff.SYSTEM_TARIFF)).thenReturn(systemTariffs);
399 when(handler.getTariffs(DatahubTariff.ELECTRICITY_TAX)).thenReturn(electricityTaxes);
400 when(handler.getTariffs(DatahubTariff.TRANSMISSION_NET_TARIFF)).thenReturn(transmissionNetTariffs);
401 when(handler.getCurrency()).thenReturn(EnergiDataServiceBindingConstants.CURRENCY_DKK);
402 actions.setThingHandler(handler);