]> git.basschouten.com Git - openhab-addons.git/blob
58e1a185d2429ff1fc1174095131f4bea5979252
[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.somfytahoma.internal.discovery;
14
15 import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*;
16
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.somfytahoma.internal.handler.SomfyTahomaBridgeHandler;
27 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaActionGroup;
28 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaDevice;
29 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaGateway;
30 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaRootPlace;
31 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaSetup;
32 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaState;
33 import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaSubPlace;
34 import org.openhab.core.config.discovery.AbstractDiscoveryService;
35 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
36 import org.openhab.core.config.discovery.DiscoveryService;
37 import org.openhab.core.thing.ThingStatus;
38 import org.openhab.core.thing.ThingTypeUID;
39 import org.openhab.core.thing.ThingUID;
40 import org.openhab.core.thing.binding.ThingHandler;
41 import org.openhab.core.thing.binding.ThingHandlerService;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * The {@link SomfyTahomaItemDiscoveryService} discovers rollershutters and
47  * action groups associated with your TahomaLink cloud account.
48  *
49  * @author Ondrej Pecta - Initial contribution
50  * @author Laurent Garnier - Include the place into the inbox label (when defined for the device)
51  */
52 @NonNullByDefault
53 public class SomfyTahomaItemDiscoveryService extends AbstractDiscoveryService
54         implements DiscoveryService, ThingHandlerService {
55
56     private static final int DISCOVERY_TIMEOUT_SEC = 10;
57     private static final int DISCOVERY_REFRESH_SEC = 3600;
58
59     private final Logger logger = LoggerFactory.getLogger(SomfyTahomaItemDiscoveryService.class);
60
61     private @Nullable SomfyTahomaBridgeHandler bridgeHandler;
62
63     private @Nullable ScheduledFuture<?> discoveryJob;
64
65     public SomfyTahomaItemDiscoveryService() {
66         super(DISCOVERY_TIMEOUT_SEC);
67         logger.debug("Creating discovery service");
68     }
69
70     @Override
71     public void activate() {
72         super.activate(null);
73     }
74
75     @Override
76     public void deactivate() {
77         super.deactivate();
78     }
79
80     @Override
81     public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
82         if (handler instanceof SomfyTahomaBridgeHandler) {
83             bridgeHandler = (SomfyTahomaBridgeHandler) handler;
84         }
85     }
86
87     @Override
88     public @Nullable ThingHandler getThingHandler() {
89         return bridgeHandler;
90     }
91
92     @Override
93     protected void startBackgroundDiscovery() {
94         logger.debug("Starting SomfyTahoma background discovery");
95
96         ScheduledFuture<?> localDiscoveryJob = discoveryJob;
97         if (localDiscoveryJob == null || localDiscoveryJob.isCancelled()) {
98             discoveryJob = scheduler.scheduleWithFixedDelay(this::runDiscovery, 10, DISCOVERY_REFRESH_SEC,
99                     TimeUnit.SECONDS);
100         }
101     }
102
103     @Override
104     protected void stopBackgroundDiscovery() {
105         logger.debug("Stopping SomfyTahoma background discovery");
106         ScheduledFuture<?> localDiscoveryJob = discoveryJob;
107         if (localDiscoveryJob != null && !localDiscoveryJob.isCancelled()) {
108             localDiscoveryJob.cancel(true);
109         }
110     }
111
112     @Override
113     public Set<ThingTypeUID> getSupportedThingTypes() {
114         return SUPPORTED_THING_TYPES_UIDS;
115     }
116
117     @Override
118     protected void startScan() {
119         runDiscovery();
120     }
121
122     private synchronized void runDiscovery() {
123         logger.debug("Starting scanning for things...");
124
125         SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
126         if (localBridgeHandler != null && ThingStatus.ONLINE == localBridgeHandler.getThing().getStatus()) {
127             SomfyTahomaSetup setup = localBridgeHandler.getSetup();
128
129             if (setup == null) {
130                 return;
131             }
132
133             for (SomfyTahomaDevice device : setup.getDevices()) {
134                 discoverDevice(device, setup);
135             }
136             for (SomfyTahomaGateway gw : setup.getGateways()) {
137                 gatewayDiscovered(gw);
138             }
139
140             List<SomfyTahomaActionGroup> actions = localBridgeHandler.listActionGroups();
141
142             for (SomfyTahomaActionGroup group : actions) {
143                 String oid = group.getOid();
144                 String label = group.getLabel();
145
146                 // actiongroups use oid as deviceURL
147                 actionGroupDiscovered(label, oid, oid);
148             }
149         } else {
150             logger.debug("Cannot start discovery since the bridge is not online!");
151         }
152     }
153
154     private void discoverDevice(SomfyTahomaDevice device, SomfyTahomaSetup setup) {
155         logger.debug("url: {}", device.getDeviceURL());
156         String place = getPlaceLabel(setup, device.getPlaceOID());
157         switch (device.getUiClass()) {
158             case CLASS_AWNING:
159                 // widget: PositionableHorizontalAwning
160                 deviceDiscovered(device, THING_TYPE_AWNING, place);
161                 break;
162             case CLASS_CONTACT_SENSOR:
163                 // widget: ContactSensor
164                 deviceDiscovered(device, THING_TYPE_CONTACTSENSOR, place);
165                 break;
166             case CLASS_CURTAIN:
167                 deviceDiscovered(device, THING_TYPE_CURTAIN, place);
168                 break;
169             case CLASS_EXTERIOR_SCREEN:
170                 // widget: PositionableScreen
171                 deviceDiscovered(device, THING_TYPE_EXTERIORSCREEN, place);
172                 break;
173             case CLASS_EXTERIOR_VENETIAN_BLIND:
174                 // widget: PositionableExteriorVenetianBlind
175                 deviceDiscovered(device, THING_TYPE_EXTERIORVENETIANBLIND, place);
176                 break;
177             case CLASS_GARAGE_DOOR:
178                 deviceDiscovered(device, THING_TYPE_GARAGEDOOR, place);
179                 break;
180             case CLASS_LIGHT:
181                 if ("DimmerLight".equals(device.getWidget())) {
182                     // widget: DimmerLight
183                     deviceDiscovered(device, THING_TYPE_DIMMER_LIGHT, place);
184                 } else {
185                     // widget: TimedOnOffLight
186                     // widget: StatefulOnOffLight
187                     deviceDiscovered(device, THING_TYPE_LIGHT, place);
188                 }
189                 break;
190             case CLASS_LIGHT_SENSOR:
191                 deviceDiscovered(device, THING_TYPE_LIGHTSENSOR, place);
192                 break;
193             case CLASS_OCCUPANCY_SENSOR:
194                 // widget: OccupancySensor
195                 deviceDiscovered(device, THING_TYPE_OCCUPANCYSENSOR, place);
196                 break;
197             case CLASS_ON_OFF:
198                 // widget: StatefulOnOff
199                 deviceDiscovered(device, THING_TYPE_ONOFF, place);
200                 break;
201             case CLASS_ROLLER_SHUTTER:
202                 if (isSilentRollerShutter(device)) {
203                     // widget: PositionableRollerShutterWithLowSpeedManagement
204                     deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER_SILENT, place);
205                 } else if (isUnoRollerShutter(device)) {
206                     // widget: PositionableRollerShutterUno
207                     deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER_UNO, place);
208                 } else {
209                     // widget: PositionableRollerShutter
210                     // widget: PositionableTiltedRollerShutter
211                     deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER, place);
212                 }
213                 break;
214             case CLASS_SCREEN:
215                 // widget: PositionableTiltedScreen
216                 deviceDiscovered(device, THING_TYPE_SCREEN, place);
217                 break;
218             case CLASS_SMOKE_SENSOR:
219                 // widget: SmokeSensor
220                 deviceDiscovered(device, THING_TYPE_SMOKESENSOR, place);
221                 break;
222             case CLASS_VENETIAN_BLIND:
223                 deviceDiscovered(device, THING_TYPE_VENETIANBLIND, place);
224                 break;
225             case CLASS_WINDOW:
226                 // widget: PositionableTiltedWindow
227                 deviceDiscovered(device, THING_TYPE_WINDOW, place);
228                 break;
229             case CLASS_ALARM:
230                 if (device.getDeviceURL().startsWith("internal:")) {
231                     // widget: TSKAlarmController
232                     deviceDiscovered(device, THING_TYPE_INTERNAL_ALARM, place);
233                 } else if ("MyFoxAlarmController".equals(device.getWidget())) {
234                     // widget: MyFoxAlarmController
235                     deviceDiscovered(device, THING_TYPE_MYFOX_ALARM, place);
236                 } else {
237                     deviceDiscovered(device, THING_TYPE_EXTERNAL_ALARM, place);
238                 }
239                 break;
240             case CLASS_POD:
241                 if (hasState(device, CYCLIC_BUTTON_STATE)) {
242                     deviceDiscovered(device, THING_TYPE_POD, place);
243                 }
244                 break;
245             case CLASS_HEATING_SYSTEM:
246                 if ("SomfyThermostat".equals(device.getWidget())) {
247                     deviceDiscovered(device, THING_TYPE_THERMOSTAT, place);
248                 } else if ("ValveHeatingTemperatureInterface".equals(device.getWidget())) {
249                     deviceDiscovered(device, THING_TYPE_VALVE_HEATING_SYSTEM, place);
250                 } else if (isOnOffHeatingSystem(device)) {
251                     deviceDiscovered(device, THING_TYPE_ONOFF_HEATING_SYSTEM, place);
252                 } else if (isZwaveHeatingSystem(device)) {
253                     deviceDiscovered(device, THING_TYPE_ZWAVE_HEATING_SYSTEM, place);
254                 } else {
255                     logUnsupportedDevice(device);
256                 }
257                 break;
258             case CLASS_EXTERIOR_HEATING_SYSTEM:
259                 if ("DimmerExteriorHeating".equals(device.getWidget())) {
260                     // widget: DimmerExteriorHeating
261                     deviceDiscovered(device, THING_TYPE_EXTERIOR_HEATING_SYSTEM, place);
262                 } else {
263                     logUnsupportedDevice(device);
264                 }
265                 break;
266             case CLASS_HUMIDITY_SENSOR:
267                 if (hasState(device, WATER_DETECTION_STATE)) {
268                     deviceDiscovered(device, THING_TYPE_WATERSENSOR, place);
269                 } else {
270                     // widget: RelativeHumiditySensor
271                     deviceDiscovered(device, THING_TYPE_HUMIDITYSENSOR, place);
272                 }
273             case CLASS_DOOR_LOCK:
274                 // widget: UnlockDoorLockWithUnknownPosition
275                 deviceDiscovered(device, THING_TYPE_DOOR_LOCK, place);
276                 break;
277             case CLASS_PERGOLA:
278                 if ("BioclimaticPergola".equals(device.getWidget())) {
279                     // widget: BioclimaticPergola
280                     deviceDiscovered(device, THING_TYPE_BIOCLIMATIC_PERGOLA, place);
281                 } else {
282                     deviceDiscovered(device, THING_TYPE_PERGOLA, place);
283                 }
284                 break;
285             case CLASS_WINDOW_HANDLE:
286                 // widget: ThreeWayWindowHandle
287                 deviceDiscovered(device, THING_TYPE_WINDOW_HANDLE, place);
288                 break;
289             case CLASS_TEMPERATURE_SENSOR:
290                 // widget: TemperatureSensor
291                 deviceDiscovered(device, THING_TYPE_TEMPERATURESENSOR, place);
292                 break;
293             case CLASS_GATE:
294                 deviceDiscovered(device, THING_TYPE_GATE, place);
295                 break;
296             case CLASS_ELECTRICITY_SENSOR:
297                 if (hasEnergyConsumption(device)) {
298                     deviceDiscovered(device, THING_TYPE_ELECTRICITYSENSOR, place);
299                 } else {
300                     logUnsupportedDevice(device);
301                 }
302                 break;
303             case CLASS_WATER_HEATING_SYSTEM:
304                 // widget: DomesticHotWaterProduction
305                 if ("DomesticHotWaterProduction".equals(device.getWidget())) {
306                     deviceDiscovered(device, THING_TYPE_WATERHEATINGSYSTEM, place);
307                 } else {
308                     logUnsupportedDevice(device);
309                 }
310                 break;
311             case CLASS_DOCK:
312                 // widget: Dock
313                 deviceDiscovered(device, THING_TYPE_DOCK, place);
314                 break;
315             case CLASS_SIREN:
316                 deviceDiscovered(device, THING_TYPE_SIREN, place);
317                 break;
318             case CLASS_ADJUSTABLE_SLATS_ROLLER_SHUTTER:
319                 deviceDiscovered(device, THING_TYPE_ADJUSTABLE_SLATS_ROLLERSHUTTER, place);
320                 break;
321             case CLASS_CAMERA:
322                 if (hasMyfoxShutter(device)) {
323                     // widget: MyFoxSecurityCamera
324                     deviceDiscovered(device, THING_TYPE_MYFOX_CAMERA, place);
325                 } else {
326                     logUnsupportedDevice(device);
327                 }
328                 break;
329             case CLASS_HITACHI_HEATING_SYSTEM:
330                 if ("HitachiAirToWaterHeatingZone".equals(device.getWidget())) {
331                     // widget: HitachiAirToWaterHeatingZone
332                     deviceDiscovered(device, THING_TYPE_HITACHI_ATWHZ, place);
333                 } else if ("HitachiAirToWaterMainComponent".equals(device.getWidget())) {
334                     // widget: HitachiAirToWaterMainComponent
335                     deviceDiscovered(device, THING_TYPE_HITACHI_ATWMC, place);
336                 } else if ("HitachiDHW".equals(device.getWidget())) {
337                     // widget: HitachiDHW
338                     deviceDiscovered(device, THING_TYPE_HITACHI_DHW, place);
339                 } else {
340                     logUnsupportedDevice(device);
341                 }
342                 break;
343             case CLASS_RAIN_SENSOR:
344                 if ("RainSensor".equals(device.getWidget())) {
345                     // widget: RainSensor
346                     deviceDiscovered(device, THING_TYPE_RAINSENSOR, place);
347                 } else {
348                     logUnsupportedDevice(device);
349                 }
350             case THING_PROTOCOL_GATEWAY:
351             case THING_REMOTE_CONTROLLER:
352                 // widget: AlarmRemoteController
353             case THING_NETWORK_COMPONENT:
354             case THING_GENERIC:
355                 // widget: unknown
356                 break;
357
358             default:
359                 logUnsupportedDevice(device);
360         }
361     }
362
363     private @Nullable String getPlaceLabel(SomfyTahomaSetup setup, String oid) {
364         SomfyTahomaRootPlace root = setup.getRootPlace();
365         if (!oid.isEmpty() && root != null) {
366             for (SomfyTahomaSubPlace place : root.getSubPlaces()) {
367                 if (oid.equals(place.getOid())) {
368                     return place.getLabel();
369                 }
370             }
371         }
372         return null;
373     }
374
375     private boolean isStateLess(SomfyTahomaDevice device) {
376         return device.getStates().isEmpty() || (device.getStates().size() == 1 && hasState(device, STATUS_STATE));
377     }
378
379     private void logUnsupportedDevice(SomfyTahomaDevice device) {
380         if (!isStateLess(device)) {
381             logger.info("Detected a new unsupported device: {} with widgetName: {}", device.getUiClass(),
382                     device.getWidget());
383             logger.info("If you want to add the support, please create a new issue and attach the information below");
384             logger.info("Device definition:\n{}", device.getDefinition());
385
386             StringBuilder sb = new StringBuilder().append('\n');
387             for (SomfyTahomaState state : device.getStates()) {
388                 sb.append(state.toString()).append('\n');
389             }
390             logger.info("Current device states: {}", sb);
391         }
392     }
393
394     private boolean hasState(SomfyTahomaDevice device, String state) {
395         return device.getDefinition().getStates().stream().anyMatch(st -> state.equals(st.getQualifiedName()));
396     }
397
398     private boolean hasMyfoxShutter(SomfyTahomaDevice device) {
399         return hasState(device, MYFOX_SHUTTER_STATUS_STATE);
400     }
401
402     private boolean hasEnergyConsumption(SomfyTahomaDevice device) {
403         return hasState(device, ENERGY_CONSUMPTION_STATE);
404     }
405
406     private boolean isSilentRollerShutter(SomfyTahomaDevice device) {
407         return "PositionableRollerShutterWithLowSpeedManagement".equals(device.getWidget());
408     }
409
410     private boolean isUnoRollerShutter(SomfyTahomaDevice device) {
411         return "PositionableRollerShutterUno".equals(device.getWidget());
412     }
413
414     private boolean isOnOffHeatingSystem(SomfyTahomaDevice device) {
415         return hasCommmand(device, COMMAND_SET_HEATINGLEVEL);
416     }
417
418     private boolean isZwaveHeatingSystem(SomfyTahomaDevice device) {
419         return hasState(device, ZWAVE_SET_POINT_TYPE_STATE);
420     }
421
422     private boolean hasCommmand(SomfyTahomaDevice device, String command) {
423         return device.getDefinition().getCommands().stream().anyMatch(cmd -> command.equals(cmd.getCommandName()));
424     }
425
426     private void deviceDiscovered(SomfyTahomaDevice device, ThingTypeUID thingTypeUID, @Nullable String place) {
427         String label = device.getLabel();
428         if (place != null && !place.isBlank()) {
429             label += " (" + place + ")";
430         }
431         deviceDiscovered(label, device.getDeviceURL(), device.getOid(), thingTypeUID,
432                 hasState(device, RSSI_LEVEL_STATE));
433     }
434
435     private void deviceDiscovered(String label, String deviceURL, String oid, ThingTypeUID thingTypeUID, boolean rssi) {
436         Map<String, Object> properties = new HashMap<>();
437         properties.put("url", deviceURL);
438         properties.put(NAME_STATE, label);
439         if (rssi) {
440             properties.put(RSSI_LEVEL_STATE, "-1");
441         }
442
443         SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
444         if (localBridgeHandler != null) {
445             ThingUID thingUID = new ThingUID(thingTypeUID, localBridgeHandler.getThing().getUID(), oid);
446
447             logger.debug("Detected a/an {} - label: {} oid: {}", thingTypeUID.getId(), label, oid);
448             thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
449                     .withProperties(properties).withRepresentationProperty("url").withLabel(label)
450                     .withBridge(localBridgeHandler.getThing().getUID()).build());
451         }
452     }
453
454     private void actionGroupDiscovered(String label, String deviceURL, String oid) {
455         deviceDiscovered(label, deviceURL, oid, THING_TYPE_ACTIONGROUP, false);
456     }
457
458     private void gatewayDiscovered(SomfyTahomaGateway gw) {
459         Map<String, Object> properties = new HashMap<>(1);
460         String type = gatewayTypes.getOrDefault(gw.getType(), "UNKNOWN");
461         String id = gw.getGatewayId();
462         properties.put("id", id);
463         properties.put("type", type);
464
465         SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
466         if (localBridgeHandler != null) {
467             ThingUID thingUID = new ThingUID(THING_TYPE_GATEWAY, localBridgeHandler.getThing().getUID(), id);
468
469             logger.debug("Detected a gateway with id: {} and type: {}", id, type);
470             thingDiscovered(
471                     DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_GATEWAY).withProperties(properties)
472                             .withRepresentationProperty("id").withLabel("Somfy Gateway (" + type + ")")
473                             .withBridge(localBridgeHandler.getThing().getUID()).build());
474         }
475     }
476 }