]> git.basschouten.com Git - openhab-addons.git/blob
5679d3d7a4fb523f78820d29a766263c7fbdb31a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.action;
14
15 import static org.hamcrest.CoreMatchers.*;
16 import static org.hamcrest.MatcherAssert.assertThat;
17 import static org.mockito.Mockito.when;
18
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;
29 import java.util.Map;
30 import java.util.Objects;
31 import java.util.stream.Collectors;
32
33 import javax.measure.quantity.Power;
34
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;
53
54 import com.google.gson.Gson;
55 import com.google.gson.GsonBuilder;
56
57 import ch.qos.logback.classic.Level;
58 import ch.qos.logback.classic.Logger;
59
60 /**
61  * Tests for {@link EnergiDataServiceActions}.
62  * 
63  * @author Jacob Laursen - Initial contribution
64  */
65 @NonNullByDefault
66 @ExtendWith(MockitoExtension.class)
67 @MockitoSettings(strictness = Strictness.LENIENT)
68 public class EnergiDataServiceActionsTest {
69
70     private @NonNullByDefault({}) @Mock EnergiDataServiceHandler handler;
71     private EnergiDataServiceActions actions = new EnergiDataServiceActions();
72
73     private Gson gson = new GsonBuilder().registerTypeAdapter(Instant.class, new InstantDeserializer())
74             .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer()).create();
75
76     private record SpotPrice(Instant hourStart, BigDecimal spotPrice) {
77     }
78
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");
83             }
84             byte[] bytes = inputStream.readAllBytes();
85             if (bytes == null) {
86                 throw new IOException("Resulting byte-array empty");
87             }
88             String json = new String(bytes, StandardCharsets.UTF_8);
89             return Objects.requireNonNull(gson.fromJson(json, clazz));
90         }
91     }
92
93     @BeforeEach
94     void setUp() {
95         final Logger logger = (Logger) LoggerFactory.getLogger(EnergiDataServiceActions.class);
96         logger.setLevel(Level.OFF);
97
98         actions = new EnergiDataServiceActions();
99     }
100
101     @Test
102     void getPricesSpotPrice() throws IOException {
103         mockCommonDatasets(actions);
104
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"))));
109     }
110
111     @Test
112     void getPricesNetTariff() throws IOException {
113         mockCommonDatasets(actions);
114
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"))));
119     }
120
121     @Test
122     void getPricesSystemTariff() throws IOException {
123         mockCommonDatasets(actions);
124
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"))));
129     }
130
131     @Test
132     void getPricesElectricityTax() throws IOException {
133         mockCommonDatasets(actions);
134
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"))));
139     }
140
141     @Test
142     void getPricesTransmissionNetTariff() throws IOException {
143         mockCommonDatasets(actions);
144
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"))));
149     }
150
151     @Test
152     void getPricesSpotPriceNetTariff() throws IOException {
153         mockCommonDatasets(actions);
154
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"))));
159     }
160
161     @Test
162     void getPricesSpotPriceNetTariffElectricityTax() throws IOException {
163         mockCommonDatasets(actions);
164
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"))));
169     }
170
171     @Test
172     void getPricesTotal() throws IOException {
173         mockCommonDatasets(actions);
174
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"))));
179     }
180
181     @Test
182     void getPricesTotalAllElements() throws IOException {
183         mockCommonDatasets(actions);
184
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"))));
191     }
192
193     @Test
194     void getPricesInvalidPriceElement() throws IOException {
195         mockCommonDatasets(actions);
196
197         Map<Instant, BigDecimal> actual = actions.getPrices("spotprice,nettarif");
198         assertThat(actual.size(), is(0));
199     }
200
201     @Test
202     void getPricesMixedCurrencies() throws IOException {
203         mockCommonDatasets(actions);
204         when(handler.getCurrency()).thenReturn(EnergiDataServiceBindingConstants.CURRENCY_EUR);
205
206         Map<Instant, BigDecimal> actual = actions.getPrices("spotprice,nettariff");
207         assertThat(actual.size(), is(0));
208     }
209
210     /**
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
214      *
215      * Result = (1.708765039 / 2) + (2.443870054 / 2) * 0.150
216      *
217      * @throws IOException
218      */
219     @Test
220     void calculatePriceSimple() throws IOException {
221         mockCommonDatasets(actions);
222
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
226     }
227
228     /**
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
232      *
233      * Result = 1.708765039 + 2.443870054
234      *
235      * @throws IOException
236      */
237     @Test
238     void calculatePriceFullHours() throws IOException {
239         mockCommonDatasets(actions);
240
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
244     }
245
246     @Test
247     void calculatePriceOutOfRangeStart() throws IOException {
248         mockCommonDatasets(actions);
249
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)));
253     }
254
255     @Test
256     void calculatePriceOutOfRangeEnd() throws IOException {
257         mockCommonDatasets(actions);
258
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)));
262     }
263
264     /**
265      * Miele G 6895 SCVi XXL K2O dishwasher, program ECO.
266      *
267      * @throws IOException
268      */
269     @Test
270     void calculateCheapestPeriodWithPowerDishwasher() throws IOException {
271         mockCommonDatasets(actions, "SpotPrices20230205.json");
272
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"))));
287     }
288
289     @Test
290     void calculateCheapestPeriodWithPowerOutOfRange() throws IOException {
291         mockCommonDatasets(actions);
292
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)));
298     }
299
300     /**
301      * Miele G 6895 SCVi XXL K2O dishwasher, program ECO.
302      *
303      * @throws IOException
304      */
305     @Test
306     void calculateCheapestPeriodWithEnergyDishwasher() throws IOException {
307         mockCommonDatasets(actions, "SpotPrices20230205.json");
308
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"))));
318     }
319
320     @Test
321     void calculateCheapestPeriodWithEnergyTotalDurationIsExactSum() throws IOException {
322         mockCommonDatasets(actions, "SpotPrices20230205.json");
323
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"))));
330     }
331
332     @Test
333     void calculateCheapestPeriodWithEnergyTotalDurationInvalid() throws IOException {
334         mockCommonDatasets(actions, "SpotPrices20230205.json");
335
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)));
341     }
342
343     /**
344      * Like {@link #calculateCheapestPeriodWithEnergyDishwasher} but with unknown consumption/timetable map.
345      *
346      * @throws IOException
347      */
348     @Test
349     void calculateCheapestPeriodAssumingLinearUnknownConsumption() throws IOException {
350         mockCommonDatasets(actions, "SpotPrices20230205.json");
351
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"))));
358     }
359
360     @Test
361     void calculateCheapestPeriodForLinearPowerUsage() throws IOException {
362         mockCommonDatasets(actions);
363
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"))));
370     }
371
372     private void mockCommonDatasets(EnergiDataServiceActions actions) throws IOException {
373         mockCommonDatasets(actions, "SpotPrices20230204.json");
374     }
375
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));
380
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());
395
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);
403     }
404 }