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