]> git.basschouten.com Git - openhab-addons.git/blob
da31c3136d3308bc42864d7725e25d136a019de5
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.windcentrale.internal.handler;
14
15 import static org.openhab.binding.windcentrale.internal.WindcentraleBindingConstants.*;
16 import static org.openhab.core.library.unit.MetricPrefix.KILO;
17
18 import java.io.IOException;
19 import java.math.BigDecimal;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22
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;
42
43 import com.google.gson.JsonElement;
44 import com.google.gson.JsonObject;
45 import com.google.gson.JsonParseException;
46 import com.google.gson.JsonParser;
47
48 /**
49  * The {@link WindcentraleHandler} is responsible for handling commands, which are
50  * sent to one of the channels.
51  *
52  * @author Marcel Verpaalen - Initial contribution
53  * @author Wouter Born - Add null annotations
54  */
55 @NonNullByDefault
56 public class WindcentraleHandler extends BaseThingHandler {
57
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);
61
62     private final Logger logger = LoggerFactory.getLogger(WindcentraleHandler.class);
63
64     private @Nullable MillConfig millConfig;
65     private @Nullable String millUrl;
66     private @Nullable ScheduledFuture<?> pollingJob;
67
68     private final ExpiringCache<@Nullable String> windcentraleCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
69         try {
70             return millUrl != null ? HttpUtil.executeUrl("GET", millUrl, 5000) : null;
71         } catch (IOException e) {
72             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
73             return null;
74         }
75     });
76
77     public WindcentraleHandler(Thing thing) {
78         super(thing);
79     }
80
81     @Override
82     public void handleCommand(ChannelUID channelUID, Command command) {
83         if (command == RefreshType.REFRESH) {
84             logger.debug("Refreshing {}", channelUID);
85             updateData();
86         } else {
87             logger.debug("This binding is a read-only binding and cannot handle commands");
88         }
89     }
90
91     @Override
92     public void initialize() {
93         logger.debug("Initializing Windcentrale handler '{}'", getThing().getUID());
94
95         final MillConfig config = getConfig().as(MillConfig.class);
96
97         millConfig = config;
98         millUrl = String.format(URL_FORMAT, config.millId);
99         pollingJob = scheduler.scheduleWithFixedDelay(this::updateData, 0, config.refreshInterval, TimeUnit.SECONDS);
100
101         logger.debug("Polling job scheduled to run every {} sec. for '{}'", config.refreshInterval,
102                 getThing().getUID());
103
104         updateProperty(Thing.PROPERTY_VENDOR, "Windcentrale");
105         updateProperty(Thing.PROPERTY_MODEL_ID, "Windmolen");
106         updateProperty(Thing.PROPERTY_SERIAL_NUMBER, Integer.toString(config.millId));
107     }
108
109     @Override
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;
116         }
117     }
118
119     private synchronized void updateData() {
120         try {
121             logger.debug("Update windmill data '{}'", getThing().getUID());
122
123             final MillConfig config = millConfig;
124             final String rawMillData = windcentraleCache.getValue();
125
126             if (config == null || rawMillData == null) {
127                 return;
128             }
129             logger.trace("Retrieved updated mill data: {}", rawMillData);
130             final JsonElement jsonElement = JsonParser.parseString(rawMillData);
131
132             if (!(jsonElement instanceof JsonObject)) {
133                 throw new JsonParseException("Could not parse windmill json data");
134             }
135             final JsonObject millData = (JsonObject) jsonElement;
136
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,
142                     new QuantityType<>(
143                             millData.get(CHANNEL_POWER_PER_WD).getAsBigDecimal().multiply(new BigDecimal(config.wd)),
144                             Units.WATT));
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()));
156
157             if (!getThing().getStatus().equals(ThingStatus.ONLINE)) {
158                 updateStatus(ThingStatus.ONLINE);
159             }
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");
164         }
165     }
166 }