]> git.basschouten.com Git - openhab-addons.git/blob
1e1fbda0c9c297524e837e2de24274d10e3ac688
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.dwdpollenflug.internal.handler;
14
15 import java.net.SocketTimeoutException;
16 import java.net.URI;
17 import java.util.Set;
18 import java.util.concurrent.CompletableFuture;
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.TimeoutException;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.eclipse.jetty.client.HttpResponse;
28 import org.eclipse.jetty.client.api.Request;
29 import org.eclipse.jetty.client.api.Result;
30 import org.eclipse.jetty.client.util.BufferingResponseListener;
31 import org.eclipse.jetty.http.HttpMethod;
32 import org.openhab.binding.dwdpollenflug.internal.DWDPollingException;
33 import org.openhab.binding.dwdpollenflug.internal.config.DWDPollenflugBridgeConfiguration;
34 import org.openhab.binding.dwdpollenflug.internal.dto.DWDPollenflug;
35 import org.openhab.core.thing.Bridge;
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.BaseBridgeHandler;
41 import org.openhab.core.thing.binding.ThingHandler;
42 import org.openhab.core.types.Command;
43 import org.openhab.core.types.RefreshType;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import com.google.gson.Gson;
48 import com.google.gson.JsonSyntaxException;
49
50 /**
51  * The {@link DWDPollenflugBridgeHandler} is the handler for bridge thing
52  *
53  * @author Johannes Ott - Initial contribution
54  */
55 @NonNullByDefault
56 public class DWDPollenflugBridgeHandler extends BaseBridgeHandler {
57     private static final String DWD_URL = "https://opendata.dwd.de/climate_environment/health/alerts/s31fg.json";
58
59     private final Logger logger = LoggerFactory.getLogger(DWDPollenflugBridgeHandler.class);
60
61     private DWDPollenflugBridgeConfiguration bridgeConfig = new DWDPollenflugBridgeConfiguration();
62     private @Nullable ScheduledFuture<?> pollingJob;
63     private @Nullable DWDPollenflug pollenflug;
64     private final Set<DWDPollenflugRegionHandler> regionListeners = ConcurrentHashMap.newKeySet();
65     private final HttpClient client;
66     private final Gson gson = new Gson();
67
68     public DWDPollenflugBridgeHandler(Bridge bridge, HttpClient client) {
69         super(bridge);
70         this.client = client;
71     }
72
73     @Override
74     public void handleCommand(ChannelUID channelUID, Command command) {
75         if (command instanceof RefreshType) {
76             final DWDPollenflug localPollenflug = pollenflug;
77             if (localPollenflug != null) {
78                 notifyOnUpdate(localPollenflug);
79             }
80         }
81     }
82
83     @Override
84     public void initialize() {
85         logger.debug("Initializing DWD Pollenflug bridge handler");
86         bridgeConfig = getConfigAs(DWDPollenflugBridgeConfiguration.class);
87
88         if (bridgeConfig.isValid()) {
89             updateStatus(ThingStatus.UNKNOWN);
90             startPolling();
91         } else {
92             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
93                     "Refresh interval has to be at least 15 minutes.");
94         }
95     }
96
97     @Override
98     public void dispose() {
99         logger.debug("Handler disposed.");
100         stopPolling();
101     }
102
103     private void startPolling() {
104         final ScheduledFuture<?> localPollingJob = this.pollingJob;
105         if (localPollingJob == null || localPollingJob.isCancelled()) {
106             logger.debug("Start polling.");
107             pollingJob = scheduler.scheduleWithFixedDelay(this::poll, 0, bridgeConfig.refresh, TimeUnit.MINUTES);
108         }
109     }
110
111     private void stopPolling() {
112         final ScheduledFuture<?> localPollingJob = this.pollingJob;
113         if (localPollingJob != null && !localPollingJob.isCancelled()) {
114             logger.debug("Stop polling.");
115             localPollingJob.cancel(true);
116             pollingJob = null;
117         }
118     }
119
120     private void poll() {
121         logger.debug("Polling");
122         requestRefresh().handle((resultPollenflug, pollException) -> {
123             if (resultPollenflug == null) {
124                 if (pollException == null) {
125                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
126                 } else {
127                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
128                             pollException.getMessage());
129                 }
130             } else {
131                 updateStatus(ThingStatus.ONLINE);
132                 notifyOnUpdate(resultPollenflug);
133             }
134
135             return null;
136         });
137     }
138
139     private CompletableFuture<@Nullable DWDPollenflug> requestRefresh() {
140         CompletableFuture<@Nullable DWDPollenflug> f = new CompletableFuture<>();
141         Request request = client.newRequest(URI.create(DWD_URL));
142
143         request.method(HttpMethod.GET).timeout(2000, TimeUnit.SECONDS).send(new BufferingResponseListener() {
144             @NonNullByDefault({})
145             @Override
146             public void onComplete(Result result) {
147                 final HttpResponse response = (HttpResponse) result.getResponse();
148                 if (result.getFailure() != null) {
149                     Throwable e = result.getFailure();
150                     if (e instanceof SocketTimeoutException || e instanceof TimeoutException) {
151                         f.completeExceptionally(new DWDPollingException("Request timeout", e));
152                     } else {
153                         f.completeExceptionally(new DWDPollingException("Request failed", e));
154                     }
155                 } else if (response.getStatus() != 200) {
156                     f.completeExceptionally(new DWDPollingException(getContentAsString()));
157                 } else {
158                     try {
159                         DWDPollenflug pollenflugJSON = gson.fromJson(getContentAsString(), DWDPollenflug.class);
160                         f.complete(pollenflugJSON);
161                     } catch (JsonSyntaxException ex2) {
162                         f.completeExceptionally(new DWDPollingException("Parsing of response failed"));
163                     }
164                 }
165             }
166         });
167
168         return f;
169     }
170
171     @Override
172     public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
173         if (childHandler instanceof DWDPollenflugRegionHandler) {
174             logger.debug("Register region listener.");
175             final DWDPollenflugRegionHandler regionListener = (DWDPollenflugRegionHandler) childHandler;
176             if (regionListeners.add(regionListener)) {
177                 final DWDPollenflug localPollenflug = pollenflug;
178                 if (localPollenflug != null) {
179                     regionListener.notifyOnUpdate(localPollenflug);
180                 }
181             } else {
182                 logger.warn("Tried to add listener {} but it was already present. This is probably an error.",
183                         childHandler);
184             }
185         }
186     }
187
188     @Override
189     public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
190         if (childHandler instanceof DWDPollenflugRegionHandler) {
191             logger.debug("Unregister region listener.");
192             if (!regionListeners.remove((DWDPollenflugRegionHandler) childHandler)) {
193                 logger.warn("Tried to remove listener {} but it was not registered. This is probably an error.",
194                         childHandler);
195             }
196         }
197     }
198
199     public void notifyOnUpdate(@Nullable DWDPollenflug newPollenflug) {
200         if (newPollenflug != null) {
201             pollenflug = newPollenflug;
202             updateProperties(newPollenflug.getProperties());
203             regionListeners.forEach(listener -> listener.notifyOnUpdate(newPollenflug));
204             newPollenflug.getChannelsStateMap().forEach(this::updateState);
205         }
206     }
207
208     public @Nullable DWDPollenflug getPollenflug() {
209         return pollenflug;
210     }
211 }