]> git.basschouten.com Git - openhab-addons.git/blob
d77438a38958a0c3604c25ae3dc77f334886b8c8
[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.meteoalerte.internal.handler;
14
15 import static org.openhab.binding.meteoalerte.internal.MeteoAlerteBindingConstants.*;
16
17 import java.io.BufferedReader;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.net.MalformedURLException;
22 import java.time.ZonedDateTime;
23 import java.util.AbstractMap;
24 import java.util.Arrays;
25 import java.util.Map;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
28 import java.util.stream.Collectors;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.openhab.binding.meteoalerte.internal.MeteoAlerteConfiguration;
33 import org.openhab.binding.meteoalerte.internal.json.ApiResponse;
34 import org.openhab.binding.meteoalerte.internal.json.ResponseFieldDTO.AlertLevel;
35 import org.openhab.core.io.net.http.HttpUtil;
36 import org.openhab.core.library.types.DateTimeType;
37 import org.openhab.core.library.types.RawType;
38 import org.openhab.core.library.types.StringType;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.thing.ThingStatus;
42 import org.openhab.core.thing.ThingStatusDetail;
43 import org.openhab.core.thing.binding.BaseThingHandler;
44 import org.openhab.core.types.Command;
45 import org.openhab.core.types.RefreshType;
46 import org.openhab.core.types.UnDefType;
47 import org.osgi.framework.Bundle;
48 import org.osgi.framework.FrameworkUtil;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 import com.google.gson.Gson;
53
54 /**
55  * The {@link MeteoAlerteHandler} is responsible for updating channels
56  * and querying the API
57  *
58  * @author Gaël L'hopital - Initial contribution
59  */
60 @NonNullByDefault
61 public class MeteoAlerteHandler extends BaseThingHandler {
62     private static final String URL = "https://public.opendatasoft.com/api/records/1.0/search/?dataset=risques-meteorologiques-copy&"
63             + "facet=etat_vent&facet=etat_pluie_inondation&facet=etat_orage&facet=etat_inondation&facet=etat_neige&facet=etat_canicule&"
64             + "facet=etat_grand_froid&facet=etat_avalanches&refine.nom_dept=";
65     private static final int TIMEOUT_MS = 30000;
66     private static final Map<AlertLevel, String> ALERT_COLORS = Map.ofEntries(
67             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.GREEN, "00ff00"),
68             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.YELLOW, "ffff00"),
69             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.ORANGE, "ff6600"),
70             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.RED, "ff0000"),
71             new AbstractMap.SimpleEntry<AlertLevel, String>(AlertLevel.UNKNOWN, "b3b3b3"));
72
73     private final Logger logger = LoggerFactory.getLogger(MeteoAlerteHandler.class);
74     // Time zone provider representing time zone configured in openHAB configuration
75     private final Gson gson;
76     private @Nullable ScheduledFuture<?> refreshJob;
77     private String queryUrl = "";
78
79     public MeteoAlerteHandler(Thing thing, Gson gson) {
80         super(thing);
81         this.gson = gson;
82     }
83
84     @Override
85     public void initialize() {
86         logger.debug("Initializing Météo Alerte handler.");
87
88         MeteoAlerteConfiguration config = getConfigAs(MeteoAlerteConfiguration.class);
89         logger.debug("config department = {}", config.department);
90         logger.debug("config refresh = {}", config.refresh);
91
92         updateStatus(ThingStatus.UNKNOWN);
93         queryUrl = URL + config.department;
94         refreshJob = scheduler.scheduleWithFixedDelay(this::updateAndPublish, 0, config.refresh, TimeUnit.MINUTES);
95     }
96
97     @Override
98     public void dispose() {
99         logger.debug("Disposing the Météo Alerte handler.");
100         ScheduledFuture<?> refreshJob = this.refreshJob;
101         if (refreshJob != null) {
102             refreshJob.cancel(true);
103         }
104         this.refreshJob = null;
105     }
106
107     @Override
108     public void handleCommand(ChannelUID channelUID, Command command) {
109         if (command instanceof RefreshType) {
110             updateAndPublish();
111         }
112     }
113
114     private void updateAndPublish() {
115         try {
116             if (queryUrl.isEmpty()) {
117                 throw new MalformedURLException("queryUrl not initialized");
118             }
119             String response = HttpUtil.executeUrl("GET", queryUrl, TIMEOUT_MS);
120             updateStatus(ThingStatus.ONLINE);
121             ApiResponse apiResponse = gson.fromJson(response, ApiResponse.class);
122             updateChannels(apiResponse);
123         } catch (MalformedURLException e) {
124             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
125                     String.format("Querying '%s' raised : %s", queryUrl, e.getMessage()));
126         } catch (IOException e) {
127             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
128         }
129     }
130
131     /**
132      * Update the channel from the last Meteo Alerte data retrieved
133      *
134      * @param channelId the id identifying the channel to be updated
135      */
136     private void updateChannels(ApiResponse apiResponse) {
137         Arrays.stream(apiResponse.getRecords()).findFirst()
138                 .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));
151                 }));
152     }
153
154     public @Nullable String getResource(String iconPath) {
155         Bundle bundle = FrameworkUtil.getBundle(getClass());
156         try (InputStream stream = bundle.getResource(iconPath).openStream()) {
157             return new BufferedReader(new InputStreamReader(stream)).lines().collect(Collectors.joining("\n"));
158         } catch (IOException e) {
159             logger.warn("Unable to load ressource '{}' : {}", iconPath, e.getMessage());
160         }
161         return null;
162     }
163
164     public void updateAlert(String channelId, AlertLevel value) {
165         String channelIcon = channelId + "-icon";
166         if (isLinked(channelId)) {
167             updateState(channelId, value != AlertLevel.UNKNOWN ? new StringType(value.name()) : UnDefType.UNDEF);
168         }
169         if (isLinked(channelIcon)) {
170             String resource = getResource(String.format("picto/%s.svg", channelId));
171             if (resource != null) {
172                 resource = resource.replaceAll(ALERT_COLORS.get(AlertLevel.UNKNOWN), ALERT_COLORS.get(value));
173             }
174             updateState(channelIcon,
175                     resource != null ? new RawType(resource.getBytes(), "image/svg+xml") : UnDefType.UNDEF);
176         }
177     }
178
179     public void updateDate(String channelId, ZonedDateTime zonedDateTime) {
180         if (isLinked(channelId)) {
181             updateState(channelId, new DateTimeType(zonedDateTime));
182         }
183     }
184 }