2 * Copyright (c) 2010-2023 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.meteoalerte.internal.handler;
15 import static org.openhab.binding.meteoalerte.internal.MeteoAlerteBindingConstants.*;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.net.MalformedURLException;
20 import java.time.ZonedDateTime;
21 import java.util.Objects;
22 import java.util.Optional;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.openhab.binding.meteoalerte.internal.MeteoAlertIconProvider;
28 import org.openhab.binding.meteoalerte.internal.MeteoAlerteConfiguration;
29 import org.openhab.binding.meteoalerte.internal.json.ApiResponse;
30 import org.openhab.binding.meteoalerte.internal.json.ResponseFieldDTO.AlertLevel;
31 import org.openhab.core.io.net.http.HttpUtil;
32 import org.openhab.core.library.types.DateTimeType;
33 import org.openhab.core.library.types.DecimalType;
34 import org.openhab.core.library.types.RawType;
35 import org.openhab.core.library.types.StringType;
36 import org.openhab.core.thing.ChannelUID;
37 import org.openhab.core.thing.Thing;
38 import org.openhab.core.thing.ThingStatus;
39 import org.openhab.core.thing.ThingStatusDetail;
40 import org.openhab.core.thing.binding.BaseThingHandler;
41 import org.openhab.core.types.Command;
42 import org.openhab.core.types.RefreshType;
43 import org.openhab.core.types.State;
44 import org.openhab.core.types.UnDefType;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 import com.google.gson.Gson;
51 * The {@link MeteoAlerteHandler} is responsible for updating channels
52 * and querying the API
54 * @author Gaël L'hopital - Initial contribution
57 public class MeteoAlerteHandler extends BaseThingHandler {
58 private static final int TIMEOUT_MS = 30000;
59 private static final String URL = "https://public.opendatasoft.com/api/records/1.0/search/?dataset=risques-meteorologiques-copy&"
60 + "facet=etat_vent&facet=etat_pluie_inondation&facet=etat_orage&facet=etat_inondation&facet=etat_neige&facet=etat_canicule&"
61 + "facet=etat_grand_froid&facet=etat_avalanches&refine.nom_dept=%s";
63 private final Logger logger = LoggerFactory.getLogger(MeteoAlerteHandler.class);
64 private final MeteoAlertIconProvider iconProvider;
65 private final Gson gson;
67 private Optional<ScheduledFuture<?>> refreshJob = Optional.empty();
68 private String queryUrl = "";
70 public MeteoAlerteHandler(Thing thing, Gson gson, MeteoAlertIconProvider iconProvider) {
73 this.iconProvider = iconProvider;
77 public void initialize() {
78 logger.debug("Initializing Météo Alerte handler.");
80 MeteoAlerteConfiguration config = getConfigAs(MeteoAlerteConfiguration.class);
81 logger.debug("config department = {}", config.department);
82 logger.debug("config refresh = {}", config.refresh);
84 updateStatus(ThingStatus.UNKNOWN);
85 queryUrl = URL.formatted(config.department);
87 .of(scheduler.scheduleWithFixedDelay(this::updateAndPublish, 0, config.refresh, TimeUnit.MINUTES));
91 public void dispose() {
92 logger.debug("Disposing the Météo Alerte handler.");
94 refreshJob.ifPresent(job -> job.cancel(true));
95 refreshJob = Optional.empty();
99 public void handleCommand(ChannelUID channelUID, Command command) {
100 if (command instanceof RefreshType) {
105 private void updateAndPublish() {
107 if (queryUrl.isEmpty()) {
108 throw new MalformedURLException("queryUrl not initialized");
110 String response = HttpUtil.executeUrl("GET", queryUrl, TIMEOUT_MS);
111 if (response == null) {
112 throw new IOException("Empty response");
114 updateStatus(ThingStatus.ONLINE);
115 updateChannels(Objects.requireNonNull(gson.fromJson(response, ApiResponse.class)));
116 } catch (MalformedURLException e) {
117 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
118 "Querying '%s' error : %s".formatted(queryUrl, e.getMessage()));
119 } catch (IOException e) {
120 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
125 * Update the channel from the last Meteo Alerte data retrieved
127 * @param channelId the id identifying the channel to be updated
129 private void updateChannels(ApiResponse apiResponse) {
130 apiResponse.getRecords().findFirst().ifPresent(record -> record.getResponseFieldDTO().ifPresent(fields -> {
131 updateAlert(WIND, fields.getVent());
132 updateAlert(RAIN, fields.getPluieInondation());
133 updateAlert(STORM, fields.getOrage());
134 updateAlert(FLOOD, fields.getInondation());
135 updateAlert(SNOW, fields.getNeige());
136 updateAlert(HEAT, fields.getCanicule());
137 updateAlert(FREEZE, fields.getGrandFroid());
138 updateAlert(AVALANCHE, fields.getAvalanches());
139 updateAlert(WAVE, fields.getVagueSubmersion());
140 updateState(COMMENT, StringType.valueOf(fields.getVigilanceComment()));
141 fields.getDateInsert().ifPresent(date -> updateDate(OBSERVATION_TIME, date));
142 fields.getDatePrevue().ifPresent(date -> updateDate(END_TIME, date));
146 private void updateAlert(String channelId, AlertLevel value) {
147 State state = value != AlertLevel.UNKNOWN ? new DecimalType(value.ordinal()) : UnDefType.NULL;
148 if (isLinked(channelId)) {
149 updateState(channelId, state);
152 String channelIcon = channelId + "-icon";
153 if (isLinked(channelIcon)) {
154 InputStream icon = iconProvider.getIcon(channelId, state.toString());
157 State result = new RawType(icon.readAllBytes(), "image/svg+xml");
158 updateState(channelIcon, result);
159 } catch (IOException e) {
160 logger.warn("Error getting icon for channel {} and value {} : {}", channelId, value,
164 logger.warn("Null icon returned for channel {} and state {}", channelIcon, state);
169 private void updateDate(String channelId, ZonedDateTime zonedDateTime) {
170 if (isLinked(channelId)) {
171 updateState(channelId, new DateTimeType(zonedDateTime));