]> git.basschouten.com Git - openhab-addons.git/blob
27657adc49adc988a57d5e6c3d38ccd1558c844e
[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.konnected.internal;
14
15 import static org.openhab.binding.konnected.internal.KonnectedBindingConstants.*;
16
17 import java.util.Dictionary;
18 import java.util.Set;
19
20 import javax.servlet.ServletException;
21
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.konnected.internal.handler.KonnectedHandler;
24 import org.openhab.binding.konnected.internal.servlet.KonnectedHTTPServlet;
25 import org.openhab.binding.konnected.internal.servlet.KonnectedWebHookFail;
26 import org.openhab.core.net.HttpServiceUtil;
27 import org.openhab.core.net.NetworkAddressService;
28 import org.openhab.core.thing.Thing;
29 import org.openhab.core.thing.ThingTypeUID;
30 import org.openhab.core.thing.binding.BaseThingHandlerFactory;
31 import org.openhab.core.thing.binding.ThingHandler;
32 import org.openhab.core.thing.binding.ThingHandlerFactory;
33 import org.osgi.service.component.ComponentContext;
34 import org.osgi.service.component.annotations.Component;
35 import org.osgi.service.component.annotations.Reference;
36 import org.osgi.service.http.HttpService;
37 import org.osgi.service.http.NamespaceException;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * The {@link KonnectedHandlerFactory} is responsible for creating things and thing
43  * handlers.
44  *
45  * @author Zachary Christiansen - Initial contribution
46  */
47 @Component(configurationPid = "binding.konnected", service = ThingHandlerFactory.class)
48 public class KonnectedHandlerFactory extends BaseThingHandlerFactory {
49     private final Logger logger = LoggerFactory.getLogger(KonnectedHandlerFactory.class);
50     private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PROMODULE,
51             THING_TYPE_WIFIMODULE);
52     private static final String alias = "/" + BINDING_ID;
53
54     private HttpService httpService;
55     private String callbackUrl = null;
56     private NetworkAddressService networkAddressService;
57     private KonnectedHTTPServlet servlet;
58
59     @Override
60     public boolean supportsThingType(ThingTypeUID thingTypeUID) {
61         return SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID);
62     }
63
64     @Override
65     protected void activate(ComponentContext componentContext) {
66         super.activate(componentContext);
67         Dictionary<String, Object> properties = componentContext.getProperties();
68         callbackUrl = (String) properties.get(CALLBACK_URL);
69         logger.debug("Callback URL from OSGI service: {}", callbackUrl);
70         try {
71             this.servlet = registerWebHookServlet();
72         } catch (KonnectedWebHookFail e) {
73             logger.error("Failed registering Konnected servlet - binding is not functional!", e);
74         }
75     }
76
77     @Override
78     protected void deactivate(ComponentContext componentContext) {
79         super.deactivate(componentContext);
80         httpService.unregister(alias);
81     }
82
83     @Override
84     protected @Nullable ThingHandler createHandler(Thing thing) {
85         KonnectedHandler thingHandler = new KonnectedHandler(thing, getCallbackUrl());
86         if (servlet != null) {
87             logger.debug("Adding thinghandler for thing {} to webhook.", thing.getUID().getId());
88             servlet.add(thingHandler);
89         }
90         return thingHandler;
91     }
92
93     /**
94      * @param thingHandler thing handler to be removed
95      */
96     @Override
97     protected void removeHandler(ThingHandler thingHandler) {
98         servlet.remove((KonnectedHandler) thingHandler);
99         thingHandler.dispose();
100         super.removeHandler(thingHandler);
101     }
102
103     private KonnectedHTTPServlet registerWebHookServlet() throws KonnectedWebHookFail {
104         KonnectedHTTPServlet servlet = new KonnectedHTTPServlet();
105         try {
106             httpService.registerServlet(alias, servlet, null, httpService.createDefaultHttpContext());
107             return servlet;
108         } catch (ServletException | NamespaceException e) {
109             throw new KonnectedWebHookFail("Could not start Konnected Webhook servlet: " + e.getMessage(), e);
110         }
111     }
112
113     @Reference
114     public void setHttpService(HttpService httpService) {
115         this.httpService = httpService;
116     }
117
118     public void unsetHttpService(HttpService httpService) {
119         this.httpService = null;
120     }
121
122     private String getCallbackUrl() {
123         if (callbackUrl == null) {
124             String callbackIP = discoverCallbackIP();
125             String callbackPort = discoverCallbackPort();
126             if (callbackPort != null && callbackIP != null) {
127                 callbackUrl = "http://" + discoverCallbackIP() + ":" + discoverCallbackPort() + '/' + BINDING_ID;
128             }
129         }
130         return callbackUrl;
131     }
132
133     private String discoverCallbackIP() {
134         final String ipAddress = networkAddressService.getPrimaryIpv4HostAddress();
135         if (ipAddress == null) {
136             logger.warn("No network interface could be found.");
137             return null;
138         }
139         logger.debug("The callback ip address obtained from the Network Address Service was:{}", ipAddress);
140         return ipAddress;
141     }
142
143     private String discoverCallbackPort() {
144         // we do not use SSL as it can cause certificate validation issues.
145         final int port = HttpServiceUtil.getHttpServicePort(bundleContext);
146         if (port == -1) {
147             logger.warn("Cannot find port of the http service.");
148             return null;
149         }
150         logger.debug("the port for the callback is: {}", port);
151         return Integer.toString(port);
152     }
153
154     @Reference
155     protected void setNetworkAddressService(NetworkAddressService networkAddressService) {
156         this.networkAddressService = networkAddressService;
157     }
158
159     protected void unsetNetworkAddressService(NetworkAddressService networkAddressService) {
160         this.networkAddressService = null;
161     }
162 }