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