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.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.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;
55 import com.google.gson.Gson;
58 * A subclass of {@link BaseBridgeHandler} is responsible for handling commands and discovery for a
61 * @author Tim Roberts - Initial contribution
64 public class NeeoBrainHandler extends BaseBridgeHandler {
67 private final Logger logger = LoggerFactory.getLogger(NeeoBrainHandler.class);
69 /** The {@link HttpService} to register callbacks */
70 private final HttpService httpService;
72 /** The {@link NetworkAddressService} to use */
73 private final NetworkAddressService networkAddressService;
75 /** The {@link ClientBuilder} to use */
76 private final ClientBuilder clientBuilder;
78 /** GSON implementation - only used to deserialize {@link NeeoAction} */
79 private final Gson gson = new Gson();
81 /** The port the HTTP service is listening on */
82 private final int servicePort;
85 * The initialization task (null until set by {@link #initializeTask()} and set back to null in {@link #dispose()}
87 private final AtomicReference<@Nullable Future<?>> initializationTask = new AtomicReference<>();
89 /** The check status task (not-null when connecting, null otherwise) */
90 private final AtomicReference<@Nullable Future<?>> checkStatus = new AtomicReference<>();
92 /** The lock that protected multi-threaded access to the state variables */
93 private final ReadWriteLock stateLock = new ReentrantReadWriteLock();
95 /** The {@link NeeoBrainApi} (null until set by {@link #initializationTask}) */
97 private NeeoBrainApi neeoBrainApi;
99 /** The path to the forward action servlet - will be null if not enabled */
101 private String servletPath;
103 /** The servlet for forward actions - will be null if not enabled */
105 private NeeoForwardActionsServlet forwardActionServlet;
108 * Instantiates a new neeo brain handler from the {@link Bridge}, service port, {@link HttpService} and
109 * {@link NetworkAddressService}.
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}
116 NeeoBrainHandler(Bridge bridge, int servicePort, HttpService httpService,
117 NetworkAddressService networkAddressService, ClientBuilder clientBuilder) {
120 Objects.requireNonNull(bridge, "bridge cannot be null");
121 Objects.requireNonNull(httpService, "httpService cannot be null");
122 Objects.requireNonNull(networkAddressService, "networkAddressService cannot be null");
124 this.servicePort = servicePort;
125 this.httpService = httpService;
126 this.networkAddressService = networkAddressService;
127 this.clientBuilder = clientBuilder;
131 * Handles any {@link Command} sent - this bridge has no commands and does nothing
134 * org.openhab.core.thing.binding.ThingHandler#handleCommand(org.openhab.core.thing.ChannelUID,
135 * org.openhab.core.types.Command)
138 public void handleCommand(ChannelUID channelUID, Command command) {
142 * Simply cancels any existing initialization tasks and schedules a new task
144 * @see org.openhab.core.thing.binding.BaseThingHandler#initialize()
147 public void initialize() {
148 NeeoUtil.cancel(initializationTask.getAndSet(scheduler.submit(() -> {
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.
157 private void initializeTask() {
158 final Lock writerLock = stateLock.writeLock();
161 NeeoUtil.checkInterrupt();
163 final NeeoBrainConfig config = getBrainConfig();
164 logger.trace("Brain-UID {}: config is {}", thing.getUID(), config);
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");
172 final NeeoBrainApi api = new NeeoBrainApi(ipAddress, clientBuilder);
173 final NeeoBrain brain = api.getBrain();
174 final String brainId = getNeeoBrainId();
176 NeeoUtil.checkInterrupt();
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);
189 if (config.isEnableForwardActions()) {
190 NeeoUtil.checkInterrupt();
192 forwardActionServlet = new NeeoForwardActionsServlet(scheduler, json -> {
193 triggerChannel(NeeoConstants.CHANNEL_BRAIN_FOWARDACTIONS, json);
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);
200 NeeoUtil.checkInterrupt();
202 servletPath = NeeoConstants.WEBAPP_FORWARDACTIONS.replace("{brainid}", brainId);
204 httpService.registerServlet(servletPath, forwardActionServlet, new Hashtable<>(),
205 httpService.createDefaultHttpContext());
207 final URL callbackURL = createCallbackUrl(brainId, config);
208 if (callbackURL == null) {
210 "Unable to create a callback URL because there is no primary address specified (please set the primary address in the configuration)");
212 final URL url = new URL(callbackURL, servletPath);
213 api.registerForwardActions(url);
215 } catch (NamespaceException | ServletException e) {
216 logger.debug("Error registering forward actions to {}: {}", servletPath, e.getMessage(), e);
220 NeeoUtil.checkInterrupt();
221 updateStatus(ThingStatus.ONLINE);
222 NeeoUtil.checkInterrupt();
223 if (config.getCheckStatusInterval() > 0) {
224 NeeoUtil.cancel(checkStatus.getAndSet(scheduler.scheduleWithFixedDelay(() -> {
226 NeeoUtil.checkInterrupt();
227 checkStatus(ipAddress);
228 } catch (InterruptedException e) {
229 // do nothing - we were interrupted and should stop
231 }, config.getCheckStatusInterval(), config.getCheckStatusInterval(), TimeUnit.SECONDS)));
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");
247 * Helper method to add a property to the properties map if the value is not null
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
253 private void addProperty(Map<String, String> properties, String key, @Nullable String value) {
254 if (value != null && !value.isEmpty()) {
255 properties.put(key, value);
260 * Gets the {@link NeeoBrainApi} used by this bridge
262 * @return a possibly null {@link NeeoBrainApi}
265 public NeeoBrainApi getNeeoBrainApi() {
266 final Lock readerLock = stateLock.readLock();
276 * Gets the brain id used by this bridge
278 * @return a non-null, non-empty brain id
280 public String getNeeoBrainId() {
281 return getThing().getUID().getId();
285 * Helper method to get the {@link NeeoBrainConfig}
287 * @return the {@link NeeoBrainConfig}
289 private NeeoBrainConfig getBrainConfig() {
290 return getConfigAs(NeeoBrainConfig.class);
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}.
298 * @param ipAddress a non-null, non-empty IP address
300 private void checkStatus(String ipAddress) {
301 NeeoUtil.requireNotEmpty(ipAddress, "ipAddress cannot be empty");
304 try (Socket soc = new Socket()) {
305 soc.connect(new InetSocketAddress(ipAddress, NeeoConstants.DEFAULT_BRAIN_PORT), 5000);
307 logger.debug("Checking connectivity to {}:{} - successful", ipAddress, NeeoConstants.DEFAULT_BRAIN_PORT);
309 if (getThing().getStatus() != ThingStatus.ONLINE) {
310 updateStatus(ThingStatus.ONLINE);
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());
319 logger.debug("Checking connectivity to {}:{} - unsuccessful - still offline", ipAddress,
320 NeeoConstants.DEFAULT_BRAIN_PORT);
326 * Disposes of the bridge by closing/removing the {@link #neeoBrainApi} and canceling/removing any pending
327 * {@link #initializeTask()}
330 public void dispose() {
331 final Lock writerLock = stateLock.writeLock();
334 final NeeoBrainApi api = neeoBrainApi;
337 NeeoUtil.cancel(initializationTask.getAndSet(null));
338 NeeoUtil.cancel(checkStatus.getAndSet(null));
340 if (forwardActionServlet != null) {
341 forwardActionServlet = null;
345 api.deregisterForwardActions();
346 } catch (IOException e) {
347 logger.debug("IOException occurred deregistering the forward actions: {}", e.getMessage(), e);
351 if (servletPath != null) {
352 httpService.unregister(servletPath);
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
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
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");
377 final String ipAddress = networkAddressService.getPrimaryIpv4HostAddress();
378 if (ipAddress == null) {
379 logger.debug("No network interface could be found.");
383 return new URL("http://" + ipAddress + ":" + servicePort);