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;
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.eclipse.jetty.client.HttpClient;
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 private final HttpClient httpClient;
77 /** GSON implementation - only used to deserialize {@link NeeoAction} */
78 private final Gson gson = new Gson();
80 /** The port the HTTP service is listening on */
81 private final int servicePort;
84 * The initialization task (null until set by {@link #initializeTask()} and set back to null in {@link #dispose()}
86 private final AtomicReference<@Nullable Future<?>> initializationTask = new AtomicReference<>();
88 /** The check status task (not-null when connecting, null otherwise) */
89 private final AtomicReference<@Nullable Future<?>> checkStatus = new AtomicReference<>();
91 /** The lock that protected multi-threaded access to the state variables */
92 private final ReadWriteLock stateLock = new ReentrantReadWriteLock();
94 /** The {@link NeeoBrainApi} (null until set by {@link #initializationTask}) */
96 private NeeoBrainApi neeoBrainApi;
98 /** The path to the forward action servlet - will be null if not enabled */
100 private String servletPath;
102 /** The servlet for forward actions - will be null if not enabled */
104 private NeeoForwardActionsServlet forwardActionServlet;
107 * Instantiates a new neeo brain handler from the {@link Bridge}, service port, {@link HttpService} and
108 * {@link NetworkAddressService}.
110 * @param bridge the non-null {@link Bridge}
111 * @param servicePort the service port the http service is listening on
112 * @param httpService the non-null {@link HttpService}
113 * @param networkAddressService the non-null {@link NetworkAddressService}
115 NeeoBrainHandler(Bridge bridge, int servicePort, HttpService httpService,
116 NetworkAddressService networkAddressService, HttpClient httpClient) {
119 Objects.requireNonNull(bridge, "bridge cannot be null");
120 Objects.requireNonNull(httpService, "httpService cannot be null");
121 Objects.requireNonNull(networkAddressService, "networkAddressService cannot be null");
123 this.servicePort = servicePort;
124 this.httpService = httpService;
125 this.networkAddressService = networkAddressService;
126 this.httpClient = httpClient;
130 * Handles any {@link Command} sent - this bridge has no commands and does nothing
133 * org.openhab.core.thing.binding.ThingHandler#handleCommand(org.openhab.core.thing.ChannelUID,
134 * org.openhab.core.types.Command)
137 public void handleCommand(ChannelUID channelUID, Command command) {
141 * Simply cancels any existing initialization tasks and schedules a new task
143 * @see org.openhab.core.thing.binding.BaseThingHandler#initialize()
146 public void initialize() {
147 NeeoUtil.cancel(initializationTask.getAndSet(scheduler.submit(() -> {
153 * Initializes the bridge by connecting to the configuration ip address and parsing the results. Properties will be
154 * set and the thing will go online.
156 private void initializeTask() {
157 final Lock writerLock = stateLock.writeLock();
160 NeeoUtil.checkInterrupt();
162 final NeeoBrainConfig config = getBrainConfig();
163 logger.trace("Brain-UID {}: config is {}", thing.getUID(), config);
165 final String ipAddress = config.getIpAddress();
166 if (ipAddress == null || ipAddress.isEmpty()) {
167 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
168 "Brain IP Address must be specified");
171 final NeeoBrainApi api = new NeeoBrainApi(ipAddress, httpClient);
172 final NeeoBrain brain = api.getBrain();
173 final String brainId = getNeeoBrainId();
175 NeeoUtil.checkInterrupt();
178 final Map<String, String> properties = new HashMap<>();
179 addProperty(properties, "Name", brain.getName());
180 addProperty(properties, "Version", brain.getVersion());
181 addProperty(properties, "Label", brain.getLabel());
182 addProperty(properties, "Is Configured", String.valueOf(brain.isConfigured()));
183 addProperty(properties, "Key", brain.getKey());
184 addProperty(properties, "AirKey", brain.getAirkey());
185 addProperty(properties, "Last Change", String.valueOf(brain.getLastChange()));
186 updateProperties(properties);
188 if (config.isEnableForwardActions()) {
189 NeeoUtil.checkInterrupt();
191 forwardActionServlet = new NeeoForwardActionsServlet(scheduler, json -> {
192 triggerChannel(NeeoConstants.CHANNEL_BRAIN_FOWARDACTIONS, json);
194 final NeeoAction action = Objects.requireNonNull(gson.fromJson(json, NeeoAction.class));
195 getThing().getThings().stream().map(Thing::getHandler).filter(NeeoRoomHandler.class::isInstance)
196 .forEach(h -> ((NeeoRoomHandler) h).processAction(action));
197 }, config.getForwardChain(), httpClient);
199 NeeoUtil.checkInterrupt();
201 String servletPath = NeeoConstants.WEBAPP_FORWARDACTIONS.replace("{brainid}", brainId);
202 this.servletPath = servletPath;
204 Hashtable<Object, Object> initParams = new Hashtable<>();
205 initParams.put("servlet-name", servletPath);
207 httpService.registerServlet(servletPath, forwardActionServlet, initParams,
208 httpService.createDefaultHttpContext());
210 final URL callbackURL = createCallbackUrl(brainId, config);
211 if (callbackURL == null) {
213 "Unable to create a callback URL because there is no primary address specified (please set the primary address in the configuration)");
215 final URL url = new URL(callbackURL, servletPath);
216 api.registerForwardActions(url);
218 } catch (NamespaceException | ServletException e) {
219 logger.debug("Error registering forward actions to {}: {}", servletPath, e.getMessage(), e);
223 NeeoUtil.checkInterrupt();
224 updateStatus(ThingStatus.ONLINE);
225 NeeoUtil.checkInterrupt();
226 if (config.getCheckStatusInterval() > 0) {
227 NeeoUtil.cancel(checkStatus.getAndSet(scheduler.scheduleWithFixedDelay(() -> {
229 NeeoUtil.checkInterrupt();
230 checkStatus(ipAddress);
231 } catch (InterruptedException e) {
232 // do nothing - we were interrupted and should stop
234 }, config.getCheckStatusInterval(), config.getCheckStatusInterval(), TimeUnit.SECONDS)));
236 } catch (IOException e) {
237 logger.debug("Exception occurred connecting to brain: {}", e.getMessage(), e);
238 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
239 "Exception occurred connecting to brain: " + e.getMessage());
240 } catch (InterruptedException e) {
241 logger.debug("Initialization was interrupted", e);
242 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR,
243 "Initialization was interrupted");
250 * Helper method to add a property to the properties map if the value is not null
252 * @param properties a non-null properties map
253 * @param key a non-null, non-empty key
254 * @param value a possibly null, possibly empty key
256 private void addProperty(Map<String, String> properties, String key, @Nullable String value) {
257 if (value != null && !value.isEmpty()) {
258 properties.put(key, value);
263 * Gets the {@link NeeoBrainApi} used by this bridge
265 * @return a possibly null {@link NeeoBrainApi}
268 public NeeoBrainApi getNeeoBrainApi() {
269 final Lock readerLock = stateLock.readLock();
279 * Gets the brain id used by this bridge
281 * @return a non-null, non-empty brain id
283 public String getNeeoBrainId() {
284 return getThing().getUID().getId();
288 * Helper method to get the {@link NeeoBrainConfig}
290 * @return the {@link NeeoBrainConfig}
292 private NeeoBrainConfig getBrainConfig() {
293 return getConfigAs(NeeoBrainConfig.class);
297 * Checks the status of the brain via a quick socket connection. If the status is unavailable and we are
298 * {@link ThingStatus#ONLINE}, then we go {@link ThingStatus#OFFLINE}. If the status is available and we are
299 * {@link ThingStatus#OFFLINE}, we go {@link ThingStatus#ONLINE}.
301 * @param ipAddress a non-null, non-empty IP address
303 private void checkStatus(String ipAddress) {
304 NeeoUtil.requireNotEmpty(ipAddress, "ipAddress cannot be empty");
307 try (Socket soc = new Socket()) {
308 soc.connect(new InetSocketAddress(ipAddress, NeeoConstants.DEFAULT_BRAIN_PORT), 5000);
310 logger.debug("Checking connectivity to {}:{} - successful", ipAddress, NeeoConstants.DEFAULT_BRAIN_PORT);
312 if (getThing().getStatus() != ThingStatus.ONLINE) {
313 updateStatus(ThingStatus.ONLINE);
315 } catch (IOException e) {
316 if (getThing().getStatus() == ThingStatus.ONLINE) {
317 logger.debug("Checking connectivity to {}:{} - unsuccessful - going offline: {}", ipAddress,
318 NeeoConstants.DEFAULT_BRAIN_PORT, e.getMessage(), e);
319 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
320 "Exception occurred connecting to brain: " + e.getMessage());
322 logger.debug("Checking connectivity to {}:{} - unsuccessful - still offline", ipAddress,
323 NeeoConstants.DEFAULT_BRAIN_PORT);
329 * Disposes of the bridge by closing/removing the {@link #neeoBrainApi} and canceling/removing any pending
330 * {@link #initializeTask()}
333 public void dispose() {
334 final Lock writerLock = stateLock.writeLock();
337 final NeeoBrainApi api = neeoBrainApi;
340 NeeoUtil.cancel(initializationTask.getAndSet(null));
341 NeeoUtil.cancel(checkStatus.getAndSet(null));
343 if (forwardActionServlet != null) {
344 forwardActionServlet = null;
348 api.deregisterForwardActions();
349 } catch (IOException e) {
350 logger.debug("IOException occurred deregistering the forward actions: {}", e.getMessage(), e);
354 if (servletPath != null) {
355 httpService.unregister(servletPath);
367 * Creates the URL the brain should callback. Note: if there is multiple interfaces, we try to prefer the one on the
368 * same subnet as the brain
370 * @param brainId the non-null, non-empty brain identifier
371 * @param config the non-null brain configuration
372 * @return the callback URL
373 * @throws MalformedURLException if the URL is malformed
376 private URL createCallbackUrl(String brainId, NeeoBrainConfig config) throws MalformedURLException {
377 NeeoUtil.requireNotEmpty(brainId, "brainId cannot be empty");
378 Objects.requireNonNull(config, "config cannot be null");
380 final String ipAddress = networkAddressService.getPrimaryIpv4HostAddress();
381 if (ipAddress == null) {
382 logger.debug("No network interface could be found.");
386 return new URL("http://" + ipAddress + ":" + servicePort);