2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.somfytahoma.internal.discovery;
15 import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*;
17 import java.util.HashMap;
18 import java.util.List;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
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;
46 * The {@link SomfyTahomaItemDiscoveryService} discovers rollershutters and
47 * action groups associated with your TahomaLink cloud account.
49 * @author Ondrej Pecta - Initial contribution
50 * @author Laurent Garnier - Include the place into the inbox label (when defined for the device)
53 public class SomfyTahomaItemDiscoveryService extends AbstractDiscoveryService
54 implements DiscoveryService, ThingHandlerService {
56 private static final int DISCOVERY_TIMEOUT_SEC = 10;
57 private static final int DISCOVERY_REFRESH_SEC = 3600;
59 private final Logger logger = LoggerFactory.getLogger(SomfyTahomaItemDiscoveryService.class);
61 private @Nullable SomfyTahomaBridgeHandler bridgeHandler;
63 private @Nullable ScheduledFuture<?> discoveryJob;
65 public SomfyTahomaItemDiscoveryService() {
66 super(DISCOVERY_TIMEOUT_SEC);
67 logger.debug("Creating discovery service");
71 public void activate() {
76 public void deactivate() {
81 public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
82 if (handler instanceof SomfyTahomaBridgeHandler) {
83 bridgeHandler = (SomfyTahomaBridgeHandler) handler;
88 public @Nullable ThingHandler getThingHandler() {
93 protected void startBackgroundDiscovery() {
94 logger.debug("Starting SomfyTahoma background discovery");
96 ScheduledFuture<?> localDiscoveryJob = discoveryJob;
97 if (localDiscoveryJob == null || localDiscoveryJob.isCancelled()) {
98 discoveryJob = scheduler.scheduleWithFixedDelay(this::runDiscovery, 10, DISCOVERY_REFRESH_SEC,
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);
113 public Set<ThingTypeUID> getSupportedThingTypes() {
114 return SUPPORTED_THING_TYPES_UIDS;
118 protected void startScan() {
122 private synchronized void runDiscovery() {
123 logger.debug("Starting scanning for things...");
125 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
126 if (localBridgeHandler != null && ThingStatus.ONLINE == localBridgeHandler.getThing().getStatus()) {
127 SomfyTahomaSetup setup = localBridgeHandler.getSetup();
133 for (SomfyTahomaDevice device : setup.getDevices()) {
134 discoverDevice(device, setup);
136 for (SomfyTahomaGateway gw : setup.getGateways()) {
137 gatewayDiscovered(gw);
140 List<SomfyTahomaActionGroup> actions = localBridgeHandler.listActionGroups();
142 for (SomfyTahomaActionGroup group : actions) {
143 String oid = group.getOid();
144 String label = group.getLabel();
146 // actiongroups use oid as deviceURL
147 actionGroupDiscovered(label, oid, oid);
150 logger.debug("Cannot start discovery since the bridge is not online!");
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()) {
159 // widget: PositionableHorizontalAwning
160 // widget: DynamicAwning
161 // widget: UpDownHorizontalAwning
162 deviceDiscovered(device, THING_TYPE_AWNING, place);
164 case CLASS_CONTACT_SENSOR:
165 // widget: ContactSensor
166 deviceDiscovered(device, THING_TYPE_CONTACTSENSOR, place);
169 deviceDiscovered(device, THING_TYPE_CURTAIN, place);
171 case CLASS_EXTERIOR_SCREEN:
172 // widget: PositionableScreen
173 deviceDiscovered(device, THING_TYPE_EXTERIORSCREEN, place);
175 case CLASS_EXTERIOR_VENETIAN_BLIND:
176 // widget: PositionableExteriorVenetianBlind
177 deviceDiscovered(device, THING_TYPE_EXTERIORVENETIANBLIND, place);
179 case CLASS_GARAGE_DOOR:
180 deviceDiscovered(device, THING_TYPE_GARAGEDOOR, place);
183 if ("DimmerLight".equals(device.getWidget())) {
184 // widget: DimmerLight
185 deviceDiscovered(device, THING_TYPE_DIMMER_LIGHT, place);
187 // widget: TimedOnOffLight
188 // widget: StatefulOnOffLight
189 deviceDiscovered(device, THING_TYPE_LIGHT, place);
192 case CLASS_LIGHT_SENSOR:
193 deviceDiscovered(device, THING_TYPE_LIGHTSENSOR, place);
195 case CLASS_OCCUPANCY_SENSOR:
196 // widget: OccupancySensor
197 deviceDiscovered(device, THING_TYPE_OCCUPANCYSENSOR, place);
200 // widget: StatefulOnOff
201 deviceDiscovered(device, THING_TYPE_ONOFF, place);
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);
211 // widget: PositionableRollerShutter
212 // widget: PositionableTiltedRollerShutter
213 deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER, place);
217 // widget: DynamicShutter
218 deviceDiscovered(device, THING_TYPE_SHUTTER, place);
221 // widget: PositionableTiltedScreen
222 deviceDiscovered(device, THING_TYPE_SCREEN, place);
224 case CLASS_SMOKE_SENSOR:
225 // widget: SmokeSensor
226 deviceDiscovered(device, THING_TYPE_SMOKESENSOR, place);
228 case CLASS_VENETIAN_BLIND:
229 // widget: DynamicVenetianBlind
230 if (hasCommmand(device, "setOrientation")) {
231 deviceDiscovered(device, THING_TYPE_VENETIANBLIND, place);
233 // simple venetian blind without orientation
234 deviceDiscovered(device, THING_TYPE_SHUTTER, place);
238 // widget: PositionableTiltedWindow
239 deviceDiscovered(device, THING_TYPE_WINDOW, place);
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);
249 deviceDiscovered(device, THING_TYPE_EXTERNAL_ALARM, place);
253 if (hasState(device, CYCLIC_BUTTON_STATE)) {
254 deviceDiscovered(device, THING_TYPE_POD, place);
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);
267 logUnsupportedDevice(device);
270 case CLASS_EXTERIOR_HEATING_SYSTEM:
271 if ("DimmerExteriorHeating".equals(device.getWidget())) {
272 // widget: DimmerExteriorHeating
273 deviceDiscovered(device, THING_TYPE_EXTERIOR_HEATING_SYSTEM, place);
275 logUnsupportedDevice(device);
278 case CLASS_HUMIDITY_SENSOR:
279 if (hasState(device, WATER_DETECTION_STATE)) {
280 deviceDiscovered(device, THING_TYPE_WATERSENSOR, place);
282 // widget: RelativeHumiditySensor
283 deviceDiscovered(device, THING_TYPE_HUMIDITYSENSOR, place);
285 case CLASS_DOOR_LOCK:
286 // widget: UnlockDoorLockWithUnknownPosition
287 deviceDiscovered(device, THING_TYPE_DOOR_LOCK, place);
290 if ("BioclimaticPergola".equals(device.getWidget())) {
291 // widget: BioclimaticPergola
292 deviceDiscovered(device, THING_TYPE_BIOCLIMATIC_PERGOLA, place);
294 deviceDiscovered(device, THING_TYPE_PERGOLA, place);
297 case CLASS_WINDOW_HANDLE:
298 // widget: ThreeWayWindowHandle
299 deviceDiscovered(device, THING_TYPE_WINDOW_HANDLE, place);
301 case CLASS_TEMPERATURE_SENSOR:
302 // widget: TemperatureSensor
303 deviceDiscovered(device, THING_TYPE_TEMPERATURESENSOR, place);
306 deviceDiscovered(device, THING_TYPE_GATE, place);
308 case CLASS_ELECTRICITY_SENSOR:
309 if (hasEnergyConsumption(device)) {
310 deviceDiscovered(device, THING_TYPE_ELECTRICITYSENSOR, place);
312 logUnsupportedDevice(device);
315 case CLASS_WATER_HEATING_SYSTEM:
316 // widget: DomesticHotWaterProduction
317 if ("DomesticHotWaterProduction".equals(device.getWidget())) {
318 deviceDiscovered(device, THING_TYPE_WATERHEATINGSYSTEM, place);
320 logUnsupportedDevice(device);
325 deviceDiscovered(device, THING_TYPE_DOCK, place);
328 deviceDiscovered(device, THING_TYPE_SIREN, place);
330 case CLASS_ADJUSTABLE_SLATS_ROLLER_SHUTTER:
331 deviceDiscovered(device, THING_TYPE_ADJUSTABLE_SLATS_ROLLERSHUTTER, place);
334 if (hasMyfoxShutter(device)) {
335 // widget: MyFoxSecurityCamera
336 deviceDiscovered(device, THING_TYPE_MYFOX_CAMERA, place);
338 logUnsupportedDevice(device);
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);
352 logUnsupportedDevice(device);
355 case CLASS_RAIN_SENSOR:
356 if ("RainSensor".equals(device.getWidget())) {
357 // widget: RainSensor
358 deviceDiscovered(device, THING_TYPE_RAINSENSOR, place);
360 logUnsupportedDevice(device);
362 case THING_PROTOCOL_GATEWAY:
363 case THING_REMOTE_CONTROLLER:
364 // widget: AlarmRemoteController
365 case THING_NETWORK_COMPONENT:
371 logUnsupportedDevice(device);
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();
387 private boolean isStateLess(SomfyTahomaDevice device) {
388 return device.getStates().isEmpty() || (device.getStates().size() == 1 && hasState(device, STATUS_STATE));
391 private void logUnsupportedDevice(SomfyTahomaDevice device) {
392 if (!isStateLess(device)) {
393 logger.debug("Detected a new unsupported device: {} with widgetName: {}", device.getUiClass(),
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());
398 StringBuilder sb = new StringBuilder().append('\n');
399 for (SomfyTahomaState state : device.getStates()) {
400 sb.append(state.toString()).append('\n');
402 logger.debug("Current device states: {}", sb);
406 private boolean hasState(SomfyTahomaDevice device, String state) {
407 return device.getDefinition().getStates().stream().anyMatch(st -> state.equals(st.getQualifiedName()));
410 private boolean hasMyfoxShutter(SomfyTahomaDevice device) {
411 return hasState(device, MYFOX_SHUTTER_STATUS_STATE);
414 private boolean hasEnergyConsumption(SomfyTahomaDevice device) {
415 return hasState(device, ENERGY_CONSUMPTION_STATE);
418 private boolean isSilentRollerShutter(SomfyTahomaDevice device) {
419 return "PositionableRollerShutterWithLowSpeedManagement".equals(device.getWidget());
422 private boolean isUnoRollerShutter(SomfyTahomaDevice device) {
423 return "PositionableRollerShutterUno".equals(device.getWidget());
426 private boolean isOnOffHeatingSystem(SomfyTahomaDevice device) {
427 return hasCommmand(device, COMMAND_SET_HEATINGLEVEL);
430 private boolean isZwaveHeatingSystem(SomfyTahomaDevice device) {
431 return hasState(device, ZWAVE_SET_POINT_TYPE_STATE);
434 private boolean hasCommmand(SomfyTahomaDevice device, String command) {
435 return device.getDefinition().getCommands().stream().anyMatch(cmd -> command.equals(cmd.getCommandName()));
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 + ")";
443 deviceDiscovered(label, device.getDeviceURL(), device.getOid(), thingTypeUID,
444 hasState(device, RSSI_LEVEL_STATE));
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);
452 properties.put(RSSI_LEVEL_STATE, "-1");
455 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
456 if (localBridgeHandler != null) {
457 ThingUID thingUID = new ThingUID(thingTypeUID, localBridgeHandler.getThing().getUID(), oid);
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());
466 private void actionGroupDiscovered(String label, String deviceURL, String oid) {
467 deviceDiscovered(label, deviceURL, oid, THING_TYPE_ACTIONGROUP, false);
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);
477 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
478 if (localBridgeHandler != null) {
479 ThingUID thingUID = new ThingUID(THING_TYPE_GATEWAY, localBridgeHandler.getThing().getUID(), id);
481 logger.debug("Detected a gateway with id: {} and type: {}", id, type);
483 DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_GATEWAY).withProperties(properties)
484 .withRepresentationProperty("id").withLabel("Somfy Gateway (" + type + ")")
485 .withBridge(localBridgeHandler.getThing().getUID()).build());