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 deviceDiscovered(device, THING_TYPE_AWNING, place);
162 case CLASS_CONTACT_SENSOR:
163 // widget: ContactSensor
164 deviceDiscovered(device, THING_TYPE_CONTACTSENSOR, place);
167 deviceDiscovered(device, THING_TYPE_CURTAIN, place);
169 case CLASS_EXTERIOR_SCREEN:
170 // widget: PositionableScreen
171 deviceDiscovered(device, THING_TYPE_EXTERIORSCREEN, place);
173 case CLASS_EXTERIOR_VENETIAN_BLIND:
174 // widget: PositionableExteriorVenetianBlind
175 deviceDiscovered(device, THING_TYPE_EXTERIORVENETIANBLIND, place);
177 case CLASS_GARAGE_DOOR:
178 deviceDiscovered(device, THING_TYPE_GARAGEDOOR, place);
181 if ("DimmerLight".equals(device.getWidget())) {
182 // widget: DimmerLight
183 deviceDiscovered(device, THING_TYPE_DIMMER_LIGHT, place);
185 // widget: TimedOnOffLight
186 // widget: StatefulOnOffLight
187 deviceDiscovered(device, THING_TYPE_LIGHT, place);
190 case CLASS_LIGHT_SENSOR:
191 deviceDiscovered(device, THING_TYPE_LIGHTSENSOR, place);
193 case CLASS_OCCUPANCY_SENSOR:
194 // widget: OccupancySensor
195 deviceDiscovered(device, THING_TYPE_OCCUPANCYSENSOR, place);
198 // widget: StatefulOnOff
199 deviceDiscovered(device, THING_TYPE_ONOFF, place);
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);
209 // widget: PositionableRollerShutter
210 // widget: PositionableTiltedRollerShutter
211 deviceDiscovered(device, THING_TYPE_ROLLERSHUTTER, place);
215 // widget: PositionableTiltedScreen
216 deviceDiscovered(device, THING_TYPE_SCREEN, place);
218 case CLASS_SMOKE_SENSOR:
219 // widget: SmokeSensor
220 deviceDiscovered(device, THING_TYPE_SMOKESENSOR, place);
222 case CLASS_VENETIAN_BLIND:
223 deviceDiscovered(device, THING_TYPE_VENETIANBLIND, place);
226 // widget: PositionableTiltedWindow
227 deviceDiscovered(device, THING_TYPE_WINDOW, place);
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);
237 deviceDiscovered(device, THING_TYPE_EXTERNAL_ALARM, place);
241 if (hasState(device, CYCLIC_BUTTON_STATE)) {
242 deviceDiscovered(device, THING_TYPE_POD, place);
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);
255 logUnsupportedDevice(device);
258 case CLASS_EXTERIOR_HEATING_SYSTEM:
259 if ("DimmerExteriorHeating".equals(device.getWidget())) {
260 // widget: DimmerExteriorHeating
261 deviceDiscovered(device, THING_TYPE_EXTERIOR_HEATING_SYSTEM, place);
263 logUnsupportedDevice(device);
266 case CLASS_HUMIDITY_SENSOR:
267 if (hasState(device, WATER_DETECTION_STATE)) {
268 deviceDiscovered(device, THING_TYPE_WATERSENSOR, place);
270 // widget: RelativeHumiditySensor
271 deviceDiscovered(device, THING_TYPE_HUMIDITYSENSOR, place);
273 case CLASS_DOOR_LOCK:
274 // widget: UnlockDoorLockWithUnknownPosition
275 deviceDiscovered(device, THING_TYPE_DOOR_LOCK, place);
278 if ("BioclimaticPergola".equals(device.getWidget())) {
279 // widget: BioclimaticPergola
280 deviceDiscovered(device, THING_TYPE_BIOCLIMATIC_PERGOLA, place);
282 deviceDiscovered(device, THING_TYPE_PERGOLA, place);
285 case CLASS_WINDOW_HANDLE:
286 // widget: ThreeWayWindowHandle
287 deviceDiscovered(device, THING_TYPE_WINDOW_HANDLE, place);
289 case CLASS_TEMPERATURE_SENSOR:
290 // widget: TemperatureSensor
291 deviceDiscovered(device, THING_TYPE_TEMPERATURESENSOR, place);
294 deviceDiscovered(device, THING_TYPE_GATE, place);
296 case CLASS_ELECTRICITY_SENSOR:
297 if (hasEnergyConsumption(device)) {
298 deviceDiscovered(device, THING_TYPE_ELECTRICITYSENSOR, place);
300 logUnsupportedDevice(device);
305 deviceDiscovered(device, THING_TYPE_DOCK, place);
308 deviceDiscovered(device, THING_TYPE_SIREN, place);
310 case CLASS_ADJUSTABLE_SLATS_ROLLER_SHUTTER:
311 deviceDiscovered(device, THING_TYPE_ADJUSTABLE_SLATS_ROLLERSHUTTER, place);
314 if (hasMyfoxShutter(device)) {
315 // widget: MyFoxSecurityCamera
316 deviceDiscovered(device, THING_TYPE_MYFOX_CAMERA, place);
318 logUnsupportedDevice(device);
321 case THING_PROTOCOL_GATEWAY:
322 case THING_REMOTE_CONTROLLER:
323 // widget: AlarmRemoteController
324 case THING_NETWORK_COMPONENT:
327 logUnsupportedDevice(device);
331 private @Nullable String getPlaceLabel(SomfyTahomaSetup setup, String oid) {
332 SomfyTahomaRootPlace root = setup.getRootPlace();
333 if (!oid.isEmpty() && root != null) {
334 for (SomfyTahomaSubPlace place : root.getSubPlaces()) {
335 if (oid.equals(place.getOid())) {
336 return place.getLabel();
343 private boolean isStateLess(SomfyTahomaDevice device) {
344 return device.getStates().isEmpty() || (device.getStates().size() == 1 && hasState(device, STATUS_STATE));
347 private void logUnsupportedDevice(SomfyTahomaDevice device) {
348 if (!isStateLess(device)) {
349 logger.info("Detected a new unsupported device: {} with widgetName: {}", device.getUiClass(),
351 logger.info("If you want to add the support, please create a new issue and attach the information below");
352 logger.info("Device definition:\n{}", device.getDefinition());
354 StringBuilder sb = new StringBuilder().append('\n');
355 for (SomfyTahomaState state : device.getStates()) {
356 sb.append(state.toString()).append('\n');
358 logger.info("Current device states: {}", sb);
362 private boolean hasState(SomfyTahomaDevice device, String state) {
363 return device.getDefinition().getStates().stream().anyMatch(st -> state.equals(st.getQualifiedName()));
366 private boolean hasMyfoxShutter(SomfyTahomaDevice device) {
367 return hasState(device, MYFOX_SHUTTER_STATUS_STATE);
370 private boolean hasEnergyConsumption(SomfyTahomaDevice device) {
371 return hasState(device, ENERGY_CONSUMPTION_STATE);
374 private boolean isSilentRollerShutter(SomfyTahomaDevice device) {
375 return "PositionableRollerShutterWithLowSpeedManagement".equals(device.getWidget());
378 private boolean isUnoRollerShutter(SomfyTahomaDevice device) {
379 return "PositionableRollerShutterUno".equals(device.getWidget());
382 private boolean isOnOffHeatingSystem(SomfyTahomaDevice device) {
383 return hasCommmand(device, COMMAND_SET_HEATINGLEVEL);
386 private boolean isZwaveHeatingSystem(SomfyTahomaDevice device) {
387 return hasState(device, ZWAVE_SET_POINT_TYPE_STATE);
390 private boolean hasCommmand(SomfyTahomaDevice device, String command) {
391 return device.getDefinition().getCommands().stream().anyMatch(cmd -> command.equals(cmd.getCommandName()));
394 private void deviceDiscovered(SomfyTahomaDevice device, ThingTypeUID thingTypeUID, @Nullable String place) {
395 String label = device.getLabel();
396 if (place != null && !place.isBlank()) {
397 label += " (" + place + ")";
399 deviceDiscovered(label, device.getDeviceURL(), device.getOid(), thingTypeUID,
400 hasState(device, RSSI_LEVEL_STATE));
403 private void deviceDiscovered(String label, String deviceURL, String oid, ThingTypeUID thingTypeUID, boolean rssi) {
404 Map<String, Object> properties = new HashMap<>();
405 properties.put("url", deviceURL);
406 properties.put(NAME_STATE, label);
408 properties.put(RSSI_LEVEL_STATE, "-1");
411 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
412 if (localBridgeHandler != null) {
413 ThingUID thingUID = new ThingUID(thingTypeUID, localBridgeHandler.getThing().getUID(), oid);
415 logger.debug("Detected a/an {} - label: {} oid: {}", thingTypeUID.getId(), label, oid);
416 thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
417 .withProperties(properties).withRepresentationProperty("url").withLabel(label)
418 .withBridge(localBridgeHandler.getThing().getUID()).build());
422 private void actionGroupDiscovered(String label, String deviceURL, String oid) {
423 deviceDiscovered(label, deviceURL, oid, THING_TYPE_ACTIONGROUP, false);
426 private void gatewayDiscovered(SomfyTahomaGateway gw) {
427 Map<String, Object> properties = new HashMap<>(1);
428 String type = gatewayTypes.getOrDefault(gw.getType(), "UNKNOWN");
429 String id = gw.getGatewayId();
430 properties.put("id", id);
431 properties.put("type", type);
433 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
434 if (localBridgeHandler != null) {
435 ThingUID thingUID = new ThingUID(THING_TYPE_GATEWAY, localBridgeHandler.getThing().getUID(), id);
437 logger.debug("Detected a gateway with id: {} and type: {}", id, type);
439 DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_GATEWAY).withProperties(properties)
440 .withRepresentationProperty("id").withLabel("Somfy Gateway (" + type + ")")
441 .withBridge(localBridgeHandler.getThing().getUID()).build());