]> git.basschouten.com Git - openhab-addons.git/blob
880236caf3196fdc264a47f390c054c98b892622
[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.neeo.internal.handler;
14
15 import java.io.IOException;
16 import java.net.InetSocketAddress;
17 import java.net.MalformedURLException;
18 import java.net.Socket;
19 import java.net.URL;
20 import java.util.HashMap;
21 import java.util.Hashtable;
22 import java.util.Map;
23 import java.util.Objects;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.atomic.AtomicReference;
27 import java.util.concurrent.locks.Lock;
28 import java.util.concurrent.locks.ReadWriteLock;
29 import java.util.concurrent.locks.ReentrantReadWriteLock;
30
31 import javax.servlet.ServletException;
32 import javax.ws.rs.client.ClientBuilder;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.openhab.binding.neeo.internal.NeeoBrainApi;
37 import org.openhab.binding.neeo.internal.NeeoBrainConfig;
38 import org.openhab.binding.neeo.internal.NeeoConstants;
39 import org.openhab.binding.neeo.internal.NeeoUtil;
40 import org.openhab.binding.neeo.internal.models.NeeoAction;
41 import org.openhab.binding.neeo.internal.models.NeeoBrain;
42 import org.openhab.core.net.NetworkAddressService;
43 import org.openhab.core.thing.Bridge;
44 import org.openhab.core.thing.ChannelUID;
45 import org.openhab.core.thing.Thing;
46 import org.openhab.core.thing.ThingStatus;
47 import org.openhab.core.thing.ThingStatusDetail;
48 import org.openhab.core.thing.binding.BaseBridgeHandler;
49 import org.openhab.core.types.Command;
50 import org.osgi.service.http.HttpService;
51 import org.osgi.service.http.NamespaceException;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 import com.google.gson.Gson;
56
57 /**
58  * A subclass of {@link BaseBridgeHandler} is responsible for handling commands and discovery for a
59  * {@link NeeoBrain}
60  *
61  * @author Tim Roberts - Initial contribution
62  */
63 @NonNullByDefault
64 public class NeeoBrainHandler extends BaseBridgeHandler {
65
66     /** The logger */
67     private final Logger logger = LoggerFactory.getLogger(NeeoBrainHandler.class);
68
69     /** The {@link HttpService} to register callbacks */
70     private final HttpService httpService;
71
72     /** The {@link NetworkAddressService} to use */
73     private final NetworkAddressService networkAddressService;
74
75     /** The {@link ClientBuilder} to use */
76     private final ClientBuilder clientBuilder;
77
78     /** GSON implementation - only used to deserialize {@link NeeoAction} */
79     private final Gson gson = new Gson();
80
81     /** The port the HTTP service is listening on */
82     private final int servicePort;
83
84     /**
85      * The initialization task (null until set by {@link #initializeTask()} and set back to null in {@link #dispose()}
86      */
87     private final AtomicReference<@Nullable Future<?>> initializationTask = new AtomicReference<>();
88
89     /** The check status task (not-null when connecting, null otherwise) */
90     private final AtomicReference<@Nullable Future<?>> checkStatus = new AtomicReference<>();
91
92     /** The lock that protected multi-threaded access to the state variables */
93     private final ReadWriteLock stateLock = new ReentrantReadWriteLock();
94
95     /** The {@link NeeoBrainApi} (null until set by {@link #initializationTask}) */
96     @Nullable
97     private NeeoBrainApi neeoBrainApi;
98
99     /** The path to the forward action servlet - will be null if not enabled */
100     @Nullable
101     private String servletPath;
102
103     /** The servlet for forward actions - will be null if not enabled */
104     @Nullable
105     private NeeoForwardActionsServlet forwardActionServlet;
106
107     /**
108      * Instantiates a new neeo brain handler from the {@link Bridge}, service port, {@link HttpService} and
109      * {@link NetworkAddressService}.
110      *
111      * @param bridge the non-null {@link Bridge}
112      * @param servicePort the service port the http service is listening on
113      * @param httpService the non-null {@link HttpService}
114      * @param networkAddressService the non-null {@link NetworkAddressService}
115      */
116     NeeoBrainHandler(Bridge bridge, int servicePort, HttpService httpService,
117             NetworkAddressService networkAddressService, ClientBuilder clientBuilder) {
118         super(bridge);
119
120         Objects.requireNonNull(bridge, "bridge cannot be null");
121         Objects.requireNonNull(httpService, "httpService cannot be null");
122         Objects.requireNonNull(networkAddressService, "networkAddressService cannot be null");
123
124         this.servicePort = servicePort;
125         this.httpService = httpService;
126         this.networkAddressService = networkAddressService;
127         this.clientBuilder = clientBuilder;
128     }
129
130     /**
131      * Handles any {@link Command} sent - this bridge has no commands and does nothing
132      *
133      * @see
134      *      org.openhab.core.thing.binding.ThingHandler#handleCommand(org.openhab.core.thing.ChannelUID,
135      *      org.openhab.core.types.Command)
136      */
137     @Override
138     public void handleCommand(ChannelUID channelUID, Command command) {
139     }
140
141     /**
142      * Simply cancels any existing initialization tasks and schedules a new task
143      *
144      * @see org.openhab.core.thing.binding.BaseThingHandler#initialize()
145      */
146     @Override
147     public void initialize() {
148         NeeoUtil.cancel(initializationTask.getAndSet(scheduler.submit(() -> {
149             initializeTask();
150         })));
151     }
152
153     /**
154      * Initializes the bridge by connecting to the configuration ip address and parsing the results. Properties will be
155      * set and the thing will go online.
156      */
157     private void initializeTask() {
158         final Lock writerLock = stateLock.writeLock();
159         writerLock.lock();
160         try {
161             NeeoUtil.checkInterrupt();
162
163             final NeeoBrainConfig config = getBrainConfig();
164             logger.trace("Brain-UID {}: config is {}", thing.getUID(), config);
165
166             final String ipAddress = config.getIpAddress();
167             if (ipAddress == null || ipAddress.isEmpty()) {
168                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
169                         "Brain IP Address must be specified");
170                 return;
171             }
172             final NeeoBrainApi api = new NeeoBrainApi(ipAddress, clientBuilder);
173             final NeeoBrain brain = api.getBrain();
174             final String brainId = getNeeoBrainId();
175
176             NeeoUtil.checkInterrupt();
177             neeoBrainApi = api;
178
179             final Map<String, String> properties = new HashMap<>();
180             addProperty(properties, "Name", brain.getName());
181             addProperty(properties, "Version", brain.getVersion());
182             addProperty(properties, "Label", brain.getLabel());
183             addProperty(properties, "Is Configured", String.valueOf(brain.isConfigured()));
184             addProperty(properties, "Key", brain.getKey());
185             addProperty(properties, "AirKey", brain.getAirkey());
186             addProperty(properties, "Last Change", String.valueOf(brain.getLastChange()));
187             updateProperties(properties);
188
189             if (config.isEnableForwardActions()) {
190                 NeeoUtil.checkInterrupt();
191
192                 forwardActionServlet = new NeeoForwardActionsServlet(scheduler, json -> {
193                     triggerChannel(NeeoConstants.CHANNEL_BRAIN_FOWARDACTIONS, json);
194
195                     final NeeoAction action = Objects.requireNonNull(gson.fromJson(json, NeeoAction.class));
196                     getThing().getThings().stream().map(Thing::getHandler).filter(NeeoRoomHandler.class::isInstance)
197                             .forEach(h -> ((NeeoRoomHandler) h).processAction(action));
198                 }, config.getForwardChain(), clientBuilder);
199
200                 NeeoUtil.checkInterrupt();
201                 try {
202                     servletPath = NeeoConstants.WEBAPP_FORWARDACTIONS.replace("{brainid}", brainId);
203
204                     httpService.registerServlet(servletPath, forwardActionServlet, new Hashtable<>(),
205                             httpService.createDefaultHttpContext());
206
207                     final URL callbackURL = createCallbackUrl(brainId, config);
208                     if (callbackURL == null) {
209                         logger.debug(
210                                 "Unable to create a callback URL because there is no primary address specified (please set the primary address in the configuration)");
211                     } else {
212                         final URL url = new URL(callbackURL, servletPath);
213                         api.registerForwardActions(url);
214                     }
215                 } catch (NamespaceException | ServletException e) {
216                     logger.debug("Error registering forward actions to {}: {}", servletPath, e.getMessage(), e);
217                 }
218             }
219
220             NeeoUtil.checkInterrupt();
221             updateStatus(ThingStatus.ONLINE);
222             NeeoUtil.checkInterrupt();
223             if (config.getCheckStatusInterval() > 0) {
224                 NeeoUtil.cancel(checkStatus.getAndSet(scheduler.scheduleWithFixedDelay(() -> {
225                     try {
226                         NeeoUtil.checkInterrupt();
227                         checkStatus(ipAddress);
228                     } catch (InterruptedException e) {
229                         // do nothing - we were interrupted and should stop
230                     }
231                 }, config.getCheckStatusInterval(), config.getCheckStatusInterval(), TimeUnit.SECONDS)));
232             }
233         } catch (IOException e) {
234             logger.debug("Exception occurred connecting to brain: {}", e.getMessage(), e);
235             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
236                     "Exception occurred connecting to brain: " + e.getMessage());
237         } catch (InterruptedException e) {
238             logger.debug("Initialization was interrupted", e);
239             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR,
240                     "Initialization was interrupted");
241         } finally {
242             writerLock.unlock();
243         }
244     }
245
246     /**
247      * Helper method to add a property to the properties map if the value is not null
248      *
249      * @param properties a non-null properties map
250      * @param key a non-null, non-empty key
251      * @param value a possibly null, possibly empty key
252      */
253     private void addProperty(Map<String, String> properties, String key, @Nullable String value) {
254         if (value != null && !value.isEmpty()) {
255             properties.put(key, value);
256         }
257     }
258
259     /**
260      * Gets the {@link NeeoBrainApi} used by this bridge
261      *
262      * @return a possibly null {@link NeeoBrainApi}
263      */
264     @Nullable
265     public NeeoBrainApi getNeeoBrainApi() {
266         final Lock readerLock = stateLock.readLock();
267         readerLock.lock();
268         try {
269             return neeoBrainApi;
270         } finally {
271             readerLock.unlock();
272         }
273     }
274
275     /**
276      * Gets the brain id used by this bridge
277      *
278      * @return a non-null, non-empty brain id
279      */
280     public String getNeeoBrainId() {
281         return getThing().getUID().getId();
282     }
283
284     /**
285      * Helper method to get the {@link NeeoBrainConfig}
286      *
287      * @return the {@link NeeoBrainConfig}
288      */
289     private NeeoBrainConfig getBrainConfig() {
290         return getConfigAs(NeeoBrainConfig.class);
291     }
292
293     /**
294      * Checks the status of the brain via a quick socket connection. If the status is unavailable and we are
295      * {@link ThingStatus#ONLINE}, then we go {@link ThingStatus#OFFLINE}. If the status is available and we are
296      * {@link ThingStatus#OFFLINE}, we go {@link ThingStatus#ONLINE}.
297      *
298      * @param ipAddress a non-null, non-empty IP address
299      */
300     private void checkStatus(String ipAddress) {
301         NeeoUtil.requireNotEmpty(ipAddress, "ipAddress cannot be empty");
302
303         try {
304             try (Socket soc = new Socket()) {
305                 soc.connect(new InetSocketAddress(ipAddress, NeeoConstants.DEFAULT_BRAIN_PORT), 5000);
306             }
307             logger.debug("Checking connectivity to {}:{} - successful", ipAddress, NeeoConstants.DEFAULT_BRAIN_PORT);
308
309             if (getThing().getStatus() != ThingStatus.ONLINE) {
310                 updateStatus(ThingStatus.ONLINE);
311             }
312         } catch (IOException e) {
313             if (getThing().getStatus() == ThingStatus.ONLINE) {
314                 logger.debug("Checking connectivity to {}:{} - unsuccessful - going offline: {}", ipAddress,
315                         NeeoConstants.DEFAULT_BRAIN_PORT, e.getMessage(), e);
316                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
317                         "Exception occurred connecting to brain: " + e.getMessage());
318             } else {
319                 logger.debug("Checking connectivity to {}:{} - unsuccessful - still offline", ipAddress,
320                         NeeoConstants.DEFAULT_BRAIN_PORT);
321             }
322         }
323     }
324
325     /**
326      * Disposes of the bridge by closing/removing the {@link #neeoBrainApi} and canceling/removing any pending
327      * {@link #initializeTask()}
328      */
329     @Override
330     public void dispose() {
331         final Lock writerLock = stateLock.writeLock();
332         writerLock.lock();
333         try {
334             final NeeoBrainApi api = neeoBrainApi;
335             neeoBrainApi = null;
336
337             NeeoUtil.cancel(initializationTask.getAndSet(null));
338             NeeoUtil.cancel(checkStatus.getAndSet(null));
339
340             if (forwardActionServlet != null) {
341                 forwardActionServlet = null;
342
343                 if (api != null) {
344                     try {
345                         api.deregisterForwardActions();
346                     } catch (IOException e) {
347                         logger.debug("IOException occurred deregistering the forward actions: {}", e.getMessage(), e);
348                     }
349                 }
350
351                 if (servletPath != null) {
352                     httpService.unregister(servletPath);
353                     servletPath = null;
354                 }
355             }
356
357             NeeoUtil.close(api);
358         } finally {
359             writerLock.unlock();
360         }
361     }
362
363     /**
364      * Creates the URL the brain should callback. Note: if there is multiple interfaces, we try to prefer the one on the
365      * same subnet as the brain
366      *
367      * @param brainId the non-null, non-empty brain identifier
368      * @param config the non-null brain configuration
369      * @return the callback URL
370      * @throws MalformedURLException if the URL is malformed
371      */
372     @Nullable
373     private URL createCallbackUrl(String brainId, NeeoBrainConfig config) throws MalformedURLException {
374         NeeoUtil.requireNotEmpty(brainId, "brainId cannot be empty");
375         Objects.requireNonNull(config, "config cannot be null");
376
377         final String ipAddress = networkAddressService.getPrimaryIpv4HostAddress();
378         if (ipAddress == null) {
379             logger.debug("No network interface could be found.");
380             return null;
381         }
382
383         return new URL("http://" + ipAddress + ":" + servicePort);
384     }
385 }