2 * Copyright (c) 2010-2023 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.windcentrale.internal.handler;
15 import static org.openhab.binding.windcentrale.internal.WindcentraleBindingConstants.*;
16 import static org.openhab.core.library.unit.MetricPrefix.KILO;
18 import java.io.IOException;
19 import java.math.BigDecimal;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.binding.windcentrale.internal.config.MillConfig;
26 import org.openhab.core.cache.ExpiringCache;
27 import org.openhab.core.io.net.http.HttpUtil;
28 import org.openhab.core.library.types.DateTimeType;
29 import org.openhab.core.library.types.DecimalType;
30 import org.openhab.core.library.types.QuantityType;
31 import org.openhab.core.library.types.StringType;
32 import org.openhab.core.library.unit.Units;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.Thing;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingStatusDetail;
37 import org.openhab.core.thing.binding.BaseThingHandler;
38 import org.openhab.core.types.Command;
39 import org.openhab.core.types.RefreshType;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 import com.google.gson.JsonElement;
44 import com.google.gson.JsonObject;
45 import com.google.gson.JsonParseException;
46 import com.google.gson.JsonParser;
49 * The {@link WindcentraleHandler} is responsible for handling commands, which are
50 * sent to one of the channels.
52 * @author Marcel Verpaalen - Initial contribution
53 * @author Wouter Born - Add null annotations
56 public class WindcentraleHandler extends BaseThingHandler {
58 private static final String HOURS_RUN_THIS_YEAR = "hoursRunThisYear";
59 private static final String URL_FORMAT = "https://zep-api.windcentrale.nl/production/%d/live?ignoreLoadingBar=true";
60 private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(5);
62 private final Logger logger = LoggerFactory.getLogger(WindcentraleHandler.class);
64 private @Nullable MillConfig millConfig;
65 private @Nullable String millUrl;
66 private @Nullable ScheduledFuture<?> pollingJob;
68 private final ExpiringCache<@Nullable String> windcentraleCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
70 return millUrl != null ? HttpUtil.executeUrl("GET", millUrl, 5000) : null;
71 } catch (IOException e) {
72 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
77 public WindcentraleHandler(Thing thing) {
82 public void handleCommand(ChannelUID channelUID, Command command) {
83 if (command == RefreshType.REFRESH) {
84 logger.debug("Refreshing {}", channelUID);
87 logger.debug("This binding is a read-only binding and cannot handle commands");
92 public void initialize() {
93 logger.debug("Initializing Windcentrale handler '{}'", getThing().getUID());
95 final MillConfig config = getConfig().as(MillConfig.class);
98 millUrl = String.format(URL_FORMAT, config.millId);
99 pollingJob = scheduler.scheduleWithFixedDelay(this::updateData, 0, config.refreshInterval, TimeUnit.SECONDS);
101 logger.debug("Polling job scheduled to run every {} sec. for '{}'", config.refreshInterval,
102 getThing().getUID());
104 updateProperty(Thing.PROPERTY_VENDOR, "Windcentrale");
105 updateProperty(Thing.PROPERTY_MODEL_ID, "Windmolen");
106 updateProperty(Thing.PROPERTY_SERIAL_NUMBER, Integer.toString(config.millId));
110 public void dispose() {
111 logger.debug("Disposing Windcentrale handler '{}'", getThing().getUID());
112 final ScheduledFuture<?> pollingJob = this.pollingJob;
113 if (pollingJob != null) {
114 pollingJob.cancel(true);
115 this.pollingJob = null;
119 private synchronized void updateData() {
121 logger.debug("Update windmill data '{}'", getThing().getUID());
123 final MillConfig config = millConfig;
124 final String rawMillData = windcentraleCache.getValue();
126 if (config == null || rawMillData == null) {
129 logger.trace("Retrieved updated mill data: {}", rawMillData);
130 final JsonElement jsonElement = JsonParser.parseString(rawMillData);
132 if (!(jsonElement instanceof JsonObject)) {
133 throw new JsonParseException("Could not parse windmill json data");
135 final JsonObject millData = (JsonObject) jsonElement;
137 updateState(CHANNEL_WIND_SPEED, new DecimalType(millData.get(CHANNEL_WIND_SPEED).getAsString()));
138 updateState(CHANNEL_WIND_DIRECTION, new StringType(millData.get(CHANNEL_WIND_DIRECTION).getAsString()));
139 updateState(CHANNEL_POWER_TOTAL,
140 new QuantityType<>(millData.get(CHANNEL_POWER_TOTAL).getAsBigDecimal(), KILO(Units.WATT)));
141 updateState(CHANNEL_POWER_PER_WD,
143 millData.get(CHANNEL_POWER_PER_WD).getAsBigDecimal().multiply(new BigDecimal(config.wd)),
145 updateState(CHANNEL_POWER_RELATIVE,
146 new QuantityType<>(millData.get(CHANNEL_POWER_RELATIVE).getAsBigDecimal(), Units.PERCENT));
147 updateState(CHANNEL_ENERGY,
148 new QuantityType<>(millData.get(CHANNEL_ENERGY).getAsBigDecimal(), Units.KILOWATT_HOUR));
149 updateState(CHANNEL_ENERGY_FC,
150 new QuantityType<>(millData.get(CHANNEL_ENERGY_FC).getAsBigDecimal(), Units.KILOWATT_HOUR));
151 updateState(CHANNEL_RUNTIME,
152 new QuantityType<>(millData.get(HOURS_RUN_THIS_YEAR).getAsBigDecimal(), Units.HOUR));
153 updateState(CHANNEL_RUNTIME_PER,
154 new QuantityType<>(millData.get(CHANNEL_RUNTIME_PER).getAsBigDecimal(), Units.PERCENT));
155 updateState(CHANNEL_LAST_UPDATE, new DateTimeType(millData.get(CHANNEL_LAST_UPDATE).getAsString()));
157 if (!getThing().getStatus().equals(ThingStatus.ONLINE)) {
158 updateStatus(ThingStatus.ONLINE);
160 } catch (final RuntimeException e) {
161 logger.debug("Failed to process windmill data", e);
162 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
163 "@text/offline.mill-data-error");