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.nio.charset.StandardCharsets;
21 import java.time.ZonedDateTime;
23 import java.util.Objects;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.meteoalerte.internal.MeteoAlerteConfiguration;
30 import org.openhab.binding.meteoalerte.internal.json.ApiResponse;
31 import org.openhab.binding.meteoalerte.internal.json.ResponseFieldDTO.AlertLevel;
32 import org.openhab.core.io.net.http.HttpUtil;
33 import org.openhab.core.library.types.DateTimeType;
34 import org.openhab.core.library.types.DecimalType;
35 import org.openhab.core.library.types.RawType;
36 import org.openhab.core.library.types.StringType;
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.openhab.core.types.State;
45 import org.openhab.core.types.UnDefType;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 import com.google.gson.Gson;
52 * The {@link MeteoAlerteHandler} is responsible for updating channels
53 * and querying the API
55 * @author Gaël L'hopital - Initial contribution
58 public class MeteoAlerteHandler extends BaseThingHandler {
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";
62 private static final int TIMEOUT_MS = 30000;
63 private static final String UNKNOWN_COLOR = "b3b3b3";
64 private static final Map<AlertLevel, String> ALERT_COLORS = Map.ofEntries(Map.entry(AlertLevel.GREEN, "00ff00"),
65 Map.entry(AlertLevel.YELLOW, "ffff00"), Map.entry(AlertLevel.ORANGE, "ff6600"),
66 Map.entry(AlertLevel.RED, "ff0000"), Map.entry(AlertLevel.UNKNOWN, UNKNOWN_COLOR));
68 private static final Map<AlertLevel, State> ALERT_LEVELS = Map.ofEntries(
69 Map.entry(AlertLevel.GREEN, DecimalType.ZERO), Map.entry(AlertLevel.YELLOW, new DecimalType(1)),
70 Map.entry(AlertLevel.ORANGE, new DecimalType(2)), Map.entry(AlertLevel.RED, new DecimalType(3)));
72 private final Logger logger = LoggerFactory.getLogger(MeteoAlerteHandler.class);
73 private final Gson gson;
74 private @Nullable ScheduledFuture<?> refreshJob;
75 private String queryUrl = "";
77 public MeteoAlerteHandler(Thing thing, Gson gson) {
83 public void initialize() {
84 logger.debug("Initializing Météo Alerte handler.");
86 MeteoAlerteConfiguration config = getConfigAs(MeteoAlerteConfiguration.class);
87 logger.debug("config department = {}", config.department);
88 logger.debug("config refresh = {}", config.refresh);
90 updateStatus(ThingStatus.UNKNOWN);
91 queryUrl = String.format(URL, config.department);
92 refreshJob = scheduler.scheduleWithFixedDelay(this::updateAndPublish, 0, config.refresh, TimeUnit.MINUTES);
96 public void dispose() {
97 logger.debug("Disposing the Météo Alerte handler.");
98 ScheduledFuture<?> localJob = refreshJob;
99 if (localJob != null) {
100 localJob.cancel(true);
106 public void handleCommand(ChannelUID channelUID, Command command) {
107 if (command instanceof RefreshType) {
112 private void updateAndPublish() {
114 if (queryUrl.isEmpty()) {
115 throw new MalformedURLException("queryUrl not initialized");
117 String response = HttpUtil.executeUrl("GET", queryUrl, TIMEOUT_MS);
118 if (response == null) {
119 throw new IOException("Empty response");
121 updateStatus(ThingStatus.ONLINE);
122 ApiResponse apiResponse = gson.fromJson(response, ApiResponse.class);
123 updateChannels(Objects.requireNonNull(apiResponse));
124 } catch (MalformedURLException e) {
125 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
126 String.format("Querying '%s' raised : %s", queryUrl, e.getMessage()));
127 } catch (IOException e) {
128 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
133 * Update the channel from the last Meteo Alerte data retrieved
135 * @param channelId the id identifying the channel to be updated
137 private void updateChannels(ApiResponse apiResponse) {
138 apiResponse.getRecords().findFirst().ifPresent((record) -> record.getResponseFieldDTO().ifPresent(fields -> {
139 updateAlert(WIND, fields.getVent());
140 updateAlert(RAIN, fields.getPluieInondation());
141 updateAlert(STORM, fields.getOrage());
142 updateAlert(FLOOD, fields.getInondation());
143 updateAlert(SNOW, fields.getNeige());
144 updateAlert(HEAT, fields.getCanicule());
145 updateAlert(FREEZE, fields.getGrandFroid());
146 updateAlert(AVALANCHE, fields.getAvalanches());
147 updateAlert(WAVE, fields.getVagueSubmersion());
148 updateState(COMMENT, new StringType(fields.getVigilanceComment()));
149 fields.getDateInsert().ifPresent(date -> updateDate(OBSERVATION_TIME, date));
150 fields.getDatePrevue().ifPresent(date -> updateDate(END_TIME, date));
154 private byte @Nullable [] getResource(String iconPath) {
155 ClassLoader classLoader = MeteoAlerteHandler.class.getClassLoader();
156 if (classLoader != null) {
157 try (InputStream stream = classLoader.getResourceAsStream(iconPath)) {
158 return stream != null ? stream.readAllBytes() : null;
159 } catch (IOException e) {
160 logger.warn("Unable to load ressource '{}' : {}", iconPath, e.getMessage());
166 private void updateAlert(String channelId, AlertLevel value) {
167 String channelIcon = channelId + "-icon";
168 if (isLinked(channelId)) {
169 updateState(channelId, ALERT_LEVELS.getOrDefault(value, UnDefType.UNDEF));
171 if (isLinked(channelIcon)) {
172 State result = UnDefType.UNDEF;
173 byte[] bytes = getResource(String.format("picto/%s.svg", channelId));
175 String resource = new String(bytes, StandardCharsets.UTF_8);
176 resource = resource.replaceAll(UNKNOWN_COLOR, ALERT_COLORS.getOrDefault(value, UNKNOWN_COLOR));
177 result = new RawType(resource.getBytes(StandardCharsets.UTF_8), "image/svg+xml");
179 updateState(channelIcon, result);
183 private void updateDate(String channelId, ZonedDateTime zonedDateTime) {
184 if (isLinked(channelId)) {
185 updateState(channelId, new DateTimeType(zonedDateTime));