|
| 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.frenchgovtenergydata.internal.handler; |
| 14 | + |
| 15 | +import static org.openhab.binding.frenchgovtenergydata.internal.FrenchGovtEnergyDataBindingConstants.*; |
| 16 | + |
| 17 | +import java.io.IOException; |
| 18 | +import java.math.BigDecimal; |
| 19 | +import java.time.ZonedDateTime; |
| 20 | +import java.time.temporal.ChronoUnit; |
| 21 | +import java.util.ArrayList; |
| 22 | +import java.util.Arrays; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Optional; |
| 25 | +import java.util.concurrent.ScheduledFuture; |
| 26 | +import java.util.concurrent.TimeUnit; |
| 27 | +import java.util.stream.Collectors; |
| 28 | +import java.util.stream.Stream; |
| 29 | + |
| 30 | +import javax.ws.rs.HttpMethod; |
| 31 | + |
| 32 | +import org.eclipse.jdt.annotation.NonNullByDefault; |
| 33 | +import org.eclipse.jdt.annotation.Nullable; |
| 34 | +import org.openhab.binding.frenchgovtenergydata.internal.dto.Tariff; |
| 35 | +import org.openhab.core.io.net.http.HttpUtil; |
| 36 | +import org.openhab.core.library.types.DateTimeType; |
| 37 | +import org.openhab.core.library.types.QuantityType; |
| 38 | +import org.openhab.core.library.unit.CurrencyUnits; |
| 39 | +import org.openhab.core.thing.ChannelUID; |
| 40 | +import org.openhab.core.thing.Thing; |
| 41 | +import org.openhab.core.thing.ThingStatus; |
| 42 | +import org.openhab.core.thing.ThingStatusDetail; |
| 43 | +import org.openhab.core.thing.ThingUID; |
| 44 | +import org.openhab.core.thing.binding.BaseThingHandler; |
| 45 | +import org.openhab.core.types.Command; |
| 46 | +import org.openhab.core.types.RefreshType; |
| 47 | +import org.slf4j.Logger; |
| 48 | +import org.slf4j.LoggerFactory; |
| 49 | + |
| 50 | +/** |
| 51 | + * The {@link TariffHandler} is the base class for Tariff Things. It takes care of |
| 52 | + * update logic and update scheduling once a day. |
| 53 | + * |
| 54 | + * @author Gaël L'hopital - Initial contribution |
| 55 | + */ |
| 56 | +@NonNullByDefault |
| 57 | +public abstract class TariffHandler<T extends Tariff> extends BaseThingHandler { |
| 58 | + private static final String URL = "https://www.data.gouv.fr/fr/datasets/r/%s"; |
| 59 | + private static final int REFRESH_FIRST_HOUR_OF_DAY = 0; |
| 60 | + private static final int REFRESH_FIRST_MINUTE_OF_DAY = 1; |
| 61 | + |
| 62 | + private final Logger logger = LoggerFactory.getLogger(TariffHandler.class); |
| 63 | + private final List<T> tariffs = new ArrayList<>(); |
| 64 | + private final String url; |
| 65 | + |
| 66 | + private Optional<ScheduledFuture<?>> refreshJob = Optional.empty(); |
| 67 | + private @Nullable String fileCache = null; |
| 68 | + private int puissance = 6; |
| 69 | + |
| 70 | + public TariffHandler(Thing thing, String dataset) { |
| 71 | + super(thing); |
| 72 | + this.url = URL.formatted(dataset); |
| 73 | + } |
| 74 | + |
| 75 | + @Override |
| 76 | + public void initialize() { |
| 77 | + updateStatus(ThingStatus.UNKNOWN); |
| 78 | + Object confPower = getConfig().get("puissance"); |
| 79 | + puissance = confPower != null ? ((BigDecimal) confPower).intValue() : 6; |
| 80 | + refreshJob = Optional.of(scheduler.schedule(this::updateData, 1, TimeUnit.SECONDS)); |
| 81 | + } |
| 82 | + |
| 83 | + @Override |
| 84 | + public void dispose() { |
| 85 | + refreshJob.ifPresent(job -> job.cancel(true)); |
| 86 | + refreshJob = Optional.empty(); |
| 87 | + super.dispose(); |
| 88 | + } |
| 89 | + |
| 90 | + private @Nullable String readFile() { |
| 91 | + @Nullable |
| 92 | + String result = null; |
| 93 | + try { |
| 94 | + result = HttpUtil.executeUrl(HttpMethod.GET, url, 10000); |
| 95 | + fileCache = result; |
| 96 | + } catch (IOException e) { |
| 97 | + // Use the cache if we had an error accessing the cloud resource |
| 98 | + result = fileCache; |
| 99 | + } |
| 100 | + return result; |
| 101 | + } |
| 102 | + |
| 103 | + private void updateData() { |
| 104 | + ThingUID thingUID = getThing().getUID(); |
| 105 | + logger.debug("Updating {} channels", thingUID); |
| 106 | + |
| 107 | + @Nullable |
| 108 | + String result = readFile(); |
| 109 | + if (result != null) { |
| 110 | + List<String> lines = new ArrayList<>(Arrays.asList(result.split("\r\n"))); |
| 111 | + lines.remove(0); |
| 112 | + |
| 113 | + List<T> newTariffs = interpretLines(lines).collect(Collectors.toList()); |
| 114 | + if (!newTariffs.isEmpty()) { |
| 115 | + tariffs.clear(); |
| 116 | + tariffs.addAll(newTariffs); |
| 117 | + } |
| 118 | + |
| 119 | + tariffs.stream().filter(t -> t.puissance == puissance).filter(Tariff::isActive).findFirst().ifPresentOrElse( |
| 120 | + this::updateChannels, |
| 121 | + () -> updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "No active tariff")); |
| 122 | + |
| 123 | + ZonedDateTime now = ZonedDateTime.now(); |
| 124 | + ZonedDateTime nextUpdate = now.plusDays(1).withHour(REFRESH_FIRST_HOUR_OF_DAY) |
| 125 | + .withMinute(REFRESH_FIRST_MINUTE_OF_DAY).truncatedTo(ChronoUnit.MINUTES); |
| 126 | + long delay = ChronoUnit.MINUTES.between(now, nextUpdate); |
| 127 | + logger.debug("Scheduling next {} update in {} minutes", thingUID, delay); |
| 128 | + refreshJob = Optional.of(scheduler.schedule(this::updateData, delay, TimeUnit.MINUTES)); |
| 129 | + } else { |
| 130 | + updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, |
| 131 | + "Unable to access %s".formatted(url)); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + protected void updateChannels(T tariff) { |
| 136 | + updateStatus(ThingStatus.ONLINE); |
| 137 | + updateState(CHANNEL_TARIFF_START, new DateTimeType(tariff.dateDebut)); |
| 138 | + updateState(CHANNEL_FIXED_HT, new QuantityType<>(tariff.fixeHT, CurrencyUnits.BASE_CURRENCY)); |
| 139 | + updateState(CHANNEL_FIXED_TTC, new QuantityType<>(tariff.fixeTTC, CurrencyUnits.BASE_CURRENCY)); |
| 140 | + } |
| 141 | + |
| 142 | + protected abstract Stream<T> interpretLines(List<String> lines); |
| 143 | + |
| 144 | + @Override |
| 145 | + public void handleCommand(ChannelUID channelUID, Command command) { |
| 146 | + if (RefreshType.REFRESH.equals(command)) { |
| 147 | + updateData(); |
| 148 | + } |
| 149 | + } |
| 150 | +} |
0 commit comments