]> git.basschouten.com Git - openhab-addons.git/blob
444c53beff080f288efd16138c94a579eb7e3344
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.shelly.internal;
14
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16
17 import java.util.HashMap;
18 import java.util.Map;
19 import java.util.Set;
20 import java.util.concurrent.ConcurrentHashMap;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.eclipse.jetty.client.HttpClient;
25 import org.openhab.binding.shelly.internal.coap.ShellyCoapServer;
26 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
27 import org.openhab.binding.shelly.internal.handler.ShellyBaseHandler;
28 import org.openhab.binding.shelly.internal.handler.ShellyLightHandler;
29 import org.openhab.binding.shelly.internal.handler.ShellyManagerInterface;
30 import org.openhab.binding.shelly.internal.handler.ShellyProtectedHandler;
31 import org.openhab.binding.shelly.internal.handler.ShellyRelayHandler;
32 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
33 import org.openhab.binding.shelly.internal.util.ShellyUtils;
34 import org.openhab.core.io.net.http.HttpClientFactory;
35 import org.openhab.core.net.HttpServiceUtil;
36 import org.openhab.core.net.NetworkAddressService;
37 import org.openhab.core.thing.Thing;
38 import org.openhab.core.thing.ThingTypeUID;
39 import org.openhab.core.thing.binding.BaseThingHandlerFactory;
40 import org.openhab.core.thing.binding.ThingHandler;
41 import org.openhab.core.thing.binding.ThingHandlerFactory;
42 import org.osgi.service.component.ComponentContext;
43 import org.osgi.service.component.annotations.Activate;
44 import org.osgi.service.component.annotations.Component;
45 import org.osgi.service.component.annotations.Reference;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import io.reactivex.annotations.NonNull;
50
51 /**
52  * The {@link ShellyHandlerFactory} is responsible for creating things and thing handlers.
53  *
54  * @author Markus Michels - Initial contribution
55  */
56 @NonNullByDefault
57 @Component(service = { ThingHandlerFactory.class, ShellyHandlerFactory.class }, configurationPid = "binding.shelly")
58 public class ShellyHandlerFactory extends BaseThingHandlerFactory {
59     private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = ShellyBindingConstants.SUPPORTED_THING_TYPES_UIDS;
60
61     private final Logger logger = LoggerFactory.getLogger(ShellyHandlerFactory.class);
62     private final HttpClient httpClient;
63     private final ShellyTranslationProvider messages;
64     private final ShellyCoapServer coapServer;
65
66     private final Map<String, ShellyBaseHandler> deviceListeners = new ConcurrentHashMap<>();
67     private ShellyBindingConfiguration bindingConfig = new ShellyBindingConfiguration();
68     private String localIP = "";
69     private int httpPort = -1;
70
71     /**
72      * Activate the bundle: save properties
73      *
74      * @param componentContext
75      * @param configProperties set of properties from cfg (use same names as in
76      *            thing config)
77      */
78     @Activate
79     public ShellyHandlerFactory(@Reference NetworkAddressService networkAddressService,
80             @Reference ShellyTranslationProvider translationProvider, @Reference HttpClientFactory httpClientFactory,
81             ComponentContext componentContext, Map<String, Object> configProperties) {
82         logger.debug("Activate Shelly HandlerFactory");
83         super.activate(componentContext);
84         messages = translationProvider;
85         // Save bindingConfig & pass it to all registered listeners
86         bindingConfig.updateFromProperties(configProperties);
87
88         localIP = bindingConfig.localIP;
89         if (localIP.isEmpty()) {
90             localIP = ShellyUtils.getString(networkAddressService.getPrimaryIpv4HostAddress());
91         }
92         if (localIP.isEmpty()) {
93             logger.warn("{}", messages.get("message.init.noipaddress"));
94         }
95
96         this.httpClient = httpClientFactory.getCommonHttpClient();
97         httpPort = HttpServiceUtil.getHttpServicePort(componentContext.getBundleContext());
98         if (httpPort == -1) {
99             httpPort = 8080;
100         }
101         logger.debug("Using OH HTTP port {}", httpPort);
102
103         this.coapServer = new ShellyCoapServer();
104
105         // Promote Shelly Manager usage
106         logger.info("{}", messages.get("status.managerstarted", localIP, httpPort));
107     }
108
109     @Override
110     public boolean supportsThingType(ThingTypeUID thingTypeUID) {
111         return SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID);
112     }
113
114     @Override
115     protected @Nullable ThingHandler createHandler(Thing thing) {
116         ThingTypeUID thingTypeUID = thing.getThingTypeUID();
117         String thingType = thingTypeUID.getId();
118         ShellyBaseHandler handler = null;
119
120         if (thingType.equals(THING_TYPE_SHELLYPROTECTED_STR)) {
121             logger.debug("{}: Create new thing of type {} using ShellyProtectedHandler", thing.getLabel(),
122                     thingTypeUID.toString());
123             handler = new ShellyProtectedHandler(thing, messages, bindingConfig, coapServer, localIP, httpPort,
124                     httpClient);
125         } else if (thingType.equals(THING_TYPE_SHELLYBULB_STR) || thingType.equals(THING_TYPE_SHELLYDUO_STR)
126                 || thingType.equals(THING_TYPE_SHELLYRGBW2_COLOR_STR)
127                 || thingType.equals(THING_TYPE_SHELLYRGBW2_WHITE_STR)
128                 || thingType.equals(THING_TYPE_SHELLYDUORGBW_STR)) {
129             logger.debug("{}: Create new thing of type {} using ShellyLightHandler", thing.getLabel(),
130                     thingTypeUID.toString());
131             handler = new ShellyLightHandler(thing, messages, bindingConfig, coapServer, localIP, httpPort, httpClient);
132         } else if (SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID)) {
133             logger.debug("{}: Create new thing of type {} using ShellyRelayHandler", thing.getLabel(),
134                     thingTypeUID.toString());
135             handler = new ShellyRelayHandler(thing, messages, bindingConfig, coapServer, localIP, httpPort, httpClient);
136         }
137
138         if (handler != null) {
139             String uid = thing.getUID().getAsString();
140             deviceListeners.put(uid, handler);
141             logger.debug("Thing handler for uid {} added, total things = {}", uid, deviceListeners.size());
142             return handler;
143         }
144
145         logger.debug("Unable to create Thing Handler instance!");
146         return null;
147     }
148
149     public Map<String, ShellyManagerInterface> getThingHandlers() {
150         return new HashMap<>(deviceListeners);
151     }
152
153     /**
154      * Remove handler of things.
155      */
156     @Override
157     protected synchronized void removeHandler(@NonNull ThingHandler thingHandler) {
158         if (thingHandler instanceof ShellyBaseHandler) {
159             String uid = thingHandler.getThing().getUID().getAsString();
160             deviceListeners.remove(uid);
161         }
162     }
163
164     /**
165      * Dispatch event to registered devices.
166      *
167      * @param deviceName
168      * @param componentIndex Index of component, e.g. 2 for relay2
169      * @param eventType Type of event, e.g. light
170      * @param parameters Input parameters from URL, e.g. on sensor reports
171      */
172     public void onEvent(String ipAddress, String deviceName, String componentIndex, String eventType,
173             Map<String, String> parameters) {
174         logger.trace("{}: Dispatch event to thing handler", deviceName);
175         for (Map.Entry<String, ShellyBaseHandler> listener : deviceListeners.entrySet()) {
176             ShellyBaseHandler thingHandler = listener.getValue();
177             if (thingHandler.onEvent(ipAddress, deviceName, componentIndex, eventType, parameters)) {
178                 // event processed
179                 return;
180             }
181         }
182     }
183
184     public ShellyBindingConfiguration getBindingConfig() {
185         return bindingConfig;
186     }
187 }