2 * Copyright (c) 2010-2020 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.vigicrues.internal.handler;
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;
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;
26 import javax.measure.Unit;
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;
47 import com.google.gson.Gson;
50 * The {@link VigiCruesHandler} is responsible for querying the API and
53 * @author Gaƫl L'hopital - Initial contribution
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);
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;
67 public VigiCruesHandler(Thing thing, TimeZoneProvider timeZoneProvider, Gson gson) {
69 this.timeZoneProvider = timeZoneProvider;
74 public void initialize() {
75 logger.debug("Initializing VigiCrues handler.");
77 VigiCruesConfiguration config = getConfigAs(VigiCruesConfiguration.class);
78 logger.debug("config station = {}", config.id);
79 logger.debug("config refresh = {} min", config.refresh);
81 updateStatus(ThingStatus.UNKNOWN);
82 queryUrl = URL + config.id;
83 refreshJob = scheduler.scheduleWithFixedDelay(this::updateAndPublish, 0, config.refresh, TimeUnit.MINUTES);
87 public void dispose() {
88 logger.debug("Disposing the VigiCrues handler.");
90 ScheduledFuture<?> refreshJob = this.refreshJob;
91 if (refreshJob != null) {
92 refreshJob.cancel(true);
94 this.refreshJob = null;
98 public void handleCommand(ChannelUID channelUID, Command command) {
99 if (command instanceof RefreshType) {
104 private void updateAndPublish() {
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));
116 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.DISABLED,
117 "queryUrl should never be null, but it is !");
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()));
128 private void updateQuantity(String channelId, Double value, Unit<?> unit) {
129 if (isLinked(channelId)) {
130 updateState(channelId, new QuantityType<>(value, unit));
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));