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