]> git.basschouten.com Git - openhab-addons.git/blob
f907a5cd32373f9a48675ac7656fc33783f85355
[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                 // widget: DynamicAwning
161                 // widget: UpDownHorizontalAwning
162                 deviceDiscovered(device, THING_TYPE_AWNING, place);
163                 break;
164             case CLASS_CONTACT_SENSOR:
165                 // widget: ContactSensor
166                 deviceDiscovered(device, THING_TYPE_CONTACTSENSOR, place);
167                 break;
168             case CLASS_CURTAIN:
169                 deviceDiscovered(device, THING_TYPE_CURTAIN, place);
170                 break;
171             case CLASS_EXTERIOR_SCREEN:
172                 // widget: PositionableScreen
173                 deviceDiscovered(device, THING_TYPE_EXTERIORSCREEN, place);
174                 break;
175             case CLASS_EXTERIOR_VENETIAN_BLIND:
176                 // widget: PositionableExteriorVenetianBlind
177                 deviceDiscovered(device, THING_TYPE_EXTERIORVENETIANBLIND, place);
178                 break;
179             case CLASS_GARAGE_DOOR:
180                 deviceDiscovered(device, THING_TYPE_GARAGEDOOR, place);
181                 break;
182             case CLASS_LIGHT:
183                 if ("DimmerLight".equals(device.getWidget())) {
184                     // widget: DimmerLight
185                     deviceDiscovered(device, THING_TYPE_DIMMER_LIGHT, place);
186                 } else {
187                     // widget: TimedOnOffLight
188                     // widget: StatefulOnOffLight
189                     deviceDiscovered(device, THING_TYPE_LIGHT, place);
190                 }
191                 break;
192             case CLASS_LIGHT_SENSOR:
193                 deviceDiscovered(device, THING_TYPE_LIGHTSENSOR, place);
194                 break;
195             case CLASS_OCCUPANCY_SENSOR:
196                 // widget: OccupancySensor
197                 deviceDiscovered(device, THING_TYPE_OCCUPANCYSENSOR, place);
198                 break;
199             case CLASS_ON_OFF:
200                 // widget: StatefulOnOff
201                 deviceDiscovered(device, THING_TYPE_ONOFF, place);
202                 break;
203             case CLASS_ROLLER_SHUTTER:
204                 if (isSilentRollerShutter(device)) {
205                     // widget: PositionableRollerShutterWithLowSpeedManagement
206                     deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER_SILENT, place);
207                 } else if (isUnoRollerShutter(device)) {
208                     // widget: PositionableRollerShutterUno
209                     deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER_UNO, place);
210                 } else {
211                     // widget: PositionableRollerShutter
212                     // widget: PositionableTiltedRollerShutter
213                     deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER, place);
214                 }
215                 break;
216             case CLASS_SHUTTER:
217                 // widget: DynamicShutter
218                 deviceDiscovered(device, THING_TYPE_SHUTTER, place);
219                 break;
220             case CLASS_SCREEN:
221                 // widget: PositionableTiltedScreen
222                 deviceDiscovered(device, THING_TYPE_SCREEN, place);
223                 break;
224             case CLASS_SMOKE_SENSOR:
225                 // widget: SmokeSensor
226                 deviceDiscovered(device, THING_TYPE_SMOKESENSOR, place);
227                 break;
228             case CLASS_VENETIAN_BLIND:
229                 // widget: DynamicVenetianBlind
230                 if (hasCommmand(device, "setOrientation")) {
231                     deviceDiscovered(device, THING_TYPE_VENETIANBLIND, place);
232                 } else {
233                     // simple venetian blind without orientation
234                     deviceDiscovered(device, THING_TYPE_SHUTTER, place);
235                 }
236                 break;
237             case CLASS_WINDOW:
238                 // widget: PositionableTiltedWindow
239                 deviceDiscovered(device, THING_TYPE_WINDOW, place);
240                 break;
241             case CLASS_ALARM:
242                 if (device.getDeviceURL().startsWith("internal:")) {
243                     // widget: TSKAlarmController
244                     deviceDiscovered(device, THING_TYPE_INTERNAL_ALARM, place);
245                 } else if ("MyFoxAlarmController".equals(device.getWidget())) {
246                     // widget: MyFoxAlarmController
247                     deviceDiscovered(device, THING_TYPE_MYFOX_ALARM, place);
248                 } else {
249                     deviceDiscovered(device, THING_TYPE_EXTERNAL_ALARM, place);
250                 }
251                 break;
252             case CLASS_POD:
253                 if (hasState(device, CYCLIC_BUTTON_STATE)) {
254                     deviceDiscovered(device, THING_TYPE_POD, place);
255                 }
256                 break;
257             case CLASS_HEATING_SYSTEM:
258                 if ("SomfyThermostat".equals(device.getWidget())) {
259                     deviceDiscovered(device, THING_TYPE_THERMOSTAT, place);
260                 } else if ("ValveHeatingTemperatureInterface".equals(device.getWidget())) {
261                     deviceDiscovered(device, THING_TYPE_VALVE_HEATING_SYSTEM, place);
262                 } else if (isOnOffHeatingSystem(device)) {
263                     deviceDiscovered(device, THING_TYPE_ONOFF_HEATING_SYSTEM, place);
264                 } else if (isZwaveHeatingSystem(device)) {
265                     deviceDiscovered(device, THING_TYPE_ZWAVE_HEATING_SYSTEM, place);
266                 } else {
267                     logUnsupportedDevice(device);
268                 }
269                 break;
270             case CLASS_EXTERIOR_HEATING_SYSTEM:
271                 if ("DimmerExteriorHeating".equals(device.getWidget())) {
272                     // widget: DimmerExteriorHeating
273                     deviceDiscovered(device, THING_TYPE_EXTERIOR_HEATING_SYSTEM, place);
274                 } else {
275                     logUnsupportedDevice(device);
276                 }
277                 break;
278             case CLASS_HUMIDITY_SENSOR:
279                 if (hasState(device, WATER_DETECTION_STATE)) {
280                     deviceDiscovered(device, THING_TYPE_WATERSENSOR, place);
281                 } else {
282                     // widget: RelativeHumiditySensor
283                     deviceDiscovered(device, THING_TYPE_HUMIDITYSENSOR, place);
284                 }
285             case CLASS_DOOR_LOCK:
286                 // widget: UnlockDoorLockWithUnknownPosition
287                 deviceDiscovered(device, THING_TYPE_DOOR_LOCK, place);
288                 break;
289             case CLASS_PERGOLA:
290                 if ("BioclimaticPergola".equals(device.getWidget())) {
291                     // widget: BioclimaticPergola
292                     deviceDiscovered(device, THING_TYPE_BIOCLIMATIC_PERGOLA, place);
293                 } else {
294                     deviceDiscovered(device, THING_TYPE_PERGOLA, place);
295                 }
296                 break;
297             case CLASS_WINDOW_HANDLE:
298                 // widget: ThreeWayWindowHandle
299                 deviceDiscovered(device, THING_TYPE_WINDOW_HANDLE, place);
300                 break;
301             case CLASS_TEMPERATURE_SENSOR:
302                 // widget: TemperatureSensor
303                 deviceDiscovered(device, THING_TYPE_TEMPERATURESENSOR, place);
304                 break;
305             case CLASS_GATE:
306                 deviceDiscovered(device, THING_TYPE_GATE, place);
307                 break;
308             case CLASS_ELECTRICITY_SENSOR:
309                 if (hasEnergyConsumption(device)) {
310                     deviceDiscovered(device, THING_TYPE_ELECTRICITYSENSOR, place);
311                 } else {
312                     logUnsupportedDevice(device);
313                 }
314                 break;
315             case CLASS_WATER_HEATING_SYSTEM:
316                 // widget: DomesticHotWaterProduction
317                 if ("DomesticHotWaterProduction".equals(device.getWidget())) {
318                     deviceDiscovered(device, THING_TYPE_WATERHEATINGSYSTEM, place);
319                 } else {
320                     logUnsupportedDevice(device);
321                 }
322                 break;
323             case CLASS_DOCK:
324                 // widget: Dock
325                 deviceDiscovered(device, THING_TYPE_DOCK, place);
326                 break;
327             case CLASS_SIREN:
328                 deviceDiscovered(device, THING_TYPE_SIREN, place);
329                 break;
330             case CLASS_ADJUSTABLE_SLATS_ROLLER_SHUTTER:
331                 deviceDiscovered(device, THING_TYPE_ADJUSTABLE_SLATS_ROLLERSHUTTER, place);
332                 break;
333             case CLASS_CAMERA:
334                 if (hasMyfoxShutter(device)) {
335                     // widget: MyFoxSecurityCamera
336                     deviceDiscovered(device, THING_TYPE_MYFOX_CAMERA, place);
337                 } else {
338                     logUnsupportedDevice(device);
339                 }
340                 break;
341             case CLASS_HITACHI_HEATING_SYSTEM:
342                 if ("HitachiAirToWaterHeatingZone".equals(device.getWidget())) {
343                     // widget: HitachiAirToWaterHeatingZone
344                     deviceDiscovered(device, THING_TYPE_HITACHI_ATWHZ, place);
345                 } else if ("HitachiAirToWaterMainComponent".equals(device.getWidget())) {
346                     // widget: HitachiAirToWaterMainComponent
347                     deviceDiscovered(device, THING_TYPE_HITACHI_ATWMC, place);
348                 } else if ("HitachiDHW".equals(device.getWidget())) {
349                     // widget: HitachiDHW
350                     deviceDiscovered(device, THING_TYPE_HITACHI_DHW, place);
351                 } else {
352                     logUnsupportedDevice(device);
353                 }
354                 break;
355             case CLASS_RAIN_SENSOR:
356                 if ("RainSensor".equals(device.getWidget())) {
357                     // widget: RainSensor
358                     deviceDiscovered(device, THING_TYPE_RAINSENSOR, place);
359                 } else {
360                     logUnsupportedDevice(device);
361                 }
362             case THING_PROTOCOL_GATEWAY:
363             case THING_REMOTE_CONTROLLER:
364                 // widget: AlarmRemoteController
365             case THING_NETWORK_COMPONENT:
366             case THING_GENERIC:
367                 // widget: unknown
368                 break;
369
370             default:
371                 logUnsupportedDevice(device);
372         }
373     }
374
375     private @Nullable String getPlaceLabel(SomfyTahomaSetup setup, String oid) {
376         SomfyTahomaRootPlace root = setup.getRootPlace();
377         if (!oid.isEmpty() && root != null) {
378             for (SomfyTahomaSubPlace place : root.getSubPlaces()) {
379                 if (oid.equals(place.getOid())) {
380                     return place.getLabel();
381                 }
382             }
383         }
384         return null;
385     }
386
387     private boolean isStateLess(SomfyTahomaDevice device) {
388         return device.getStates().isEmpty() || (device.getStates().size() == 1 && hasState(device, STATUS_STATE));
389     }
390
391     private void logUnsupportedDevice(SomfyTahomaDevice device) {
392         if (!isStateLess(device)) {
393             logger.debug("Detected a new unsupported device: {} with widgetName: {}", device.getUiClass(),
394                     device.getWidget());
395             logger.debug("If you want to add the support, please create a new issue and attach the information below");
396             logger.debug("Device definition:\n{}", device.getDefinition());
397
398             StringBuilder sb = new StringBuilder().append('\n');
399             for (SomfyTahomaState state : device.getStates()) {
400                 sb.append(state.toString()).append('\n');
401             }
402             logger.debug("Current device states: {}", sb);
403         }
404     }
405
406     private boolean hasState(SomfyTahomaDevice device, String state) {
407         return device.getDefinition().getStates().stream().anyMatch(st -> state.equals(st.getQualifiedName()));
408     }
409
410     private boolean hasMyfoxShutter(SomfyTahomaDevice device) {
411         return hasState(device, MYFOX_SHUTTER_STATUS_STATE);
412     }
413
414     private boolean hasEnergyConsumption(SomfyTahomaDevice device) {
415         return hasState(device, ENERGY_CONSUMPTION_STATE);
416     }
417
418     private boolean isSilentRollerShutter(SomfyTahomaDevice device) {
419         return "PositionableRollerShutterWithLowSpeedManagement".equals(device.getWidget());
420     }
421
422     private boolean isUnoRollerShutter(SomfyTahomaDevice device) {
423         return "PositionableRollerShutterUno".equals(device.getWidget());
424     }
425
426     private boolean isOnOffHeatingSystem(SomfyTahomaDevice device) {
427         return hasCommmand(device, COMMAND_SET_HEATINGLEVEL);
428     }
429
430     private boolean isZwaveHeatingSystem(SomfyTahomaDevice device) {
431         return hasState(device, ZWAVE_SET_POINT_TYPE_STATE);
432     }
433
434     private boolean hasCommmand(SomfyTahomaDevice device, String command) {
435         return device.getDefinition().getCommands().stream().anyMatch(cmd -> command.equals(cmd.getCommandName()));
436     }
437
438     private void deviceDiscovered(SomfyTahomaDevice device, ThingTypeUID thingTypeUID, @Nullable String place) {
439         String label = device.getLabel();
440         if (place != null && !place.isBlank()) {
441             label += " (" + place + ")";
442         }
443         deviceDiscovered(label, device.getDeviceURL(), device.getOid(), thingTypeUID,
444                 hasState(device, RSSI_LEVEL_STATE));
445     }
446
447     private void deviceDiscovered(String label, String deviceURL, String oid, ThingTypeUID thingTypeUID, boolean rssi) {
448         Map<String, Object> properties = new HashMap<>();
449         properties.put("url", deviceURL);
450         properties.put(NAME_STATE, label);
451         if (rssi) {
452             properties.put(RSSI_LEVEL_STATE, "-1");
453         }
454
455         SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
456         if (localBridgeHandler != null) {
457             ThingUID thingUID = new ThingUID(thingTypeUID, localBridgeHandler.getThing().getUID(), oid);
458
459             logger.debug("Detected a/an {} - label: {} oid: {}", thingTypeUID.getId(), label, oid);
460             thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
461                     .withProperties(properties).withRepresentationProperty("url").withLabel(label)
462                     .withBridge(localBridgeHandler.getThing().getUID()).build());
463         }
464     }
465
466     private void actionGroupDiscovered(String label, String deviceURL, String oid) {
467         deviceDiscovered(label, deviceURL, oid, THING_TYPE_ACTIONGROUP, false);
468     }
469
470     private void gatewayDiscovered(SomfyTahomaGateway gw) {
471         Map<String, Object> properties = new HashMap<>(1);
472         String type = gatewayTypes.getOrDefault(gw.getType(), "UNKNOWN");
473         String id = gw.getGatewayId();
474         properties.put("id", id);
475         properties.put("type", type);
476
477         SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
478         if (localBridgeHandler != null) {
479             ThingUID thingUID = new ThingUID(THING_TYPE_GATEWAY, localBridgeHandler.getThing().getUID(), id);
480
481             logger.debug("Detected a gateway with id: {} and type: {}", id, type);
482             thingDiscovered(
483                     DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_GATEWAY).withProperties(properties)
484                             .withRepresentationProperty("id").withLabel("Somfy Gateway (" + type + ")")
485                             .withBridge(localBridgeHandler.getThing().getUID()).build());
486         }
487     }
488 }