]> git.basschouten.com Git - openhab-addons.git/blob
1b6ff686a9a95959e30465c7062e8a2d24620620
[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.vigicrues.internal.handler;
14
15 import static org.openhab.binding.vigicrues.internal.VigiCruesBindingConstants.*;
16 import static org.openhab.core.library.unit.SmartHomeUnits.CUBICMETRE_PER_SECOND;
17 import static tec.uom.se.unit.Units.METRE;
18
19 import java.io.IOException;
20 import java.net.MalformedURLException;
21 import java.time.ZonedDateTime;
22 import java.util.Arrays;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25
26 import javax.measure.Unit;
27
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.vigicrues.internal.VigiCruesConfiguration;
31 import org.openhab.binding.vigicrues.internal.json.OpenDatasoftResponse;
32 import org.openhab.binding.vigicrues.internal.json.Record;
33 import org.openhab.core.i18n.TimeZoneProvider;
34 import org.openhab.core.io.net.http.HttpUtil;
35 import org.openhab.core.library.types.DateTimeType;
36 import org.openhab.core.library.types.QuantityType;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.Thing;
39 import org.openhab.core.thing.ThingStatus;
40 import org.openhab.core.thing.ThingStatusDetail;
41 import org.openhab.core.thing.binding.BaseThingHandler;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.RefreshType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import com.google.gson.Gson;
48
49 /**
50  * The {@link VigiCruesHandler} is responsible for querying the API and
51  * updating channels
52  *
53  * @author GaĆ«l L'hopital - Initial contribution
54  */
55 @NonNullByDefault
56 public class VigiCruesHandler extends BaseThingHandler {
57     private static final String URL = OPENDATASOFT_URL + "?dataset=vigicrues&sort=timestamp&q=";
58     private static final int TIMEOUT_MS = 30000;
59     private final Logger logger = LoggerFactory.getLogger(VigiCruesHandler.class);
60
61     // Time zone provider representing time zone configured in openHAB configuration
62     private final TimeZoneProvider timeZoneProvider;
63     private final Gson gson;
64     private @Nullable ScheduledFuture<?> refreshJob;
65     private @Nullable String queryUrl;
66
67     public VigiCruesHandler(Thing thing, TimeZoneProvider timeZoneProvider, Gson gson) {
68         super(thing);
69         this.timeZoneProvider = timeZoneProvider;
70         this.gson = gson;
71     }
72
73     @Override
74     public void initialize() {
75         logger.debug("Initializing VigiCrues handler.");
76
77         VigiCruesConfiguration config = getConfigAs(VigiCruesConfiguration.class);
78         logger.debug("config station = {}", config.id);
79         logger.debug("config refresh = {} min", config.refresh);
80
81         updateStatus(ThingStatus.UNKNOWN);
82         queryUrl = URL + config.id;
83         refreshJob = scheduler.scheduleWithFixedDelay(this::updateAndPublish, 0, config.refresh, TimeUnit.MINUTES);
84     }
85
86     @Override
87     public void dispose() {
88         logger.debug("Disposing the VigiCrues handler.");
89
90         ScheduledFuture<?> refreshJob = this.refreshJob;
91         if (refreshJob != null) {
92             refreshJob.cancel(true);
93         }
94         this.refreshJob = null;
95     }
96
97     @Override
98     public void handleCommand(ChannelUID channelUID, Command command) {
99         if (command instanceof RefreshType) {
100             updateAndPublish();
101         }
102     }
103
104     private void updateAndPublish() {
105         try {
106             if (queryUrl != null) {
107                 String response = HttpUtil.executeUrl("GET", queryUrl, TIMEOUT_MS);
108                 updateStatus(ThingStatus.ONLINE);
109                 OpenDatasoftResponse apiResponse = gson.fromJson(response, OpenDatasoftResponse.class);
110                 Arrays.stream(apiResponse.getRecords()).findFirst().flatMap(Record::getFields).ifPresent(field -> {
111                     field.getHeight().ifPresent(height -> updateQuantity(HEIGHT, height, METRE));
112                     field.getFlow().ifPresent(flow -> updateQuantity(FLOW, flow, CUBICMETRE_PER_SECOND));
113                     field.getTimestamp().ifPresent(date -> updateDate(OBSERVATION_TIME, date));
114                 });
115             } else {
116                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.DISABLED,
117                         "queryUrl should never be null, but it is !");
118             }
119         } catch (MalformedURLException e) {
120             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
121                     String.format("Querying '%s' raised : %s", queryUrl, e.getMessage()));
122         } catch (IOException e) {
123             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
124                     String.format("Error opening connection to VigiCrues webservice : {}", e.getMessage()));
125         }
126     }
127
128     private void updateQuantity(String channelId, Double value, Unit<?> unit) {
129         if (isLinked(channelId)) {
130             updateState(channelId, new QuantityType<>(value, unit));
131         }
132     }
133
134     public void updateDate(String channelId, ZonedDateTime zonedDateTime) {
135         if (isLinked(channelId)) {
136             ZonedDateTime localDateTime = zonedDateTime.withZoneSameInstant(timeZoneProvider.getTimeZone());
137             updateState(channelId, new DateTimeType(localDateTime));
138         }
139     }
140 }