2 * Copyright (c) 2010-2024 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 = """
60 https://public.opendatasoft.com/api/records/1.0/search/?dataset=risques-meteorologiques-copy&\
61 facet=etat_vent&facet=etat_pluie_inondation&facet=etat_orage&facet=etat_inondation&facet=etat_neige&facet=etat_canicule&\
62 facet=etat_grand_froid&facet=etat_avalanches&refine.nom_dept=%s\
65 private final Logger logger = LoggerFactory.getLogger(MeteoAlerteHandler.class);
66 private final MeteoAlertIconProvider iconProvider;
67 private final Gson gson;
69 private Optional<ScheduledFuture<?>> refreshJob = Optional.empty();
70 private String queryUrl = "";
72 public MeteoAlerteHandler(Thing thing, Gson gson, MeteoAlertIconProvider iconProvider) {
75 this.iconProvider = iconProvider;
79 public void initialize() {
80 logger.debug("Initializing Météo Alerte handler.");
82 MeteoAlerteConfiguration config = getConfigAs(MeteoAlerteConfiguration.class);
83 logger.debug("config department = {}", config.department);
84 logger.debug("config refresh = {}", config.refresh);
86 updateStatus(ThingStatus.UNKNOWN);
87 queryUrl = URL.formatted(config.department);
89 .of(scheduler.scheduleWithFixedDelay(this::updateAndPublish, 0, config.refresh, TimeUnit.MINUTES));
93 public void dispose() {
94 logger.debug("Disposing the Météo Alerte handler.");
96 refreshJob.ifPresent(job -> job.cancel(true));
97 refreshJob = Optional.empty();
101 public void handleCommand(ChannelUID channelUID, Command command) {
102 if (command instanceof RefreshType) {
107 private void updateAndPublish() {
109 if (queryUrl.isEmpty()) {
110 throw new MalformedURLException("queryUrl not initialized");
112 String response = HttpUtil.executeUrl("GET", queryUrl, TIMEOUT_MS);
113 if (response == null) {
114 throw new IOException("Empty response");
116 updateStatus(ThingStatus.ONLINE);
117 updateChannels(Objects.requireNonNull(gson.fromJson(response, ApiResponse.class)));
118 } catch (MalformedURLException e) {
119 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
120 "Querying '%s' error : %s".formatted(queryUrl, e.getMessage()));
121 } catch (IOException e) {
122 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
127 * Update the channel from the last Meteo Alerte data retrieved
129 * @param channelId the id identifying the channel to be updated
131 private void updateChannels(ApiResponse apiResponse) {
132 apiResponse.getRecords().findFirst().ifPresent(record -> record.getResponseFieldDTO().ifPresent(fields -> {
133 updateAlert(WIND, fields.getVent());
134 updateAlert(RAIN, fields.getPluieInondation());
135 updateAlert(STORM, fields.getOrage());
136 updateAlert(FLOOD, fields.getInondation());
137 updateAlert(SNOW, fields.getNeige());
138 updateAlert(HEAT, fields.getCanicule());
139 updateAlert(FREEZE, fields.getGrandFroid());
140 updateAlert(AVALANCHE, fields.getAvalanches());
141 updateAlert(WAVE, fields.getVagueSubmersion());
142 updateState(COMMENT, StringType.valueOf(fields.getVigilanceComment()));
143 fields.getDateInsert().ifPresent(date -> updateDate(OBSERVATION_TIME, date));
144 fields.getDatePrevue().ifPresent(date -> updateDate(END_TIME, date));
148 private void updateAlert(String channelId, AlertLevel value) {
149 State state = value != AlertLevel.UNKNOWN ? new DecimalType(value.ordinal()) : UnDefType.NULL;
150 if (isLinked(channelId)) {
151 updateState(channelId, state);
154 String channelIcon = channelId + "-icon";
155 if (isLinked(channelIcon)) {
156 InputStream icon = iconProvider.getIcon(channelId, state.toString());
159 State result = new RawType(icon.readAllBytes(), "image/svg+xml");
160 updateState(channelIcon, result);
161 } catch (IOException e) {
162 logger.warn("Error getting icon for channel {} and value {} : {}", channelId, value,
166 logger.warn("Null icon returned for channel {} and state {}", channelIcon, state);
171 private void updateDate(String channelId, ZonedDateTime zonedDateTime) {
172 if (isLinked(channelId)) {
173 updateState(channelId, new DateTimeType(zonedDateTime));