]> git.basschouten.com Git - openhab-addons.git/blob
2a66f4442072678a553de30fdef972902aea67bf
[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.handler;
14
15 import static org.openhab.binding.energidataservice.internal.EnergiDataServiceBindingConstants.*;
16 import static org.openhab.core.types.TimeSeries.Policy.REPLACE;
17
18 import java.math.BigDecimal;
19 import java.time.Duration;
20 import java.time.Instant;
21 import java.time.LocalDateTime;
22 import java.time.LocalTime;
23 import java.time.format.DateTimeFormatter;
24 import java.time.temporal.ChronoUnit;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Currency;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Set;
33 import java.util.concurrent.ScheduledFuture;
34 import java.util.concurrent.TimeUnit;
35
36 import javax.measure.Unit;
37
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.eclipse.jetty.client.HttpClient;
41 import org.eclipse.jetty.http.HttpStatus;
42 import org.openhab.binding.energidataservice.internal.ApiController;
43 import org.openhab.binding.energidataservice.internal.CacheManager;
44 import org.openhab.binding.energidataservice.internal.DatahubTariff;
45 import org.openhab.binding.energidataservice.internal.action.EnergiDataServiceActions;
46 import org.openhab.binding.energidataservice.internal.api.ChargeType;
47 import org.openhab.binding.energidataservice.internal.api.ChargeTypeCode;
48 import org.openhab.binding.energidataservice.internal.api.DatahubTariffFilter;
49 import org.openhab.binding.energidataservice.internal.api.DatahubTariffFilterFactory;
50 import org.openhab.binding.energidataservice.internal.api.Dataset;
51 import org.openhab.binding.energidataservice.internal.api.DateQueryParameter;
52 import org.openhab.binding.energidataservice.internal.api.DateQueryParameterType;
53 import org.openhab.binding.energidataservice.internal.api.GlobalLocationNumber;
54 import org.openhab.binding.energidataservice.internal.api.dto.CO2EmissionRecord;
55 import org.openhab.binding.energidataservice.internal.api.dto.DatahubPricelistRecord;
56 import org.openhab.binding.energidataservice.internal.api.dto.ElspotpriceRecord;
57 import org.openhab.binding.energidataservice.internal.config.DatahubPriceConfiguration;
58 import org.openhab.binding.energidataservice.internal.config.EnergiDataServiceConfiguration;
59 import org.openhab.binding.energidataservice.internal.exception.DataServiceException;
60 import org.openhab.binding.energidataservice.internal.retry.RetryPolicyFactory;
61 import org.openhab.binding.energidataservice.internal.retry.RetryStrategy;
62 import org.openhab.core.i18n.TimeZoneProvider;
63 import org.openhab.core.library.types.DecimalType;
64 import org.openhab.core.library.types.QuantityType;
65 import org.openhab.core.library.unit.CurrencyUnits;
66 import org.openhab.core.library.unit.Units;
67 import org.openhab.core.thing.Channel;
68 import org.openhab.core.thing.ChannelUID;
69 import org.openhab.core.thing.Thing;
70 import org.openhab.core.thing.ThingStatus;
71 import org.openhab.core.thing.ThingStatusDetail;
72 import org.openhab.core.thing.binding.BaseThingHandler;
73 import org.openhab.core.thing.binding.ThingHandlerService;
74 import org.openhab.core.types.Command;
75 import org.openhab.core.types.RefreshType;
76 import org.openhab.core.types.State;
77 import org.openhab.core.types.TimeSeries;
78 import org.openhab.core.types.UnDefType;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81
82 /**
83  * The {@link EnergiDataServiceHandler} is responsible for handling commands, which are
84  * sent to one of the channels.
85  *
86  * @author Jacob Laursen - Initial contribution
87  */
88 @NonNullByDefault
89 public class EnergiDataServiceHandler extends BaseThingHandler {
90
91     private static final Duration emissionPrognosisJobInterval = Duration.ofMinutes(15);
92     private static final Duration emissionRealtimeJobInterval = Duration.ofMinutes(5);
93
94     private final Logger logger = LoggerFactory.getLogger(EnergiDataServiceHandler.class);
95     private final TimeZoneProvider timeZoneProvider;
96     private final ApiController apiController;
97     private final CacheManager cacheManager;
98
99     private EnergiDataServiceConfiguration config;
100     private RetryStrategy retryPolicy = RetryPolicyFactory.initial();
101     private boolean realtimeEmissionsFetchedFirstTime = false;
102     private @Nullable ScheduledFuture<?> refreshPriceFuture;
103     private @Nullable ScheduledFuture<?> refreshEmissionPrognosisFuture;
104     private @Nullable ScheduledFuture<?> refreshEmissionRealtimeFuture;
105     private @Nullable ScheduledFuture<?> priceUpdateFuture;
106
107     public EnergiDataServiceHandler(Thing thing, HttpClient httpClient, TimeZoneProvider timeZoneProvider) {
108         super(thing);
109         this.timeZoneProvider = timeZoneProvider;
110         this.apiController = new ApiController(httpClient, timeZoneProvider);
111         this.cacheManager = new CacheManager();
112
113         // Default configuration
114         this.config = new EnergiDataServiceConfiguration();
115     }
116
117     @Override
118     public void handleCommand(ChannelUID channelUID, Command command) {
119         if (!(command instanceof RefreshType)) {
120             return;
121         }
122
123         String channelId = channelUID.getId();
124         if (ELECTRICITY_CHANNELS.contains(channelId)) {
125             refreshElectricityPrices();
126         } else if (CHANNEL_CO2_EMISSION_PROGNOSIS.equals(channelId)) {
127             rescheduleEmissionPrognosisJob();
128         } else if (CHANNEL_CO2_EMISSION_REALTIME.equals(channelId)) {
129             realtimeEmissionsFetchedFirstTime = false;
130             rescheduleEmissionRealtimeJob();
131         }
132     }
133
134     @Override
135     public void initialize() {
136         config = getConfigAs(EnergiDataServiceConfiguration.class);
137
138         if (config.priceArea.isBlank()) {
139             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
140                     "@text/offline.conf-error.no-price-area");
141             return;
142         }
143         GlobalLocationNumber gln = config.getGridCompanyGLN();
144         if (!gln.isEmpty() && !gln.isValid()) {
145             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
146                     "@text/offline.conf-error.invalid-grid-company-gln");
147             return;
148         }
149         gln = config.getEnerginetGLN();
150         if (!gln.isEmpty() && !gln.isValid()) {
151             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
152                     "@text/offline.conf-error.invalid-energinet-gln");
153             return;
154         }
155
156         updateStatus(ThingStatus.UNKNOWN);
157
158         refreshPriceFuture = scheduler.schedule(this::refreshElectricityPrices, 0, TimeUnit.SECONDS);
159
160         if (isLinked(CHANNEL_CO2_EMISSION_PROGNOSIS)) {
161             rescheduleEmissionPrognosisJob();
162         }
163         if (isLinked(CHANNEL_CO2_EMISSION_REALTIME)) {
164             rescheduleEmissionRealtimeJob();
165         }
166     }
167
168     @Override
169     public void dispose() {
170         ScheduledFuture<?> refreshPriceFuture = this.refreshPriceFuture;
171         if (refreshPriceFuture != null) {
172             refreshPriceFuture.cancel(true);
173             this.refreshPriceFuture = null;
174         }
175         ScheduledFuture<?> refreshEmissionPrognosisFuture = this.refreshEmissionPrognosisFuture;
176         if (refreshEmissionPrognosisFuture != null) {
177             refreshEmissionPrognosisFuture.cancel(true);
178             this.refreshEmissionPrognosisFuture = null;
179         }
180         ScheduledFuture<?> refreshEmissionRealtimeFuture = this.refreshEmissionRealtimeFuture;
181         if (refreshEmissionRealtimeFuture != null) {
182             refreshEmissionRealtimeFuture.cancel(true);
183             this.refreshEmissionRealtimeFuture = null;
184         }
185         ScheduledFuture<?> priceUpdateFuture = this.priceUpdateFuture;
186         if (priceUpdateFuture != null) {
187             priceUpdateFuture.cancel(true);
188             this.priceUpdateFuture = null;
189         }
190
191         cacheManager.clear();
192     }
193
194     @Override
195     public Collection<Class<? extends ThingHandlerService>> getServices() {
196         return Set.of(EnergiDataServiceActions.class);
197     }
198
199     @Override
200     public void channelUnlinked(ChannelUID channelUID) {
201         super.channelUnlinked(channelUID);
202
203         if (CHANNEL_CO2_EMISSION_PROGNOSIS.equals(channelUID.getId()) && !isLinked(CHANNEL_CO2_EMISSION_PROGNOSIS)) {
204             logger.debug("No more items linked to channel '{}', stopping emission prognosis refresh job",
205                     channelUID.getId());
206             ScheduledFuture<?> refreshEmissionPrognosisFuture = this.refreshEmissionPrognosisFuture;
207             if (refreshEmissionPrognosisFuture != null) {
208                 refreshEmissionPrognosisFuture.cancel(true);
209                 this.refreshEmissionPrognosisFuture = null;
210             }
211         } else if (CHANNEL_CO2_EMISSION_REALTIME.contains(channelUID.getId())
212                 && !isLinked(CHANNEL_CO2_EMISSION_REALTIME)) {
213             logger.debug("No more items linked to channel '{}', stopping realtime emission refresh job",
214                     channelUID.getId());
215             ScheduledFuture<?> refreshEmissionRealtimeFuture = this.refreshEmissionRealtimeFuture;
216             if (refreshEmissionRealtimeFuture != null) {
217                 refreshEmissionRealtimeFuture.cancel(true);
218                 this.refreshEmissionRealtimeFuture = null;
219             }
220         }
221     }
222
223     private void refreshElectricityPrices() {
224         RetryStrategy retryPolicy;
225         try {
226             if (isLinked(CHANNEL_SPOT_PRICE)) {
227                 downloadSpotPrices();
228             }
229
230             for (DatahubTariff datahubTariff : DatahubTariff.values()) {
231                 if (isLinked(datahubTariff.getChannelId())) {
232                     downloadTariffs(datahubTariff);
233                 }
234             }
235
236             updateStatus(ThingStatus.ONLINE);
237             updatePrices();
238             updateTimeSeries();
239
240             if (isLinked(CHANNEL_SPOT_PRICE)) {
241                 if (cacheManager.getNumberOfFutureSpotPrices() < 13) {
242                     logger.warn("Spot prices are not yet available, retry scheduled (see details in Thing properties)");
243                     retryPolicy = RetryPolicyFactory.whenExpectedSpotPriceDataMissing(DAILY_REFRESH_TIME_CET,
244                             NORD_POOL_TIMEZONE);
245                 } else {
246                     retryPolicy = RetryPolicyFactory.atFixedTime(DAILY_REFRESH_TIME_CET, NORD_POOL_TIMEZONE);
247                 }
248             } else {
249                 retryPolicy = RetryPolicyFactory.atFixedTime(LocalTime.MIDNIGHT, timeZoneProvider.getTimeZone());
250             }
251         } catch (DataServiceException e) {
252             if (e.getHttpStatus() != 0) {
253                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
254                         HttpStatus.getCode(e.getHttpStatus()).getMessage());
255             } else {
256                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
257             }
258             if (e.getCause() != null) {
259                 logger.debug("Error retrieving prices", e);
260             }
261             retryPolicy = RetryPolicyFactory.fromThrowable(e);
262         } catch (InterruptedException e) {
263             logger.debug("Refresh job interrupted");
264             Thread.currentThread().interrupt();
265             return;
266         }
267
268         reschedulePriceRefreshJob(retryPolicy);
269     }
270
271     private void downloadSpotPrices() throws InterruptedException, DataServiceException {
272         if (cacheManager.areSpotPricesFullyCached()) {
273             logger.debug("Cached spot prices still valid, skipping download.");
274             return;
275         }
276         DateQueryParameter start;
277         if (cacheManager.areHistoricSpotPricesCached()) {
278             start = DateQueryParameter.of(DateQueryParameterType.UTC_NOW);
279         } else {
280             start = DateQueryParameter.of(DateQueryParameterType.UTC_NOW,
281                     Duration.ofHours(-CacheManager.NUMBER_OF_HISTORIC_HOURS));
282         }
283         Map<String, String> properties = editProperties();
284         ElspotpriceRecord[] spotPriceRecords = apiController.getSpotPrices(config.priceArea, config.getCurrency(),
285                 start, properties);
286         cacheManager.putSpotPrices(spotPriceRecords, config.getCurrency());
287         updateProperties(properties);
288     }
289
290     private void downloadTariffs(DatahubTariff datahubTariff) throws InterruptedException, DataServiceException {
291         GlobalLocationNumber globalLocationNumber = switch (datahubTariff) {
292             case GRID_TARIFF -> config.getGridCompanyGLN();
293             default -> config.getEnerginetGLN();
294         };
295         if (globalLocationNumber.isEmpty()) {
296             return;
297         }
298         if (cacheManager.areTariffsValidTomorrow(datahubTariff)) {
299             logger.debug("Cached tariffs of type {} still valid, skipping download.", datahubTariff);
300             cacheManager.updateTariffs(datahubTariff);
301         } else {
302             DatahubTariffFilter filter = switch (datahubTariff) {
303                 case GRID_TARIFF -> getGridTariffFilter();
304                 case SYSTEM_TARIFF -> DatahubTariffFilterFactory.getSystemTariff();
305                 case TRANSMISSION_GRID_TARIFF -> DatahubTariffFilterFactory.getTransmissionGridTariff();
306                 case ELECTRICITY_TAX -> DatahubTariffFilterFactory.getElectricityTax();
307                 case REDUCED_ELECTRICITY_TAX -> DatahubTariffFilterFactory.getReducedElectricityTax();
308             };
309             cacheManager.putTariffs(datahubTariff, downloadPriceLists(globalLocationNumber, filter));
310         }
311     }
312
313     private Collection<DatahubPricelistRecord> downloadPriceLists(GlobalLocationNumber globalLocationNumber,
314             DatahubTariffFilter filter) throws InterruptedException, DataServiceException {
315         Map<String, String> properties = editProperties();
316         Collection<DatahubPricelistRecord> records = apiController.getDatahubPriceLists(globalLocationNumber,
317                 ChargeType.Tariff, filter, properties);
318         updateProperties(properties);
319
320         return records;
321     }
322
323     private DatahubTariffFilter getGridTariffFilter() {
324         Channel channel = getThing().getChannel(CHANNEL_GRID_TARIFF);
325         if (channel == null) {
326             return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
327         }
328
329         DatahubPriceConfiguration datahubPriceConfiguration = channel.getConfiguration()
330                 .as(DatahubPriceConfiguration.class);
331
332         if (!datahubPriceConfiguration.hasAnyFilterOverrides()) {
333             return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
334         }
335
336         DateQueryParameter start = datahubPriceConfiguration.getStart();
337         if (start == null) {
338             logger.warn("Invalid channel configuration parameter 'start' or 'offset': {} (offset: {})",
339                     datahubPriceConfiguration.start, datahubPriceConfiguration.offset);
340             return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
341         }
342
343         Set<ChargeTypeCode> chargeTypeCodes = datahubPriceConfiguration.getChargeTypeCodes();
344         Set<String> notes = datahubPriceConfiguration.getNotes();
345         DatahubTariffFilter filter;
346         if (!chargeTypeCodes.isEmpty() || !notes.isEmpty()) {
347             // Completely override filter.
348             filter = new DatahubTariffFilter(chargeTypeCodes, notes, start);
349         } else {
350             // Only override start date in pre-configured filter.
351             filter = new DatahubTariffFilter(DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN),
352                     start);
353         }
354
355         return new DatahubTariffFilter(filter, DateQueryParameter.of(filter.getDateQueryParameter(),
356                 Duration.ofHours(-CacheManager.NUMBER_OF_HISTORIC_HOURS)));
357     }
358
359     private void refreshCo2EmissionPrognosis() {
360         try {
361             updateCo2Emissions(Dataset.CO2EmissionPrognosis, CHANNEL_CO2_EMISSION_PROGNOSIS,
362                     DateQueryParameter.of(DateQueryParameterType.UTC_NOW, Duration.ofMinutes(-5)));
363             updateStatus(ThingStatus.ONLINE);
364         } catch (DataServiceException e) {
365             if (e.getHttpStatus() != 0) {
366                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
367                         HttpStatus.getCode(e.getHttpStatus()).getMessage());
368             } else {
369                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
370             }
371             if (e.getCause() != null) {
372                 logger.debug("Error retrieving CO2 emission prognosis", e);
373             }
374         } catch (InterruptedException e) {
375             logger.debug("Emission prognosis refresh job interrupted");
376             Thread.currentThread().interrupt();
377             return;
378         }
379     }
380
381     private void refreshCo2EmissionRealtime() {
382         try {
383             updateCo2Emissions(Dataset.CO2Emission, CHANNEL_CO2_EMISSION_REALTIME,
384                     DateQueryParameter.of(DateQueryParameterType.UTC_NOW,
385                             realtimeEmissionsFetchedFirstTime ? Duration.ofMinutes(-5) : Duration.ofHours(-24)));
386             realtimeEmissionsFetchedFirstTime = true;
387             updateStatus(ThingStatus.ONLINE);
388         } catch (DataServiceException e) {
389             if (e.getHttpStatus() != 0) {
390                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
391                         HttpStatus.getCode(e.getHttpStatus()).getMessage());
392             } else {
393                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
394             }
395             if (e.getCause() != null) {
396                 logger.debug("Error retrieving CO2 realtime emissions", e);
397             }
398         } catch (InterruptedException e) {
399             logger.debug("Emission realtime refresh job interrupted");
400             Thread.currentThread().interrupt();
401             return;
402         }
403     }
404
405     private void updateCo2Emissions(Dataset dataset, String channelId, DateQueryParameter dateQueryParameter)
406             throws InterruptedException, DataServiceException {
407         Map<String, String> properties = editProperties();
408         CO2EmissionRecord[] emissionRecords = apiController.getCo2Emissions(dataset, config.priceArea,
409                 dateQueryParameter, properties);
410         updateProperties(properties);
411
412         TimeSeries timeSeries = new TimeSeries(REPLACE);
413         Instant now = Instant.now();
414
415         if (dataset == Dataset.CO2Emission && emissionRecords.length > 0) {
416             // Records are sorted descending, first record is current.
417             updateState(channelId, new QuantityType<>(emissionRecords[0].emission(), Units.GRAM_PER_KILOWATT_HOUR));
418         }
419
420         for (CO2EmissionRecord emissionRecord : emissionRecords) {
421             State state = new QuantityType<>(emissionRecord.emission(), Units.GRAM_PER_KILOWATT_HOUR);
422             timeSeries.add(emissionRecord.start(), state);
423
424             if (dataset == Dataset.CO2EmissionPrognosis && now.compareTo(emissionRecord.start()) >= 0
425                     && now.compareTo(emissionRecord.end()) < 0) {
426                 updateState(channelId, state);
427             }
428         }
429         sendTimeSeries(channelId, timeSeries);
430     }
431
432     private void updatePrices() {
433         cacheManager.cleanup();
434
435         updateCurrentSpotPrice();
436         Arrays.stream(DatahubTariff.values())
437                 .forEach(tariff -> updateCurrentTariff(tariff.getChannelId(), cacheManager.getTariff(tariff)));
438
439         reschedulePriceUpdateJob();
440     }
441
442     private void updateCurrentSpotPrice() {
443         if (!isLinked(CHANNEL_SPOT_PRICE)) {
444             return;
445         }
446         BigDecimal spotPrice = cacheManager.getSpotPrice();
447         updatePriceState(CHANNEL_SPOT_PRICE, spotPrice, config.getCurrency());
448     }
449
450     private void updateCurrentTariff(String channelId, @Nullable BigDecimal tariff) {
451         if (!isLinked(channelId)) {
452             return;
453         }
454         updatePriceState(channelId, tariff, CURRENCY_DKK);
455     }
456
457     private void updatePriceState(String channelID, @Nullable BigDecimal price, Currency currency) {
458         updateState(channelID, price != null ? getEnergyPrice(price, currency) : UnDefType.UNDEF);
459     }
460
461     private State getEnergyPrice(BigDecimal price, Currency currency) {
462         String currencyCode = currency.getCurrencyCode();
463         Unit<?> unit = CurrencyUnits.getInstance().getUnit(currencyCode);
464         if (unit == null) {
465             logger.trace("Currency {} is unknown, falling back to DecimalType", currency.getCurrencyCode());
466             return new DecimalType(price);
467         }
468         try {
469             return new QuantityType<>(price + " " + currencyCode + "/kWh");
470         } catch (IllegalArgumentException e) {
471             logger.debug("Unable to create QuantityType, falling back to DecimalType", e);
472             return new DecimalType(price);
473         }
474     }
475
476     private void updateTimeSeries() {
477         TimeSeries spotPriceTimeSeries = new TimeSeries(REPLACE);
478         Map<DatahubTariff, TimeSeries> datahubTimeSeriesMap = new HashMap<>();
479         Map<DatahubTariff, BigDecimal> datahubPreviousTariff = new HashMap<>();
480         for (DatahubTariff datahubTariff : DatahubTariff.values()) {
481             datahubTimeSeriesMap.put(datahubTariff, new TimeSeries(REPLACE));
482         }
483
484         Map<Instant, BigDecimal> spotPriceMap = cacheManager.getSpotPrices();
485         List<Entry<Instant, BigDecimal>> spotPrices = spotPriceMap.entrySet().stream()
486                 .sorted(Map.Entry.comparingByKey()).toList();
487         for (Entry<Instant, BigDecimal> spotPrice : spotPrices) {
488             Instant hourStart = spotPrice.getKey();
489             if (isLinked(CHANNEL_SPOT_PRICE)) {
490                 spotPriceTimeSeries.add(hourStart, getEnergyPrice(spotPrice.getValue(), config.getCurrency()));
491             }
492             for (Map.Entry<DatahubTariff, TimeSeries> entry : datahubTimeSeriesMap.entrySet()) {
493                 DatahubTariff datahubTariff = entry.getKey();
494                 String channelId = datahubTariff.getChannelId();
495                 if (!isLinked(channelId)) {
496                     continue;
497                 }
498                 BigDecimal tariff = cacheManager.getTariff(datahubTariff, hourStart);
499                 if (tariff != null) {
500                     BigDecimal previousTariff = datahubPreviousTariff.get(datahubTariff);
501                     if (previousTariff != null && tariff.equals(previousTariff)) {
502                         // Skip redundant states.
503                         continue;
504                     }
505                     TimeSeries timeSeries = entry.getValue();
506                     timeSeries.add(hourStart, getEnergyPrice(tariff, CURRENCY_DKK));
507                     datahubPreviousTariff.put(datahubTariff, tariff);
508                 }
509             }
510         }
511         if (spotPriceTimeSeries.size() > 0) {
512             sendTimeSeries(CHANNEL_SPOT_PRICE, spotPriceTimeSeries);
513         }
514         for (Map.Entry<DatahubTariff, TimeSeries> entry : datahubTimeSeriesMap.entrySet()) {
515             DatahubTariff datahubTariff = entry.getKey();
516             String channelId = datahubTariff.getChannelId();
517             if (!isLinked(channelId)) {
518                 continue;
519             }
520             TimeSeries timeSeries = entry.getValue();
521             if (timeSeries.size() > 0) {
522                 sendTimeSeries(channelId, timeSeries);
523             }
524         }
525     }
526
527     /**
528      * Get the configured {@link Currency} for spot prices.
529      * 
530      * @return Spot price currency
531      */
532     public Currency getCurrency() {
533         return config.getCurrency();
534     }
535
536     /**
537      * Get cached spot prices or try once to download them if not cached
538      * (usually if no items are linked).
539      *
540      * @return Map of future spot prices
541      */
542     public Map<Instant, BigDecimal> getSpotPrices() {
543         try {
544             downloadSpotPrices();
545         } catch (DataServiceException e) {
546             if (logger.isDebugEnabled()) {
547                 logger.warn("Error retrieving spot prices", e);
548             } else {
549                 logger.warn("Error retrieving spot prices: {}", e.getMessage());
550             }
551         } catch (InterruptedException e) {
552             Thread.currentThread().interrupt();
553         }
554
555         return cacheManager.getSpotPrices();
556     }
557
558     /**
559      * Return cached tariffs or try once to download them if not cached
560      * (usually if no items are linked).
561      *
562      * @return Map of future tariffs
563      */
564     public Map<Instant, BigDecimal> getTariffs(DatahubTariff datahubTariff) {
565         try {
566             downloadTariffs(datahubTariff);
567         } catch (DataServiceException e) {
568             if (logger.isDebugEnabled()) {
569                 logger.warn("Error retrieving tariffs", e);
570             } else {
571                 logger.warn("Error retrieving tariffs of type {}: {}", datahubTariff, e.getMessage());
572             }
573         } catch (InterruptedException e) {
574             Thread.currentThread().interrupt();
575         }
576
577         return cacheManager.getTariffs(datahubTariff);
578     }
579
580     /**
581      * Return whether reduced electricity tax is set in configuration.
582      *
583      * @return true if reduced electricity tax applies
584      */
585     public boolean isReducedElectricityTax() {
586         return config.reducedElectricityTax;
587     }
588
589     private void reschedulePriceUpdateJob() {
590         ScheduledFuture<?> priceUpdateJob = this.priceUpdateFuture;
591         if (priceUpdateJob != null) {
592             // Do not interrupt ourselves.
593             priceUpdateJob.cancel(false);
594             this.priceUpdateFuture = null;
595         }
596
597         Instant now = Instant.now();
598         long millisUntilNextClockHour = Duration
599                 .between(now, now.plus(1, ChronoUnit.HOURS).truncatedTo(ChronoUnit.HOURS)).toMillis() + 1;
600         this.priceUpdateFuture = scheduler.schedule(this::updatePrices, millisUntilNextClockHour,
601                 TimeUnit.MILLISECONDS);
602         logger.debug("Price update job rescheduled in {} milliseconds", millisUntilNextClockHour);
603     }
604
605     private void reschedulePriceRefreshJob(RetryStrategy retryPolicy) {
606         // Preserve state of previous retry policy when configuration is the same.
607         if (!retryPolicy.equals(this.retryPolicy)) {
608             this.retryPolicy = retryPolicy;
609         }
610
611         ScheduledFuture<?> refreshJob = this.refreshPriceFuture;
612
613         long secondsUntilNextRefresh = this.retryPolicy.getDuration().getSeconds();
614         Instant timeOfNextRefresh = Instant.now().plusSeconds(secondsUntilNextRefresh);
615         this.refreshPriceFuture = scheduler.schedule(this::refreshElectricityPrices, secondsUntilNextRefresh,
616                 TimeUnit.SECONDS);
617         logger.debug("Price refresh job rescheduled in {} seconds: {}", secondsUntilNextRefresh, timeOfNextRefresh);
618         DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PROPERTY_DATETIME_FORMAT);
619         updateProperty(PROPERTY_NEXT_CALL, LocalDateTime.ofInstant(timeOfNextRefresh, timeZoneProvider.getTimeZone())
620                 .truncatedTo(ChronoUnit.SECONDS).format(formatter));
621
622         if (refreshJob != null) {
623             refreshJob.cancel(true);
624         }
625     }
626
627     private void rescheduleEmissionPrognosisJob() {
628         logger.debug("Scheduling emission prognosis refresh job now and every {}", emissionPrognosisJobInterval);
629
630         ScheduledFuture<?> refreshEmissionPrognosisFuture = this.refreshEmissionPrognosisFuture;
631         if (refreshEmissionPrognosisFuture != null) {
632             refreshEmissionPrognosisFuture.cancel(true);
633         }
634
635         this.refreshEmissionPrognosisFuture = scheduler.scheduleWithFixedDelay(this::refreshCo2EmissionPrognosis, 0,
636                 emissionPrognosisJobInterval.toSeconds(), TimeUnit.SECONDS);
637     }
638
639     private void rescheduleEmissionRealtimeJob() {
640         logger.debug("Scheduling emission realtime refresh job now and every {}", emissionRealtimeJobInterval);
641
642         ScheduledFuture<?> refreshEmissionFuture = this.refreshEmissionRealtimeFuture;
643         if (refreshEmissionFuture != null) {
644             refreshEmissionFuture.cancel(true);
645         }
646
647         this.refreshEmissionRealtimeFuture = scheduler.scheduleWithFixedDelay(this::refreshCo2EmissionRealtime, 0,
648                 emissionRealtimeJobInterval.toSeconds(), TimeUnit.SECONDS);
649     }
650 }