2 * Copyright (c) 2010-2023 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 tahomaBridgeHandler) {
83 bridgeHandler = tahomaBridgeHandler;
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) {
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 // local mode does not have action groups
141 if (!localBridgeHandler.isDevModeReady()) {
142 List<SomfyTahomaActionGroup> actions = localBridgeHandler.listActionGroups();
144 for (SomfyTahomaActionGroup group : actions) {
145 String oid = group.getOid();
146 String label = group.getLabel();
148 // actiongroups use oid as deviceURL
149 actionGroupDiscovered(label, oid);
153 logger.debug("Cannot start discovery since the bridge is not online!");
157 private void discoverDevice(SomfyTahomaDevice device, SomfyTahomaSetup setup) {
158 logger.debug("url: {}", device.getDeviceURL());
159 String place = getPlaceLabel(setup, device.getPlaceOID());
160 String widget = device.getDefinition().getWidgetName();
161 switch (device.getDefinition().getUiClass()) {
163 // widget: PositionableHorizontalAwning
164 // widget: DynamicAwning
165 // widget: UpDownHorizontalAwning
166 deviceDiscovered(device, THING_TYPE_AWNING, place);
168 case CLASS_CONTACT_SENSOR:
169 // widget: ContactSensor
170 deviceDiscovered(device, THING_TYPE_CONTACTSENSOR, place);
173 deviceDiscovered(device, THING_TYPE_CURTAIN, place);
175 case CLASS_EXTERIOR_SCREEN:
176 // widget: PositionableScreen
177 deviceDiscovered(device, THING_TYPE_EXTERIORSCREEN, place);
179 case CLASS_EXTERIOR_VENETIAN_BLIND:
180 // widget: PositionableExteriorVenetianBlind
181 deviceDiscovered(device, THING_TYPE_EXTERIORVENETIANBLIND, place);
183 case CLASS_GARAGE_DOOR:
184 deviceDiscovered(device, THING_TYPE_GARAGEDOOR, place);
187 if ("DimmerLight".equals(widget) || "DynamicLight".equals(widget)) {
188 // widget: DimmerLight
189 // widget: DynamicLight
190 deviceDiscovered(device, THING_TYPE_DIMMER_LIGHT, place);
192 // widget: TimedOnOffLight
193 // widget: StatefulOnOffLight
194 deviceDiscovered(device, THING_TYPE_LIGHT, place);
197 case CLASS_LIGHT_SENSOR:
198 deviceDiscovered(device, THING_TYPE_LIGHTSENSOR, place);
200 case CLASS_OCCUPANCY_SENSOR:
201 // widget: OccupancySensor
202 deviceDiscovered(device, THING_TYPE_OCCUPANCYSENSOR, place);
205 // widget: StatefulOnOff
206 deviceDiscovered(device, THING_TYPE_ONOFF, place);
208 case CLASS_ROLLER_SHUTTER:
209 if (isSilentRollerShutter(device)) {
210 // widget: PositionableRollerShutterWithLowSpeedManagement
211 deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER_SILENT, place);
212 } else if (isUnoRollerShutter(device)) {
213 // widget: PositionableRollerShutterUno
214 deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER_UNO, place);
216 // widget: PositionableRollerShutter
217 // widget: PositionableTiltedRollerShutter
218 deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER, place);
222 // widget: DynamicShutter
223 deviceDiscovered(device, THING_TYPE_SHUTTER, place);
226 // widget: PositionableTiltedScreen
227 deviceDiscovered(device, THING_TYPE_SCREEN, place);
229 case CLASS_SMOKE_SENSOR:
230 // widget: SmokeSensor
231 deviceDiscovered(device, THING_TYPE_SMOKESENSOR, place);
233 case CLASS_VENETIAN_BLIND:
234 // widget: DynamicVenetianBlind
235 if (hasCommmand(device, "setOrientation")) {
236 deviceDiscovered(device, THING_TYPE_VENETIANBLIND, place);
238 // simple venetian blind without orientation
239 deviceDiscovered(device, THING_TYPE_SHUTTER, place);
243 // widget: PositionableTiltedWindow
244 deviceDiscovered(device, THING_TYPE_WINDOW, place);
247 if (device.getDeviceURL().startsWith("internal:")) {
248 // widget: TSKAlarmController
249 deviceDiscovered(device, THING_TYPE_INTERNAL_ALARM, place);
250 } else if ("MyFoxAlarmController".equals(widget)) {
251 // widget: MyFoxAlarmController
252 deviceDiscovered(device, THING_TYPE_MYFOX_ALARM, place);
254 deviceDiscovered(device, THING_TYPE_EXTERNAL_ALARM, place);
258 if (hasState(device, CYCLIC_BUTTON_STATE)) {
259 deviceDiscovered(device, THING_TYPE_POD, place);
262 case CLASS_HEATING_SYSTEM:
263 if ("SomfyThermostat".equals(widget)) {
264 deviceDiscovered(device, THING_TYPE_THERMOSTAT, place);
265 } else if ("ValveHeatingTemperatureInterface".equals(widget)) {
266 deviceDiscovered(device, THING_TYPE_VALVE_HEATING_SYSTEM, place);
267 } else if (isOnOffHeatingSystem(device)) {
268 deviceDiscovered(device, THING_TYPE_ONOFF_HEATING_SYSTEM, place);
269 } else if (isZwaveHeatingSystem(device)) {
270 deviceDiscovered(device, THING_TYPE_ZWAVE_HEATING_SYSTEM, place);
272 logUnsupportedDevice(device);
275 case CLASS_EXTERIOR_HEATING_SYSTEM:
276 if ("DimmerExteriorHeating".equals(widget)) {
277 // widget: DimmerExteriorHeating
278 deviceDiscovered(device, THING_TYPE_EXTERIOR_HEATING_SYSTEM, place);
280 logUnsupportedDevice(device);
283 case CLASS_HUMIDITY_SENSOR:
284 if (hasState(device, WATER_DETECTION_STATE)) {
285 deviceDiscovered(device, THING_TYPE_WATERSENSOR, place);
287 // widget: RelativeHumiditySensor
288 deviceDiscovered(device, THING_TYPE_HUMIDITYSENSOR, place);
291 case CLASS_DOOR_LOCK:
292 // widget: UnlockDoorLockWithUnknownPosition
293 deviceDiscovered(device, THING_TYPE_DOOR_LOCK, place);
296 if ("BioclimaticPergola".equals(widget)) {
297 // widget: BioclimaticPergola
298 deviceDiscovered(device, THING_TYPE_BIOCLIMATIC_PERGOLA, place);
300 deviceDiscovered(device, THING_TYPE_PERGOLA, place);
303 case CLASS_WINDOW_HANDLE:
304 // widget: ThreeWayWindowHandle
305 deviceDiscovered(device, THING_TYPE_WINDOW_HANDLE, place);
307 case CLASS_TEMPERATURE_SENSOR:
308 // widget: TemperatureSensor
309 deviceDiscovered(device, THING_TYPE_TEMPERATURESENSOR, place);
312 deviceDiscovered(device, THING_TYPE_GATE, place);
314 case CLASS_ELECTRICITY_SENSOR:
315 if (hasEnergyConsumption(device)) {
316 deviceDiscovered(device, THING_TYPE_ELECTRICITYSENSOR, place);
318 logUnsupportedDevice(device);
321 case CLASS_WATER_HEATING_SYSTEM:
322 // widget: DomesticHotWaterProduction
323 if ("DomesticHotWaterProduction".equals(widget)) {
324 deviceDiscovered(device, THING_TYPE_WATERHEATINGSYSTEM, place);
326 logUnsupportedDevice(device);
331 deviceDiscovered(device, THING_TYPE_DOCK, place);
334 deviceDiscovered(device, THING_TYPE_SIREN, place);
336 case CLASS_ADJUSTABLE_SLATS_ROLLER_SHUTTER:
337 deviceDiscovered(device, THING_TYPE_ADJUSTABLE_SLATS_ROLLERSHUTTER, place);
340 if (hasMyfoxShutter(device)) {
341 // widget: MyFoxSecurityCamera
342 deviceDiscovered(device, THING_TYPE_MYFOX_CAMERA, place);
344 logUnsupportedDevice(device);
347 case CLASS_HITACHI_HEATING_SYSTEM:
348 if ("HitachiAirToWaterHeatingZone".equals(widget)) {
349 // widget: HitachiAirToWaterHeatingZone
350 deviceDiscovered(device, THING_TYPE_HITACHI_ATWHZ, place);
351 } else if ("HitachiAirToWaterMainComponent".equals(widget)) {
352 // widget: HitachiAirToWaterMainComponent
353 deviceDiscovered(device, THING_TYPE_HITACHI_ATWMC, place);
354 } else if ("HitachiDHW".equals(widget)) {
355 // widget: HitachiDHW
356 deviceDiscovered(device, THING_TYPE_HITACHI_DHW, place);
358 logUnsupportedDevice(device);
361 case CLASS_RAIN_SENSOR:
362 if ("RainSensor".equals(widget)) {
363 // widget: RainSensor
364 deviceDiscovered(device, THING_TYPE_RAINSENSOR, place);
366 logUnsupportedDevice(device);
369 case CLASS_CARBON_DIOXIDE_SENSOR:
371 deviceDiscovered(device, THING_TYPE_CARBON_DIOXIDE_SENSOR, place);
373 case CLASS_NOISE_SENSOR:
374 // widget: NoiseSensor
375 deviceDiscovered(device, THING_TYPE_NOISE_SENSOR, place);
377 case THING_PROTOCOL_GATEWAY:
378 case THING_REMOTE_CONTROLLER:
379 // widget: AlarmRemoteController
380 case THING_NETWORK_COMPONENT:
381 case THING_CONFIGURATION_COMPONENT:
382 // widget: NetatmoHome
388 logUnsupportedDevice(device);
392 private @Nullable String getPlaceLabel(SomfyTahomaSetup setup, String oid) {
393 SomfyTahomaRootPlace root = setup.getRootPlace();
394 if (!oid.isEmpty() && root != null) {
395 for (SomfyTahomaSubPlace place : root.getSubPlaces()) {
396 if (oid.equals(place.getOid())) {
397 return place.getLabel();
404 private boolean isStateLess(SomfyTahomaDevice device) {
405 return device.getStates().isEmpty() || (device.getStates().size() == 1 && hasState(device, STATUS_STATE));
408 private void logUnsupportedDevice(SomfyTahomaDevice device) {
409 if (!isStateLess(device)) {
410 logger.debug("Detected a new unsupported device: {} with widgetName: {}",
411 device.getDefinition().getUiClass(), device.getDefinition().getWidgetName());
412 logger.debug("If you want to add the support, please create a new issue and attach the information below");
413 logger.debug("Device definition:\n{}", device.getDefinition());
415 StringBuilder sb = new StringBuilder().append('\n');
416 for (SomfyTahomaState state : device.getStates()) {
417 sb.append(state.toString()).append('\n');
419 logger.debug("Current device states: {}", sb);
423 private boolean hasState(SomfyTahomaDevice device, String state) {
424 return device.getDefinition().getStates().stream().anyMatch(st -> state.equals(st.getQualifiedName()));
427 private boolean hasMyfoxShutter(SomfyTahomaDevice device) {
428 return hasState(device, MYFOX_SHUTTER_STATUS_STATE);
431 private boolean hasEnergyConsumption(SomfyTahomaDevice device) {
432 return hasState(device, ENERGY_CONSUMPTION_STATE);
435 private boolean isSilentRollerShutter(SomfyTahomaDevice device) {
436 return "PositionableRollerShutterWithLowSpeedManagement".equals(device.getDefinition().getWidgetName());
439 private boolean isUnoRollerShutter(SomfyTahomaDevice device) {
440 return "PositionableRollerShutterUno".equals(device.getDefinition().getWidgetName());
443 private boolean isOnOffHeatingSystem(SomfyTahomaDevice device) {
444 return hasCommmand(device, COMMAND_SET_HEATINGLEVEL);
447 private boolean isZwaveHeatingSystem(SomfyTahomaDevice device) {
448 return hasState(device, ZWAVE_SET_POINT_TYPE_STATE);
451 private boolean hasCommmand(SomfyTahomaDevice device, String command) {
452 return device.getDefinition().getCommands().stream().anyMatch(cmd -> command.equals(cmd.getCommandName()));
455 private void deviceDiscovered(SomfyTahomaDevice device, ThingTypeUID thingTypeUID, @Nullable String place) {
456 String label = device.getLabel();
457 if (place != null && !place.isBlank()) {
458 label += " (" + place + ")";
460 deviceDiscovered(label, device.getDeviceURL(), thingTypeUID, hasState(device, RSSI_LEVEL_STATE));
463 private void deviceDiscovered(String label, String deviceURL, ThingTypeUID thingTypeUID, boolean rssi) {
464 Map<String, Object> properties = new HashMap<>();
465 properties.put("url", deviceURL);
466 properties.put(NAME_STATE, label);
468 properties.put(RSSI_LEVEL_STATE, "-1");
471 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
472 if (localBridgeHandler != null) {
473 ThingUID thingUID = new ThingUID(thingTypeUID, localBridgeHandler.getThing().getUID(),
474 deviceURL.replaceAll("[^a-zA-Z0-9_]", ""));
476 logger.debug("Detected a/an {} - label: {} device URL: {}", thingTypeUID.getId(), label, deviceURL);
477 thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
478 .withProperties(properties).withRepresentationProperty("url").withLabel(label)
479 .withBridge(localBridgeHandler.getThing().getUID()).build());
483 private void actionGroupDiscovered(String label, String deviceURL) {
484 deviceDiscovered(label, deviceURL, THING_TYPE_ACTIONGROUP, false);
487 private void gatewayDiscovered(SomfyTahomaGateway gw) {
488 Map<String, Object> properties = new HashMap<>(1);
489 String type = gatewayTypes.getOrDefault(gw.getType(), "UNKNOWN");
490 String id = gw.getGatewayId();
491 properties.put("id", id);
492 properties.put("type", type);
494 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
495 if (localBridgeHandler != null) {
496 ThingUID thingUID = new ThingUID(THING_TYPE_GATEWAY, localBridgeHandler.getThing().getUID(), id);
498 logger.debug("Detected a gateway with id: {} and type: {}", id, type);
500 DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_GATEWAY).withProperties(properties)
501 .withRepresentationProperty("id").withLabel("Somfy Gateway (" + type + ")")
502 .withBridge(localBridgeHandler.getThing().getUID()).build());