2 * Copyright (c) 2010-2024 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.handler;
15 import static org.openhab.binding.energidataservice.internal.EnergiDataServiceBindingConstants.*;
16 import static org.openhab.core.types.TimeSeries.Policy.REPLACE;
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;
31 import java.util.Map.Entry;
33 import java.util.concurrent.ScheduledFuture;
34 import java.util.concurrent.TimeUnit;
36 import javax.measure.Unit;
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;
83 * The {@link EnergiDataServiceHandler} is responsible for handling commands, which are
84 * sent to one of the channels.
86 * @author Jacob Laursen - Initial contribution
89 public class EnergiDataServiceHandler extends BaseThingHandler {
91 private static final Duration emissionPrognosisJobInterval = Duration.ofMinutes(15);
92 private static final Duration emissionRealtimeJobInterval = Duration.ofMinutes(5);
94 private final Logger logger = LoggerFactory.getLogger(EnergiDataServiceHandler.class);
95 private final TimeZoneProvider timeZoneProvider;
96 private final ApiController apiController;
97 private final CacheManager cacheManager;
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;
107 public EnergiDataServiceHandler(Thing thing, HttpClient httpClient, TimeZoneProvider timeZoneProvider) {
109 this.timeZoneProvider = timeZoneProvider;
110 this.apiController = new ApiController(httpClient, timeZoneProvider);
111 this.cacheManager = new CacheManager();
113 // Default configuration
114 this.config = new EnergiDataServiceConfiguration();
118 public void handleCommand(ChannelUID channelUID, Command command) {
119 if (!(command instanceof RefreshType)) {
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();
135 public void initialize() {
136 config = getConfigAs(EnergiDataServiceConfiguration.class);
138 if (config.priceArea.isBlank()) {
139 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
140 "@text/offline.conf-error.no-price-area");
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");
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");
156 updateStatus(ThingStatus.UNKNOWN);
158 refreshPriceFuture = scheduler.schedule(this::refreshElectricityPrices, 0, TimeUnit.SECONDS);
160 if (isLinked(CHANNEL_CO2_EMISSION_PROGNOSIS)) {
161 rescheduleEmissionPrognosisJob();
163 if (isLinked(CHANNEL_CO2_EMISSION_REALTIME)) {
164 rescheduleEmissionRealtimeJob();
169 public void dispose() {
170 ScheduledFuture<?> refreshPriceFuture = this.refreshPriceFuture;
171 if (refreshPriceFuture != null) {
172 refreshPriceFuture.cancel(true);
173 this.refreshPriceFuture = null;
175 ScheduledFuture<?> refreshEmissionPrognosisFuture = this.refreshEmissionPrognosisFuture;
176 if (refreshEmissionPrognosisFuture != null) {
177 refreshEmissionPrognosisFuture.cancel(true);
178 this.refreshEmissionPrognosisFuture = null;
180 ScheduledFuture<?> refreshEmissionRealtimeFuture = this.refreshEmissionRealtimeFuture;
181 if (refreshEmissionRealtimeFuture != null) {
182 refreshEmissionRealtimeFuture.cancel(true);
183 this.refreshEmissionRealtimeFuture = null;
185 ScheduledFuture<?> priceUpdateFuture = this.priceUpdateFuture;
186 if (priceUpdateFuture != null) {
187 priceUpdateFuture.cancel(true);
188 this.priceUpdateFuture = null;
191 cacheManager.clear();
195 public Collection<Class<? extends ThingHandlerService>> getServices() {
196 return Set.of(EnergiDataServiceActions.class);
200 public void channelLinked(ChannelUID channelUID) {
201 super.channelLinked(channelUID);
203 if (!"DK1".equals(config.priceArea) && !"DK2".equals(config.priceArea)
204 && (CHANNEL_CO2_EMISSION_PROGNOSIS.equals(channelUID.getId())
205 || CHANNEL_CO2_EMISSION_REALTIME.contains(channelUID.getId()))) {
206 logger.warn("Item linked to channel '{}', but price area {} is not supported for this channel",
207 channelUID.getId(), config.priceArea);
212 public void channelUnlinked(ChannelUID channelUID) {
213 super.channelUnlinked(channelUID);
215 if (CHANNEL_CO2_EMISSION_PROGNOSIS.equals(channelUID.getId()) && !isLinked(CHANNEL_CO2_EMISSION_PROGNOSIS)) {
216 logger.debug("No more items linked to channel '{}', stopping emission prognosis refresh job",
218 ScheduledFuture<?> refreshEmissionPrognosisFuture = this.refreshEmissionPrognosisFuture;
219 if (refreshEmissionPrognosisFuture != null) {
220 refreshEmissionPrognosisFuture.cancel(true);
221 this.refreshEmissionPrognosisFuture = null;
223 } else if (CHANNEL_CO2_EMISSION_REALTIME.contains(channelUID.getId())
224 && !isLinked(CHANNEL_CO2_EMISSION_REALTIME)) {
225 logger.debug("No more items linked to channel '{}', stopping realtime emission refresh job",
227 ScheduledFuture<?> refreshEmissionRealtimeFuture = this.refreshEmissionRealtimeFuture;
228 if (refreshEmissionRealtimeFuture != null) {
229 refreshEmissionRealtimeFuture.cancel(true);
230 this.refreshEmissionRealtimeFuture = null;
235 private void refreshElectricityPrices() {
236 RetryStrategy retryPolicy;
238 if (isLinked(CHANNEL_SPOT_PRICE)) {
239 downloadSpotPrices();
242 for (DatahubTariff datahubTariff : DatahubTariff.values()) {
243 if (isLinked(datahubTariff.getChannelId())) {
244 downloadTariffs(datahubTariff);
248 updateStatus(ThingStatus.ONLINE);
252 if (isLinked(CHANNEL_SPOT_PRICE)) {
253 if (cacheManager.getNumberOfFutureSpotPrices() < 13) {
254 logger.warn("Spot prices are not yet available, retry scheduled (see details in Thing properties)");
255 retryPolicy = RetryPolicyFactory.whenExpectedSpotPriceDataMissing(DAILY_REFRESH_TIME_CET,
258 retryPolicy = RetryPolicyFactory.atFixedTime(DAILY_REFRESH_TIME_CET, NORD_POOL_TIMEZONE);
261 retryPolicy = RetryPolicyFactory.atFixedTime(LocalTime.MIDNIGHT, timeZoneProvider.getTimeZone());
263 } catch (DataServiceException e) {
264 if (e.getHttpStatus() != 0) {
265 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
266 HttpStatus.getCode(e.getHttpStatus()).getMessage());
268 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
270 if (e.getCause() != null) {
271 logger.debug("Error retrieving prices", e);
273 retryPolicy = RetryPolicyFactory.fromThrowable(e);
274 } catch (InterruptedException e) {
275 logger.debug("Refresh job interrupted");
276 Thread.currentThread().interrupt();
280 reschedulePriceRefreshJob(retryPolicy);
283 private void downloadSpotPrices() throws InterruptedException, DataServiceException {
284 if (cacheManager.areSpotPricesFullyCached()) {
285 logger.debug("Cached spot prices still valid, skipping download.");
288 DateQueryParameter start;
289 if (cacheManager.areHistoricSpotPricesCached()) {
290 start = DateQueryParameter.of(DateQueryParameterType.UTC_NOW);
292 start = DateQueryParameter.of(DateQueryParameterType.UTC_NOW,
293 Duration.ofHours(-CacheManager.NUMBER_OF_HISTORIC_HOURS));
295 Map<String, String> properties = editProperties();
296 ElspotpriceRecord[] spotPriceRecords = apiController.getSpotPrices(config.priceArea, config.getCurrency(),
298 cacheManager.putSpotPrices(spotPriceRecords, config.getCurrency());
299 updateProperties(properties);
302 private void downloadTariffs(DatahubTariff datahubTariff) throws InterruptedException, DataServiceException {
303 GlobalLocationNumber globalLocationNumber = switch (datahubTariff) {
304 case GRID_TARIFF -> config.getGridCompanyGLN();
305 default -> config.getEnerginetGLN();
307 if (globalLocationNumber.isEmpty()) {
310 if (cacheManager.areTariffsValidTomorrow(datahubTariff)) {
311 logger.debug("Cached tariffs of type {} still valid, skipping download.", datahubTariff);
312 cacheManager.updateTariffs(datahubTariff);
314 DatahubTariffFilter filter = switch (datahubTariff) {
315 case GRID_TARIFF -> getGridTariffFilter();
316 case SYSTEM_TARIFF -> DatahubTariffFilterFactory.getSystemTariff();
317 case TRANSMISSION_GRID_TARIFF -> DatahubTariffFilterFactory.getTransmissionGridTariff();
318 case ELECTRICITY_TAX -> DatahubTariffFilterFactory.getElectricityTax();
319 case REDUCED_ELECTRICITY_TAX -> DatahubTariffFilterFactory.getReducedElectricityTax();
321 cacheManager.putTariffs(datahubTariff, downloadPriceLists(globalLocationNumber, filter));
325 private Collection<DatahubPricelistRecord> downloadPriceLists(GlobalLocationNumber globalLocationNumber,
326 DatahubTariffFilter filter) throws InterruptedException, DataServiceException {
327 Map<String, String> properties = editProperties();
328 Collection<DatahubPricelistRecord> records = apiController.getDatahubPriceLists(globalLocationNumber,
329 ChargeType.Tariff, filter, properties);
330 updateProperties(properties);
335 private DatahubTariffFilter getGridTariffFilter() {
336 Channel channel = getThing().getChannel(CHANNEL_GRID_TARIFF);
337 if (channel == null) {
338 return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
341 DatahubPriceConfiguration datahubPriceConfiguration = channel.getConfiguration()
342 .as(DatahubPriceConfiguration.class);
344 if (!datahubPriceConfiguration.hasAnyFilterOverrides()) {
345 return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
348 DateQueryParameter start = datahubPriceConfiguration.getStart();
350 logger.warn("Invalid channel configuration parameter 'start' or 'offset': {} (offset: {})",
351 datahubPriceConfiguration.start, datahubPriceConfiguration.offset);
352 return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
355 Set<ChargeTypeCode> chargeTypeCodes = datahubPriceConfiguration.getChargeTypeCodes();
356 Set<String> notes = datahubPriceConfiguration.getNotes();
357 DatahubTariffFilter filter;
358 if (!chargeTypeCodes.isEmpty() || !notes.isEmpty()) {
359 // Completely override filter.
360 filter = new DatahubTariffFilter(chargeTypeCodes, notes, start);
362 // Only override start date in pre-configured filter.
363 filter = new DatahubTariffFilter(DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN),
367 return new DatahubTariffFilter(filter, DateQueryParameter.of(filter.getDateQueryParameter(),
368 Duration.ofHours(-CacheManager.NUMBER_OF_HISTORIC_HOURS)));
371 private void refreshCo2EmissionPrognosis() {
373 updateCo2Emissions(Dataset.CO2EmissionPrognosis, CHANNEL_CO2_EMISSION_PROGNOSIS,
374 DateQueryParameter.of(DateQueryParameterType.UTC_NOW, Duration.ofMinutes(-5)));
375 updateStatus(ThingStatus.ONLINE);
376 } catch (DataServiceException e) {
377 if (e.getHttpStatus() != 0) {
378 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
379 HttpStatus.getCode(e.getHttpStatus()).getMessage());
381 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
383 if (e.getCause() != null) {
384 logger.debug("Error retrieving CO2 emission prognosis", e);
386 } catch (InterruptedException e) {
387 logger.debug("Emission prognosis refresh job interrupted");
388 Thread.currentThread().interrupt();
393 private void refreshCo2EmissionRealtime() {
395 updateCo2Emissions(Dataset.CO2Emission, CHANNEL_CO2_EMISSION_REALTIME,
396 DateQueryParameter.of(DateQueryParameterType.UTC_NOW,
397 realtimeEmissionsFetchedFirstTime ? Duration.ofMinutes(-5) : Duration.ofHours(-24)));
398 realtimeEmissionsFetchedFirstTime = true;
399 updateStatus(ThingStatus.ONLINE);
400 } catch (DataServiceException e) {
401 if (e.getHttpStatus() != 0) {
402 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
403 HttpStatus.getCode(e.getHttpStatus()).getMessage());
405 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
407 if (e.getCause() != null) {
408 logger.debug("Error retrieving CO2 realtime emissions", e);
410 } catch (InterruptedException e) {
411 logger.debug("Emission realtime refresh job interrupted");
412 Thread.currentThread().interrupt();
417 private void updateCo2Emissions(Dataset dataset, String channelId, DateQueryParameter dateQueryParameter)
418 throws InterruptedException, DataServiceException {
419 if (!"DK1".equals(config.priceArea) && !"DK2".equals(config.priceArea)) {
420 // Dataset is only for Denmark.
423 Map<String, String> properties = editProperties();
424 CO2EmissionRecord[] emissionRecords = apiController.getCo2Emissions(dataset, config.priceArea,
425 dateQueryParameter, properties);
426 updateProperties(properties);
428 TimeSeries timeSeries = new TimeSeries(REPLACE);
429 Instant now = Instant.now();
431 if (dataset == Dataset.CO2Emission && emissionRecords.length > 0) {
432 // Records are sorted descending, first record is current.
433 updateState(channelId, new QuantityType<>(emissionRecords[0].emission(), Units.GRAM_PER_KILOWATT_HOUR));
436 for (CO2EmissionRecord emissionRecord : emissionRecords) {
437 State state = new QuantityType<>(emissionRecord.emission(), Units.GRAM_PER_KILOWATT_HOUR);
438 timeSeries.add(emissionRecord.start(), state);
440 if (dataset == Dataset.CO2EmissionPrognosis && now.compareTo(emissionRecord.start()) >= 0
441 && now.compareTo(emissionRecord.end()) < 0) {
442 updateState(channelId, state);
445 sendTimeSeries(channelId, timeSeries);
448 private void updatePrices() {
449 cacheManager.cleanup();
451 updateCurrentSpotPrice();
452 Arrays.stream(DatahubTariff.values())
453 .forEach(tariff -> updateCurrentTariff(tariff.getChannelId(), cacheManager.getTariff(tariff)));
455 reschedulePriceUpdateJob();
458 private void updateCurrentSpotPrice() {
459 if (!isLinked(CHANNEL_SPOT_PRICE)) {
462 BigDecimal spotPrice = cacheManager.getSpotPrice();
463 updatePriceState(CHANNEL_SPOT_PRICE, spotPrice, config.getCurrency());
466 private void updateCurrentTariff(String channelId, @Nullable BigDecimal tariff) {
467 if (!isLinked(channelId)) {
470 updatePriceState(channelId, tariff, CURRENCY_DKK);
473 private void updatePriceState(String channelID, @Nullable BigDecimal price, Currency currency) {
474 updateState(channelID, price != null ? getEnergyPrice(price, currency) : UnDefType.UNDEF);
477 private State getEnergyPrice(BigDecimal price, Currency currency) {
478 String currencyCode = currency.getCurrencyCode();
479 Unit<?> unit = CurrencyUnits.getInstance().getUnit(currencyCode);
481 logger.trace("Currency {} is unknown, falling back to DecimalType", currency.getCurrencyCode());
482 return new DecimalType(price);
485 return new QuantityType<>(price + " " + currencyCode + "/kWh");
486 } catch (IllegalArgumentException e) {
487 logger.debug("Unable to create QuantityType, falling back to DecimalType", e);
488 return new DecimalType(price);
492 private void updateTimeSeries() {
493 TimeSeries spotPriceTimeSeries = new TimeSeries(REPLACE);
494 Map<DatahubTariff, TimeSeries> datahubTimeSeriesMap = new HashMap<>();
495 Map<DatahubTariff, BigDecimal> datahubPreviousTariff = new HashMap<>();
496 for (DatahubTariff datahubTariff : DatahubTariff.values()) {
497 datahubTimeSeriesMap.put(datahubTariff, new TimeSeries(REPLACE));
500 Map<Instant, BigDecimal> spotPriceMap = cacheManager.getSpotPrices();
501 List<Entry<Instant, BigDecimal>> spotPrices = spotPriceMap.entrySet().stream()
502 .sorted(Map.Entry.comparingByKey()).toList();
503 for (Entry<Instant, BigDecimal> spotPrice : spotPrices) {
504 Instant hourStart = spotPrice.getKey();
505 if (isLinked(CHANNEL_SPOT_PRICE)) {
506 spotPriceTimeSeries.add(hourStart, getEnergyPrice(spotPrice.getValue(), config.getCurrency()));
508 for (Map.Entry<DatahubTariff, TimeSeries> entry : datahubTimeSeriesMap.entrySet()) {
509 DatahubTariff datahubTariff = entry.getKey();
510 String channelId = datahubTariff.getChannelId();
511 if (!isLinked(channelId)) {
514 BigDecimal tariff = cacheManager.getTariff(datahubTariff, hourStart);
515 if (tariff != null) {
516 BigDecimal previousTariff = datahubPreviousTariff.get(datahubTariff);
517 if (previousTariff != null && tariff.equals(previousTariff)) {
518 // Skip redundant states.
521 TimeSeries timeSeries = entry.getValue();
522 timeSeries.add(hourStart, getEnergyPrice(tariff, CURRENCY_DKK));
523 datahubPreviousTariff.put(datahubTariff, tariff);
527 if (spotPriceTimeSeries.size() > 0) {
528 sendTimeSeries(CHANNEL_SPOT_PRICE, spotPriceTimeSeries);
530 for (Map.Entry<DatahubTariff, TimeSeries> entry : datahubTimeSeriesMap.entrySet()) {
531 DatahubTariff datahubTariff = entry.getKey();
532 String channelId = datahubTariff.getChannelId();
533 if (!isLinked(channelId)) {
536 TimeSeries timeSeries = entry.getValue();
537 if (timeSeries.size() > 0) {
538 sendTimeSeries(channelId, timeSeries);
544 * Get the configured {@link Currency} for spot prices.
546 * @return Spot price currency
548 public Currency getCurrency() {
549 return config.getCurrency();
553 * Get cached spot prices or try once to download them if not cached
554 * (usually if no items are linked).
556 * @return Map of future spot prices
558 public Map<Instant, BigDecimal> getSpotPrices() {
560 downloadSpotPrices();
561 } catch (DataServiceException e) {
562 if (logger.isDebugEnabled()) {
563 logger.warn("Error retrieving spot prices", e);
565 logger.warn("Error retrieving spot prices: {}", e.getMessage());
567 } catch (InterruptedException e) {
568 Thread.currentThread().interrupt();
571 return cacheManager.getSpotPrices();
575 * Return cached tariffs or try once to download them if not cached
576 * (usually if no items are linked).
578 * @return Map of future tariffs
580 public Map<Instant, BigDecimal> getTariffs(DatahubTariff datahubTariff) {
582 downloadTariffs(datahubTariff);
583 } catch (DataServiceException e) {
584 if (logger.isDebugEnabled()) {
585 logger.warn("Error retrieving tariffs", e);
587 logger.warn("Error retrieving tariffs of type {}: {}", datahubTariff, e.getMessage());
589 } catch (InterruptedException e) {
590 Thread.currentThread().interrupt();
593 return cacheManager.getTariffs(datahubTariff);
597 * Return whether reduced electricity tax is set in configuration.
599 * @return true if reduced electricity tax applies
601 public boolean isReducedElectricityTax() {
602 return config.reducedElectricityTax;
605 private void reschedulePriceUpdateJob() {
606 ScheduledFuture<?> priceUpdateJob = this.priceUpdateFuture;
607 if (priceUpdateJob != null) {
608 // Do not interrupt ourselves.
609 priceUpdateJob.cancel(false);
610 this.priceUpdateFuture = null;
613 Instant now = Instant.now();
614 long millisUntilNextClockHour = Duration
615 .between(now, now.plus(1, ChronoUnit.HOURS).truncatedTo(ChronoUnit.HOURS)).toMillis() + 1;
616 this.priceUpdateFuture = scheduler.schedule(this::updatePrices, millisUntilNextClockHour,
617 TimeUnit.MILLISECONDS);
618 logger.debug("Price update job rescheduled in {} milliseconds", millisUntilNextClockHour);
621 private void reschedulePriceRefreshJob(RetryStrategy retryPolicy) {
622 // Preserve state of previous retry policy when configuration is the same.
623 if (!retryPolicy.equals(this.retryPolicy)) {
624 this.retryPolicy = retryPolicy;
627 ScheduledFuture<?> refreshJob = this.refreshPriceFuture;
629 long secondsUntilNextRefresh = this.retryPolicy.getDuration().getSeconds();
630 Instant timeOfNextRefresh = Instant.now().plusSeconds(secondsUntilNextRefresh);
631 this.refreshPriceFuture = scheduler.schedule(this::refreshElectricityPrices, secondsUntilNextRefresh,
633 logger.debug("Price refresh job rescheduled in {} seconds: {}", secondsUntilNextRefresh, timeOfNextRefresh);
634 DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PROPERTY_DATETIME_FORMAT);
635 updateProperty(PROPERTY_NEXT_CALL, LocalDateTime.ofInstant(timeOfNextRefresh, timeZoneProvider.getTimeZone())
636 .truncatedTo(ChronoUnit.SECONDS).format(formatter));
638 if (refreshJob != null) {
639 refreshJob.cancel(true);
643 private void rescheduleEmissionPrognosisJob() {
644 logger.debug("Scheduling emission prognosis refresh job now and every {}", emissionPrognosisJobInterval);
646 ScheduledFuture<?> refreshEmissionPrognosisFuture = this.refreshEmissionPrognosisFuture;
647 if (refreshEmissionPrognosisFuture != null) {
648 refreshEmissionPrognosisFuture.cancel(true);
651 this.refreshEmissionPrognosisFuture = scheduler.scheduleWithFixedDelay(this::refreshCo2EmissionPrognosis, 0,
652 emissionPrognosisJobInterval.toSeconds(), TimeUnit.SECONDS);
655 private void rescheduleEmissionRealtimeJob() {
656 logger.debug("Scheduling emission realtime refresh job now and every {}", emissionRealtimeJobInterval);
658 ScheduledFuture<?> refreshEmissionFuture = this.refreshEmissionRealtimeFuture;
659 if (refreshEmissionFuture != null) {
660 refreshEmissionFuture.cancel(true);
663 this.refreshEmissionRealtimeFuture = scheduler.scheduleWithFixedDelay(this::refreshCo2EmissionRealtime, 0,
664 emissionRealtimeJobInterval.toSeconds(), TimeUnit.SECONDS);