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.DateQueryParameter;
51 import org.openhab.binding.energidataservice.internal.api.DateQueryParameterType;
52 import org.openhab.binding.energidataservice.internal.api.GlobalLocationNumber;
53 import org.openhab.binding.energidataservice.internal.api.dto.DatahubPricelistRecord;
54 import org.openhab.binding.energidataservice.internal.api.dto.ElspotpriceRecord;
55 import org.openhab.binding.energidataservice.internal.config.DatahubPriceConfiguration;
56 import org.openhab.binding.energidataservice.internal.config.EnergiDataServiceConfiguration;
57 import org.openhab.binding.energidataservice.internal.exception.DataServiceException;
58 import org.openhab.binding.energidataservice.internal.retry.RetryPolicyFactory;
59 import org.openhab.binding.energidataservice.internal.retry.RetryStrategy;
60 import org.openhab.core.i18n.TimeZoneProvider;
61 import org.openhab.core.library.types.DecimalType;
62 import org.openhab.core.library.types.QuantityType;
63 import org.openhab.core.library.types.StringType;
64 import org.openhab.core.library.unit.CurrencyUnits;
65 import org.openhab.core.thing.Channel;
66 import org.openhab.core.thing.ChannelUID;
67 import org.openhab.core.thing.Thing;
68 import org.openhab.core.thing.ThingStatus;
69 import org.openhab.core.thing.ThingStatusDetail;
70 import org.openhab.core.thing.binding.BaseThingHandler;
71 import org.openhab.core.thing.binding.ThingHandlerService;
72 import org.openhab.core.types.Command;
73 import org.openhab.core.types.RefreshType;
74 import org.openhab.core.types.State;
75 import org.openhab.core.types.TimeSeries;
76 import org.openhab.core.types.UnDefType;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
80 import com.google.gson.Gson;
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 final Logger logger = LoggerFactory.getLogger(EnergiDataServiceHandler.class);
92 private final TimeZoneProvider timeZoneProvider;
93 private final ApiController apiController;
94 private final CacheManager cacheManager;
95 private final Gson gson = new Gson();
97 private EnergiDataServiceConfiguration config;
98 private RetryStrategy retryPolicy = RetryPolicyFactory.initial();
99 private @Nullable ScheduledFuture<?> refreshFuture;
100 private @Nullable ScheduledFuture<?> priceUpdateFuture;
102 private record Price(String hourStart, BigDecimal spotPrice, String spotPriceCurrency,
103 @Nullable BigDecimal gridTariff, @Nullable BigDecimal systemTariff,
104 @Nullable BigDecimal transmissionGridTariff, @Nullable BigDecimal electricityTax,
105 @Nullable BigDecimal reducedElectricityTax) {
108 public EnergiDataServiceHandler(Thing thing, HttpClient httpClient, TimeZoneProvider timeZoneProvider) {
110 this.timeZoneProvider = timeZoneProvider;
111 this.apiController = new ApiController(httpClient, timeZoneProvider);
112 this.cacheManager = new CacheManager();
114 // Default configuration
115 this.config = new EnergiDataServiceConfiguration();
119 public void handleCommand(ChannelUID channelUID, Command command) {
120 if (!(command instanceof RefreshType)) {
124 if (ELECTRICITY_CHANNELS.contains(channelUID.getId())) {
125 refreshElectricityPrices();
130 public void initialize() {
131 config = getConfigAs(EnergiDataServiceConfiguration.class);
133 if (config.priceArea.isBlank()) {
134 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
135 "@text/offline.conf-error.no-price-area");
138 GlobalLocationNumber gln = config.getGridCompanyGLN();
139 if (!gln.isEmpty() && !gln.isValid()) {
140 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
141 "@text/offline.conf-error.invalid-grid-company-gln");
144 gln = config.getEnerginetGLN();
145 if (!gln.isEmpty() && !gln.isValid()) {
146 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
147 "@text/offline.conf-error.invalid-energinet-gln");
151 updateStatus(ThingStatus.UNKNOWN);
153 refreshFuture = scheduler.schedule(this::refreshElectricityPrices, 0, TimeUnit.SECONDS);
157 public void dispose() {
158 ScheduledFuture<?> refreshFuture = this.refreshFuture;
159 if (refreshFuture != null) {
160 refreshFuture.cancel(true);
161 this.refreshFuture = null;
163 ScheduledFuture<?> priceUpdateFuture = this.priceUpdateFuture;
164 if (priceUpdateFuture != null) {
165 priceUpdateFuture.cancel(true);
166 this.priceUpdateFuture = null;
169 cacheManager.clear();
173 public Collection<Class<? extends ThingHandlerService>> getServices() {
174 return Set.of(EnergiDataServiceActions.class);
177 private void refreshElectricityPrices() {
178 RetryStrategy retryPolicy;
180 if (isLinked(CHANNEL_SPOT_PRICE) || isLinked(CHANNEL_HOURLY_PRICES)) {
181 downloadSpotPrices();
184 for (DatahubTariff datahubTariff : DatahubTariff.values()) {
185 if (isLinked(datahubTariff.getChannelId()) || isLinked(CHANNEL_HOURLY_PRICES)) {
186 downloadTariffs(datahubTariff);
190 updateStatus(ThingStatus.ONLINE);
194 if (isLinked(CHANNEL_SPOT_PRICE) || isLinked(CHANNEL_HOURLY_PRICES)) {
195 if (cacheManager.getNumberOfFutureSpotPrices() < 13) {
196 retryPolicy = RetryPolicyFactory.whenExpectedSpotPriceDataMissing(DAILY_REFRESH_TIME_CET,
199 retryPolicy = RetryPolicyFactory.atFixedTime(DAILY_REFRESH_TIME_CET, NORD_POOL_TIMEZONE);
202 retryPolicy = RetryPolicyFactory.atFixedTime(LocalTime.MIDNIGHT, timeZoneProvider.getTimeZone());
204 } catch (DataServiceException e) {
205 if (e.getHttpStatus() != 0) {
206 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
207 HttpStatus.getCode(e.getHttpStatus()).getMessage());
209 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
211 if (e.getCause() != null) {
212 logger.debug("Error retrieving prices", e);
214 retryPolicy = RetryPolicyFactory.fromThrowable(e);
215 } catch (InterruptedException e) {
216 logger.debug("Refresh job interrupted");
217 Thread.currentThread().interrupt();
221 rescheduleRefreshJob(retryPolicy);
224 private void downloadSpotPrices() throws InterruptedException, DataServiceException {
225 if (cacheManager.areSpotPricesFullyCached()) {
226 logger.debug("Cached spot prices still valid, skipping download.");
229 DateQueryParameter start;
230 if (cacheManager.areHistoricSpotPricesCached()) {
231 start = DateQueryParameter.of(DateQueryParameterType.UTC_NOW);
233 start = DateQueryParameter.of(DateQueryParameterType.UTC_NOW,
234 Duration.ofHours(-CacheManager.NUMBER_OF_HISTORIC_HOURS));
236 Map<String, String> properties = editProperties();
237 ElspotpriceRecord[] spotPriceRecords = apiController.getSpotPrices(config.priceArea, config.getCurrency(),
239 cacheManager.putSpotPrices(spotPriceRecords, config.getCurrency());
240 updateProperties(properties);
243 private void downloadTariffs(DatahubTariff datahubTariff) throws InterruptedException, DataServiceException {
244 GlobalLocationNumber globalLocationNumber = switch (datahubTariff) {
245 case GRID_TARIFF -> config.getGridCompanyGLN();
246 default -> config.getEnerginetGLN();
248 if (globalLocationNumber.isEmpty()) {
251 if (cacheManager.areTariffsValidTomorrow(datahubTariff)) {
252 logger.debug("Cached tariffs of type {} still valid, skipping download.", datahubTariff);
253 cacheManager.updateTariffs(datahubTariff);
255 DatahubTariffFilter filter = switch (datahubTariff) {
256 case GRID_TARIFF -> getGridTariffFilter();
257 case SYSTEM_TARIFF -> DatahubTariffFilterFactory.getSystemTariff();
258 case TRANSMISSION_GRID_TARIFF -> DatahubTariffFilterFactory.getTransmissionGridTariff();
259 case ELECTRICITY_TAX -> DatahubTariffFilterFactory.getElectricityTax();
260 case REDUCED_ELECTRICITY_TAX -> DatahubTariffFilterFactory.getReducedElectricityTax();
262 cacheManager.putTariffs(datahubTariff, downloadPriceLists(globalLocationNumber, filter));
266 private Collection<DatahubPricelistRecord> downloadPriceLists(GlobalLocationNumber globalLocationNumber,
267 DatahubTariffFilter filter) throws InterruptedException, DataServiceException {
268 Map<String, String> properties = editProperties();
269 Collection<DatahubPricelistRecord> records = apiController.getDatahubPriceLists(globalLocationNumber,
270 ChargeType.Tariff, filter, properties);
271 updateProperties(properties);
276 private DatahubTariffFilter getGridTariffFilter() {
277 Channel channel = getThing().getChannel(CHANNEL_GRID_TARIFF);
278 if (channel == null) {
279 return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
282 DatahubPriceConfiguration datahubPriceConfiguration = channel.getConfiguration()
283 .as(DatahubPriceConfiguration.class);
285 if (!datahubPriceConfiguration.hasAnyFilterOverrides()) {
286 return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
289 DateQueryParameter start = datahubPriceConfiguration.getStart();
291 logger.warn("Invalid channel configuration parameter 'start' or 'offset': {} (offset: {})",
292 datahubPriceConfiguration.start, datahubPriceConfiguration.offset);
293 return DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN);
296 Set<ChargeTypeCode> chargeTypeCodes = datahubPriceConfiguration.getChargeTypeCodes();
297 Set<String> notes = datahubPriceConfiguration.getNotes();
298 DatahubTariffFilter filter;
299 if (!chargeTypeCodes.isEmpty() || !notes.isEmpty()) {
300 // Completely override filter.
301 filter = new DatahubTariffFilter(chargeTypeCodes, notes, start);
303 // Only override start date in pre-configured filter.
304 filter = new DatahubTariffFilter(DatahubTariffFilterFactory.getGridTariffByGLN(config.gridCompanyGLN),
308 return new DatahubTariffFilter(filter, DateQueryParameter.of(filter.getDateQueryParameter(),
309 Duration.ofHours(-CacheManager.NUMBER_OF_HISTORIC_HOURS)));
312 private void updatePrices() {
313 cacheManager.cleanup();
315 updateCurrentSpotPrice();
316 Arrays.stream(DatahubTariff.values())
317 .forEach(tariff -> updateCurrentTariff(tariff.getChannelId(), cacheManager.getTariff(tariff)));
318 updateHourlyPrices();
320 reschedulePriceUpdateJob();
323 private void updateCurrentSpotPrice() {
324 if (!isLinked(CHANNEL_SPOT_PRICE)) {
327 BigDecimal spotPrice = cacheManager.getSpotPrice();
328 updatePriceState(CHANNEL_SPOT_PRICE, spotPrice, config.getCurrency());
331 private void updateCurrentTariff(String channelId, @Nullable BigDecimal tariff) {
332 if (!isLinked(channelId)) {
335 updatePriceState(channelId, tariff, CURRENCY_DKK);
338 private void updatePriceState(String channelID, @Nullable BigDecimal price, Currency currency) {
339 updateState(channelID, price != null ? getEnergyPrice(price, currency) : UnDefType.UNDEF);
342 private State getEnergyPrice(BigDecimal price, Currency currency) {
343 Unit<?> unit = CurrencyUnits.getInstance().getUnit(currency.getCurrencyCode());
345 logger.trace("Currency {} is unknown, falling back to DecimalType", currency.getCurrencyCode());
346 return new DecimalType(price);
349 String currencyUnit = unit.getSymbol();
350 if (currencyUnit == null) {
351 currencyUnit = unit.getName();
353 return new QuantityType<>(price + " " + currencyUnit + "/kWh");
354 } catch (IllegalArgumentException e) {
355 logger.debug("Unable to create QuantityType, falling back to DecimalType", e);
356 return new DecimalType(price);
360 private void updateHourlyPrices() {
361 if (!isLinked(CHANNEL_HOURLY_PRICES)) {
364 Map<Instant, BigDecimal> spotPriceMap = cacheManager.getSpotPrices();
365 Price[] targetPrices = new Price[spotPriceMap.size()];
366 List<Entry<Instant, BigDecimal>> sourcePrices = spotPriceMap.entrySet().stream()
367 .sorted(Map.Entry.comparingByKey()).toList();
370 for (Entry<Instant, BigDecimal> sourcePrice : sourcePrices) {
371 Instant hourStart = sourcePrice.getKey();
372 BigDecimal gridTariff = cacheManager.getTariff(DatahubTariff.GRID_TARIFF, hourStart);
373 BigDecimal systemTariff = cacheManager.getTariff(DatahubTariff.SYSTEM_TARIFF, hourStart);
374 BigDecimal transmissionGridTariff = cacheManager.getTariff(DatahubTariff.TRANSMISSION_GRID_TARIFF,
376 BigDecimal electricityTax = cacheManager.getTariff(DatahubTariff.ELECTRICITY_TAX, hourStart);
377 BigDecimal reducedElectricityTax = cacheManager.getTariff(DatahubTariff.REDUCED_ELECTRICITY_TAX, hourStart);
378 targetPrices[i++] = new Price(hourStart.toString(), sourcePrice.getValue(), config.currencyCode, gridTariff,
379 systemTariff, electricityTax, reducedElectricityTax, transmissionGridTariff);
381 updateState(CHANNEL_HOURLY_PRICES, new StringType(gson.toJson(targetPrices)));
384 private void updateTimeSeries() {
385 TimeSeries spotPriceTimeSeries = new TimeSeries(REPLACE);
386 Map<DatahubTariff, TimeSeries> datahubTimeSeriesMap = new HashMap<>();
387 for (DatahubTariff datahubTariff : DatahubTariff.values()) {
388 datahubTimeSeriesMap.put(datahubTariff, new TimeSeries(REPLACE));
391 Map<Instant, BigDecimal> spotPriceMap = cacheManager.getSpotPrices();
392 List<Entry<Instant, BigDecimal>> spotPrices = spotPriceMap.entrySet().stream()
393 .sorted(Map.Entry.comparingByKey()).toList();
394 for (Entry<Instant, BigDecimal> spotPrice : spotPrices) {
395 Instant hourStart = spotPrice.getKey();
396 if (isLinked(CHANNEL_SPOT_PRICE)) {
397 spotPriceTimeSeries.add(hourStart, getEnergyPrice(spotPrice.getValue(), config.getCurrency()));
399 for (Map.Entry<DatahubTariff, TimeSeries> entry : datahubTimeSeriesMap.entrySet()) {
400 DatahubTariff datahubTariff = entry.getKey();
401 String channelId = datahubTariff.getChannelId();
402 if (!isLinked(channelId)) {
405 BigDecimal tariff = cacheManager.getTariff(datahubTariff, hourStart);
406 if (tariff != null) {
407 TimeSeries timeSeries = entry.getValue();
408 timeSeries.add(hourStart, getEnergyPrice(tariff, CURRENCY_DKK));
412 if (spotPriceTimeSeries.size() > 0) {
413 sendTimeSeries(CHANNEL_SPOT_PRICE, spotPriceTimeSeries);
415 for (Map.Entry<DatahubTariff, TimeSeries> entry : datahubTimeSeriesMap.entrySet()) {
416 DatahubTariff datahubTariff = entry.getKey();
417 String channelId = datahubTariff.getChannelId();
418 if (!isLinked(channelId)) {
421 TimeSeries timeSeries = entry.getValue();
422 if (timeSeries.size() > 0) {
423 sendTimeSeries(channelId, timeSeries);
429 * Get the configured {@link Currency} for spot prices.
431 * @return Spot price currency
433 public Currency getCurrency() {
434 return config.getCurrency();
438 * Get cached spot prices or try once to download them if not cached
439 * (usually if no items are linked).
441 * @return Map of future spot prices
443 public Map<Instant, BigDecimal> getSpotPrices() {
445 downloadSpotPrices();
446 } catch (DataServiceException e) {
447 if (logger.isDebugEnabled()) {
448 logger.warn("Error retrieving spot prices", e);
450 logger.warn("Error retrieving spot prices: {}", e.getMessage());
452 } catch (InterruptedException e) {
453 Thread.currentThread().interrupt();
456 return cacheManager.getSpotPrices();
460 * Return cached tariffs or try once to download them if not cached
461 * (usually if no items are linked).
463 * @return Map of future tariffs
465 public Map<Instant, BigDecimal> getTariffs(DatahubTariff datahubTariff) {
467 downloadTariffs(datahubTariff);
468 } catch (DataServiceException e) {
469 if (logger.isDebugEnabled()) {
470 logger.warn("Error retrieving tariffs", e);
472 logger.warn("Error retrieving tariffs of type {}: {}", datahubTariff, e.getMessage());
474 } catch (InterruptedException e) {
475 Thread.currentThread().interrupt();
478 return cacheManager.getTariffs(datahubTariff);
482 * Return whether reduced electricity tax is set in configuration.
484 * @return true if reduced electricity tax applies
486 public boolean isReducedElectricityTax() {
487 return config.reducedElectricityTax;
490 private void reschedulePriceUpdateJob() {
491 ScheduledFuture<?> priceUpdateJob = this.priceUpdateFuture;
492 if (priceUpdateJob != null) {
493 // Do not interrupt ourselves.
494 priceUpdateJob.cancel(false);
495 this.priceUpdateFuture = null;
498 Instant now = Instant.now();
499 long millisUntilNextClockHour = Duration
500 .between(now, now.plus(1, ChronoUnit.HOURS).truncatedTo(ChronoUnit.HOURS)).toMillis() + 1;
501 this.priceUpdateFuture = scheduler.schedule(this::updatePrices, millisUntilNextClockHour,
502 TimeUnit.MILLISECONDS);
503 logger.debug("Price update job rescheduled in {} milliseconds", millisUntilNextClockHour);
506 private void rescheduleRefreshJob(RetryStrategy retryPolicy) {
507 // Preserve state of previous retry policy when configuration is the same.
508 if (!retryPolicy.equals(this.retryPolicy)) {
509 this.retryPolicy = retryPolicy;
512 ScheduledFuture<?> refreshJob = this.refreshFuture;
514 long secondsUntilNextRefresh = this.retryPolicy.getDuration().getSeconds();
515 Instant timeOfNextRefresh = Instant.now().plusSeconds(secondsUntilNextRefresh);
516 this.refreshFuture = scheduler.schedule(this::refreshElectricityPrices, secondsUntilNextRefresh,
518 logger.debug("Refresh job rescheduled in {} seconds: {}", secondsUntilNextRefresh, timeOfNextRefresh);
519 DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PROPERTY_DATETIME_FORMAT);
520 updateProperty(PROPERTY_NEXT_CALL, LocalDateTime.ofInstant(timeOfNextRefresh, timeZoneProvider.getTimeZone())
521 .truncatedTo(ChronoUnit.SECONDS).format(formatter));
523 if (refreshJob != null) {
524 refreshJob.cancel(true);