]> git.basschouten.com Git - openhab-addons.git/blob
03cd2dcc4c284a251978394d39068421cfd08d64
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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         if (pollingJob != null) {
113             pollingJob.cancel(true);
114             pollingJob = null;
115         }
116     }
117
118     private synchronized void updateData() {
119         try {
120             logger.debug("Update windmill data '{}'", getThing().getUID());
121
122             final MillConfig config = millConfig;
123             final String rawMillData = windcentraleCache.getValue();
124
125             if (config == null || rawMillData == null) {
126                 return;
127             }
128             logger.trace("Retrieved updated mill data: {}", rawMillData);
129             final JsonElement jsonElement = JsonParser.parseString(rawMillData);
130
131             if (!(jsonElement instanceof JsonObject)) {
132                 throw new JsonParseException("Could not parse windmill json data");
133             }
134             final JsonObject millData = (JsonObject) jsonElement;
135
136             updateState(CHANNEL_WIND_SPEED, new DecimalType(millData.get(CHANNEL_WIND_SPEED).getAsString()));
137             updateState(CHANNEL_WIND_DIRECTION, new StringType(millData.get(CHANNEL_WIND_DIRECTION).getAsString()));
138             updateState(CHANNEL_POWER_TOTAL,
139                     new QuantityType<>(millData.get(CHANNEL_POWER_TOTAL).getAsBigDecimal(), KILO(Units.WATT)));
140             updateState(CHANNEL_POWER_PER_WD,
141                     new QuantityType<>(
142                             millData.get(CHANNEL_POWER_PER_WD).getAsBigDecimal().multiply(new BigDecimal(config.wd)),
143                             Units.WATT));
144             updateState(CHANNEL_POWER_RELATIVE,
145                     new QuantityType<>(millData.get(CHANNEL_POWER_RELATIVE).getAsBigDecimal(), Units.PERCENT));
146             updateState(CHANNEL_ENERGY,
147                     new QuantityType<>(millData.get(CHANNEL_ENERGY).getAsBigDecimal(), Units.KILOWATT_HOUR));
148             updateState(CHANNEL_ENERGY_FC,
149                     new QuantityType<>(millData.get(CHANNEL_ENERGY_FC).getAsBigDecimal(), Units.KILOWATT_HOUR));
150             updateState(CHANNEL_RUNTIME,
151                     new QuantityType<>(millData.get(HOURS_RUN_THIS_YEAR).getAsBigDecimal(), Units.HOUR));
152             updateState(CHANNEL_RUNTIME_PER,
153                     new QuantityType<>(millData.get(CHANNEL_RUNTIME_PER).getAsBigDecimal(), Units.PERCENT));
154             updateState(CHANNEL_LAST_UPDATE, new DateTimeType(millData.get(CHANNEL_LAST_UPDATE).getAsString()));
155
156             if (!getThing().getStatus().equals(ThingStatus.ONLINE)) {
157                 updateStatus(ThingStatus.ONLINE);
158             }
159         } catch (final RuntimeException e) {
160             logger.debug("Failed to process windmill data", e);
161             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
162                     "Failed to process mill data");
163         }
164     }
165 }