2 * Copyright (c) 2010-2021 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.neeo.internal.handler;
15 import java.io.IOException;
16 import java.net.InetSocketAddress;
17 import java.net.MalformedURLException;
18 import java.net.Socket;
20 import java.util.HashMap;
21 import java.util.Hashtable;
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;
31 import javax.servlet.ServletException;
32 import javax.ws.rs.client.ClientBuilder;
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.thing.binding.ThingHandler;
50 import org.openhab.core.types.Command;
51 import org.osgi.service.http.HttpService;
52 import org.osgi.service.http.NamespaceException;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 import com.google.gson.Gson;
59 * A subclass of {@link BaseBridgeHandler} is responsible for handling commands and discovery for a
62 * @author Tim Roberts - Initial contribution
65 public class NeeoBrainHandler extends BaseBridgeHandler {
68 private final Logger logger = LoggerFactory.getLogger(NeeoBrainHandler.class);
70 /** The {@link HttpService} to register callbacks */
71 private final HttpService httpService;
73 /** The {@link NetworkAddressService} to use */
74 private final NetworkAddressService networkAddressService;
76 /** The {@link ClientBuilder} to use */
77 private final ClientBuilder clientBuilder;
79 /** GSON implementation - only used to deserialize {@link NeeoAction} */
80 private final Gson gson = new Gson();
82 /** The port the HTTP service is listening on */
83 private final int servicePort;
86 * The initialization task (null until set by {@link #initializeTask()} and set back to null in {@link #dispose()}
88 private final AtomicReference<@Nullable Future<?>> initializationTask = new AtomicReference<>();
90 /** The check status task (not-null when connecting, null otherwise) */
91 private final AtomicReference<@Nullable Future<?>> checkStatus = new AtomicReference<>();
93 /** The lock that protected multi-threaded access to the state variables */
94 private final ReadWriteLock stateLock = new ReentrantReadWriteLock();
96 /** The {@link NeeoBrainApi} (null until set by {@link #initializationTask}) */
98 private NeeoBrainApi neeoBrainApi;
100 /** The path to the forward action servlet - will be null if not enabled */
102 private String servletPath;
104 /** The servlet for forward actions - will be null if not enabled */
106 private NeeoForwardActionsServlet forwardActionServlet;
109 * Instantiates a new neeo brain handler from the {@link Bridge}, service port, {@link HttpService} and
110 * {@link NetworkAddressService}.
112 * @param bridge the non-null {@link Bridge}
113 * @param servicePort the service port the http service is listening on
114 * @param httpService the non-null {@link HttpService}
115 * @param networkAddressService the non-null {@link NetworkAddressService}
117 NeeoBrainHandler(Bridge bridge, int servicePort, HttpService httpService,
118 NetworkAddressService networkAddressService, ClientBuilder clientBuilder) {
121 Objects.requireNonNull(bridge, "bridge cannot be null");
122 Objects.requireNonNull(httpService, "httpService cannot be null");
123 Objects.requireNonNull(networkAddressService, "networkAddressService cannot be null");
125 this.servicePort = servicePort;
126 this.httpService = httpService;
127 this.networkAddressService = networkAddressService;
128 this.clientBuilder = clientBuilder;
132 * Handles any {@link Command} sent - this bridge has no commands and does nothing
135 * org.openhab.core.thing.binding.ThingHandler#handleCommand(org.openhab.core.thing.ChannelUID,
136 * org.openhab.core.types.Command)
139 public void handleCommand(ChannelUID channelUID, Command command) {
143 * Simply cancels any existing initialization tasks and schedules a new task
145 * @see org.openhab.core.thing.binding.BaseThingHandler#initialize()
148 public void initialize() {
149 NeeoUtil.cancel(initializationTask.getAndSet(scheduler.submit(() -> {
155 * Initializes the bridge by connecting to the configuration ip address and parsing the results. Properties will be
156 * set and the thing will go online.
158 private void initializeTask() {
159 final Lock writerLock = stateLock.writeLock();
162 NeeoUtil.checkInterrupt();
164 final NeeoBrainConfig config = getBrainConfig();
165 logger.trace("Brain-UID {}: config is {}", thing.getUID(), config);
167 final String ipAddress = config.getIpAddress();
168 if (ipAddress == null || ipAddress.isEmpty()) {
169 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
170 "Brain IP Address must be specified");
173 final NeeoBrainApi api = new NeeoBrainApi(ipAddress, clientBuilder);
174 final NeeoBrain brain = api.getBrain();
175 final String brainId = getNeeoBrainId();
177 NeeoUtil.checkInterrupt();
180 final Map<String, String> properties = new HashMap<>();
181 addProperty(properties, "Name", brain.getName());
182 addProperty(properties, "Version", brain.getVersion());
183 addProperty(properties, "Label", brain.getLabel());
184 addProperty(properties, "Is Configured", String.valueOf(brain.isConfigured()));
185 addProperty(properties, "Key", brain.getKey());
186 addProperty(properties, "AirKey", brain.getAirkey());
187 addProperty(properties, "Last Change", String.valueOf(brain.getLastChange()));
188 updateProperties(properties);
190 String forwardChain = config.getForwardChain();
191 if (config.isEnableForwardActions() && forwardChain != null && !forwardChain.isEmpty()) {
192 NeeoUtil.checkInterrupt();
194 forwardActionServlet = new NeeoForwardActionsServlet(scheduler, json -> {
195 triggerChannel(NeeoConstants.CHANNEL_BRAIN_FOWARDACTIONS, json);
197 final NeeoAction action = Objects.requireNonNull(gson.fromJson(json, NeeoAction.class));
199 for (final Thing child : getThing().getThings()) {
200 final ThingHandler th = child.getHandler();
201 if (th instanceof NeeoRoomHandler) {
202 ((NeeoRoomHandler) th).processAction(action);
205 }, forwardChain, clientBuilder);
207 NeeoUtil.checkInterrupt();
209 servletPath = NeeoConstants.WEBAPP_FORWARDACTIONS.replace("{brainid}", brainId);
211 httpService.registerServlet(servletPath, forwardActionServlet, new Hashtable<>(),
212 httpService.createDefaultHttpContext());
214 final URL callbackURL = createCallbackUrl(brainId, config);
215 if (callbackURL == null) {
217 "Unable to create a callback URL because there is no primary address specified (please set the primary address in the configuration)");
219 final URL url = new URL(callbackURL, servletPath);
220 api.registerForwardActions(url);
222 } catch (NamespaceException | ServletException e) {
223 logger.debug("Error registering forward actions to {}: {}", servletPath, e.getMessage(), e);
227 NeeoUtil.checkInterrupt();
228 updateStatus(ThingStatus.ONLINE);
229 NeeoUtil.checkInterrupt();
230 if (config.getCheckStatusInterval() > 0) {
231 NeeoUtil.cancel(checkStatus.getAndSet(scheduler.scheduleWithFixedDelay(() -> {
233 NeeoUtil.checkInterrupt();
234 checkStatus(ipAddress);
235 } catch (InterruptedException e) {
236 // do nothing - we were interrupted and should stop
238 }, config.getCheckStatusInterval(), config.getCheckStatusInterval(), TimeUnit.SECONDS)));
240 } catch (IOException e) {
241 logger.debug("Exception occurred connecting to brain: {}", e.getMessage(), e);
242 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
243 "Exception occurred connecting to brain: " + e.getMessage());
244 } catch (InterruptedException e) {
245 logger.debug("Initialization was interrupted", e);
246 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR,
247 "Initialization was interrupted");
254 * Helper method to add a property to the properties map if the value is not null
256 * @param properties a non-null properties map
257 * @param key a non-null, non-empty key
258 * @param value a possibly null, possibly empty key
260 private void addProperty(Map<String, String> properties, String key, @Nullable String value) {
261 if (value != null && !value.isEmpty()) {
262 properties.put(key, value);
267 * Gets the {@link NeeoBrainApi} used by this bridge
269 * @return a possibly null {@link NeeoBrainApi}
272 public NeeoBrainApi getNeeoBrainApi() {
273 final Lock readerLock = stateLock.readLock();
283 * Gets the brain id used by this bridge
285 * @return a non-null, non-empty brain id
287 public String getNeeoBrainId() {
288 return getThing().getUID().getId();
292 * Helper method to get the {@link NeeoBrainConfig}
294 * @return the {@link NeeoBrainConfig}
296 private NeeoBrainConfig getBrainConfig() {
297 return getConfigAs(NeeoBrainConfig.class);
301 * Checks the status of the brain via a quick socket connection. If the status is unavailable and we are
302 * {@link ThingStatus#ONLINE}, then we go {@link ThingStatus#OFFLINE}. If the status is available and we are
303 * {@link ThingStatus#OFFLINE}, we go {@link ThingStatus#ONLINE}.
305 * @param ipAddress a non-null, non-empty IP address
307 private void checkStatus(String ipAddress) {
308 NeeoUtil.requireNotEmpty(ipAddress, "ipAddress cannot be empty");
311 try (Socket soc = new Socket()) {
312 soc.connect(new InetSocketAddress(ipAddress, NeeoConstants.DEFAULT_BRAIN_PORT), 5000);
314 logger.debug("Checking connectivity to {}:{} - successful", ipAddress, NeeoConstants.DEFAULT_BRAIN_PORT);
316 if (getThing().getStatus() != ThingStatus.ONLINE) {
317 updateStatus(ThingStatus.ONLINE);
319 } catch (IOException e) {
320 if (getThing().getStatus() == ThingStatus.ONLINE) {
321 logger.debug("Checking connectivity to {}:{} - unsuccessful - going offline: {}", ipAddress,
322 NeeoConstants.DEFAULT_BRAIN_PORT, e.getMessage(), e);
323 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
324 "Exception occurred connecting to brain: " + e.getMessage());
326 logger.debug("Checking connectivity to {}:{} - unsuccessful - still offline", ipAddress,
327 NeeoConstants.DEFAULT_BRAIN_PORT);
333 * Disposes of the bridge by closing/removing the {@link #neeoBrainApi} and canceling/removing any pending
334 * {@link #initializeTask()}
337 public void dispose() {
338 final Lock writerLock = stateLock.writeLock();
341 final NeeoBrainApi api = neeoBrainApi;
344 NeeoUtil.cancel(initializationTask.getAndSet(null));
345 NeeoUtil.cancel(checkStatus.getAndSet(null));
347 if (forwardActionServlet != null) {
348 forwardActionServlet = null;
352 api.deregisterForwardActions();
353 } catch (IOException e) {
354 logger.debug("IOException occurred deregistering the forward actions: {}", e.getMessage(), e);
358 if (servletPath != null) {
359 httpService.unregister(servletPath);
371 * Creates the URL the brain should callback. Note: if there is multiple interfaces, we try to prefer the one on the
372 * same subnet as the brain
374 * @param brainId the non-null, non-empty brain identifier
375 * @param config the non-null brain configuration
376 * @return the callback URL
377 * @throws MalformedURLException if the URL is malformed
380 private URL createCallbackUrl(String brainId, NeeoBrainConfig config) throws MalformedURLException {
381 NeeoUtil.requireNotEmpty(brainId, "brainId cannot be empty");
382 Objects.requireNonNull(config, "config cannot be null");
384 final String ipAddress = networkAddressService.getPrimaryIpv4HostAddress();
385 if (ipAddress == null) {
386 logger.debug("No network interface could be found.");
390 return new URL("http://" + ipAddress + ":" + servicePort);