]> git.basschouten.com Git - openhab-addons.git/blob
00d20d2dc39ea8c8f846b29de9d254f1df1d6822
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.SmartHomeUnits;
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     private final JsonParser parser = new JsonParser();
64
65     private @Nullable MillConfig millConfig;
66     private @Nullable String millUrl;
67     private @Nullable ScheduledFuture<?> pollingJob;
68
69     private final ExpiringCache<@Nullable String> windcentraleCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
70         try {
71             return millUrl != null ? HttpUtil.executeUrl("GET", millUrl, 5000) : null;
72         } catch (IOException e) {
73             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
74             return null;
75         }
76     });
77
78     public WindcentraleHandler(Thing thing) {
79         super(thing);
80     }
81
82     @Override
83     public void handleCommand(ChannelUID channelUID, Command command) {
84         if (command == RefreshType.REFRESH) {
85             logger.debug("Refreshing {}", channelUID);
86             updateData();
87         } else {
88             logger.debug("This binding is a read-only binding and cannot handle commands");
89         }
90     }
91
92     @Override
93     public void initialize() {
94         logger.debug("Initializing Windcentrale handler '{}'", getThing().getUID());
95
96         final MillConfig config = getConfig().as(MillConfig.class);
97
98         millConfig = config;
99         millUrl = String.format(URL_FORMAT, config.millId);
100         pollingJob = scheduler.scheduleWithFixedDelay(this::updateData, 0, config.refreshInterval, TimeUnit.SECONDS);
101
102         logger.debug("Polling job scheduled to run every {} sec. for '{}'", config.refreshInterval,
103                 getThing().getUID());
104
105         updateProperty(Thing.PROPERTY_VENDOR, "Windcentrale");
106         updateProperty(Thing.PROPERTY_MODEL_ID, "Windmolen");
107         updateProperty(Thing.PROPERTY_SERIAL_NUMBER, Integer.toString(config.millId));
108     }
109
110     @Override
111     public void dispose() {
112         logger.debug("Disposing Windcentrale handler '{}'", getThing().getUID());
113         if (pollingJob != null) {
114             pollingJob.cancel(true);
115             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 = parser.parse(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(SmartHomeUnits.WATT)));
141             updateState(CHANNEL_POWER_PER_WD,
142                     new QuantityType<>(
143                             millData.get(CHANNEL_POWER_PER_WD).getAsBigDecimal().multiply(new BigDecimal(config.wd)),
144                             SmartHomeUnits.WATT));
145             updateState(CHANNEL_POWER_RELATIVE,
146                     new QuantityType<>(millData.get(CHANNEL_POWER_RELATIVE).getAsBigDecimal(), SmartHomeUnits.PERCENT));
147             updateState(CHANNEL_ENERGY,
148                     new QuantityType<>(millData.get(CHANNEL_ENERGY).getAsBigDecimal(), SmartHomeUnits.KILOWATT_HOUR));
149             updateState(CHANNEL_ENERGY_FC, new QuantityType<>(millData.get(CHANNEL_ENERGY_FC).getAsBigDecimal(),
150                     SmartHomeUnits.KILOWATT_HOUR));
151             updateState(CHANNEL_RUNTIME,
152                     new QuantityType<>(millData.get(HOURS_RUN_THIS_YEAR).getAsBigDecimal(), SmartHomeUnits.HOUR));
153             updateState(CHANNEL_RUNTIME_PER,
154                     new QuantityType<>(millData.get(CHANNEL_RUNTIME_PER).getAsBigDecimal(), SmartHomeUnits.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                     "Failed to process mill data");
164         }
165     }
166 }