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: PositionableTiltedScreen
218 deviceDiscovered(device, THING_TYPE_SCREEN, place);
220 case CLASS_SMOKE_SENSOR:
221 // widget: SmokeSensor
222 deviceDiscovered(device, THING_TYPE_SMOKESENSOR, place);
224 case CLASS_VENETIAN_BLIND:
225 // widget: DynamicVenetianBlind
226 deviceDiscovered(device, THING_TYPE_VENETIANBLIND, place);
229 // widget: PositionableTiltedWindow
230 deviceDiscovered(device, THING_TYPE_WINDOW, place);
233 if (device.getDeviceURL().startsWith("internal:")) {
234 // widget: TSKAlarmController
235 deviceDiscovered(device, THING_TYPE_INTERNAL_ALARM, place);
236 } else if ("MyFoxAlarmController".equals(device.getWidget())) {
237 // widget: MyFoxAlarmController
238 deviceDiscovered(device, THING_TYPE_MYFOX_ALARM, place);
240 deviceDiscovered(device, THING_TYPE_EXTERNAL_ALARM, place);
244 if (hasState(device, CYCLIC_BUTTON_STATE)) {
245 deviceDiscovered(device, THING_TYPE_POD, place);
248 case CLASS_HEATING_SYSTEM:
249 if ("SomfyThermostat".equals(device.getWidget())) {
250 deviceDiscovered(device, THING_TYPE_THERMOSTAT, place);
251 } else if ("ValveHeatingTemperatureInterface".equals(device.getWidget())) {
252 deviceDiscovered(device, THING_TYPE_VALVE_HEATING_SYSTEM, place);
253 } else if (isOnOffHeatingSystem(device)) {
254 deviceDiscovered(device, THING_TYPE_ONOFF_HEATING_SYSTEM, place);
255 } else if (isZwaveHeatingSystem(device)) {
256 deviceDiscovered(device, THING_TYPE_ZWAVE_HEATING_SYSTEM, place);
258 logUnsupportedDevice(device);
261 case CLASS_EXTERIOR_HEATING_SYSTEM:
262 if ("DimmerExteriorHeating".equals(device.getWidget())) {
263 // widget: DimmerExteriorHeating
264 deviceDiscovered(device, THING_TYPE_EXTERIOR_HEATING_SYSTEM, place);
266 logUnsupportedDevice(device);
269 case CLASS_HUMIDITY_SENSOR:
270 if (hasState(device, WATER_DETECTION_STATE)) {
271 deviceDiscovered(device, THING_TYPE_WATERSENSOR, place);
273 // widget: RelativeHumiditySensor
274 deviceDiscovered(device, THING_TYPE_HUMIDITYSENSOR, place);
276 case CLASS_DOOR_LOCK:
277 // widget: UnlockDoorLockWithUnknownPosition
278 deviceDiscovered(device, THING_TYPE_DOOR_LOCK, place);
281 if ("BioclimaticPergola".equals(device.getWidget())) {
282 // widget: BioclimaticPergola
283 deviceDiscovered(device, THING_TYPE_BIOCLIMATIC_PERGOLA, place);
285 deviceDiscovered(device, THING_TYPE_PERGOLA, place);
288 case CLASS_WINDOW_HANDLE:
289 // widget: ThreeWayWindowHandle
290 deviceDiscovered(device, THING_TYPE_WINDOW_HANDLE, place);
292 case CLASS_TEMPERATURE_SENSOR:
293 // widget: TemperatureSensor
294 deviceDiscovered(device, THING_TYPE_TEMPERATURESENSOR, place);
297 deviceDiscovered(device, THING_TYPE_GATE, place);
299 case CLASS_ELECTRICITY_SENSOR:
300 if (hasEnergyConsumption(device)) {
301 deviceDiscovered(device, THING_TYPE_ELECTRICITYSENSOR, place);
303 logUnsupportedDevice(device);
306 case CLASS_WATER_HEATING_SYSTEM:
307 // widget: DomesticHotWaterProduction
308 if ("DomesticHotWaterProduction".equals(device.getWidget())) {
309 deviceDiscovered(device, THING_TYPE_WATERHEATINGSYSTEM, place);
311 logUnsupportedDevice(device);
316 deviceDiscovered(device, THING_TYPE_DOCK, place);
319 deviceDiscovered(device, THING_TYPE_SIREN, place);
321 case CLASS_ADJUSTABLE_SLATS_ROLLER_SHUTTER:
322 deviceDiscovered(device, THING_TYPE_ADJUSTABLE_SLATS_ROLLERSHUTTER, place);
325 if (hasMyfoxShutter(device)) {
326 // widget: MyFoxSecurityCamera
327 deviceDiscovered(device, THING_TYPE_MYFOX_CAMERA, place);
329 logUnsupportedDevice(device);
332 case CLASS_HITACHI_HEATING_SYSTEM:
333 if ("HitachiAirToWaterHeatingZone".equals(device.getWidget())) {
334 // widget: HitachiAirToWaterHeatingZone
335 deviceDiscovered(device, THING_TYPE_HITACHI_ATWHZ, place);
336 } else if ("HitachiAirToWaterMainComponent".equals(device.getWidget())) {
337 // widget: HitachiAirToWaterMainComponent
338 deviceDiscovered(device, THING_TYPE_HITACHI_ATWMC, place);
339 } else if ("HitachiDHW".equals(device.getWidget())) {
340 // widget: HitachiDHW
341 deviceDiscovered(device, THING_TYPE_HITACHI_DHW, place);
343 logUnsupportedDevice(device);
346 case CLASS_RAIN_SENSOR:
347 if ("RainSensor".equals(device.getWidget())) {
348 // widget: RainSensor
349 deviceDiscovered(device, THING_TYPE_RAINSENSOR, place);
351 logUnsupportedDevice(device);
353 case THING_PROTOCOL_GATEWAY:
354 case THING_REMOTE_CONTROLLER:
355 // widget: AlarmRemoteController
356 case THING_NETWORK_COMPONENT:
362 logUnsupportedDevice(device);
366 private @Nullable String getPlaceLabel(SomfyTahomaSetup setup, String oid) {
367 SomfyTahomaRootPlace root = setup.getRootPlace();
368 if (!oid.isEmpty() && root != null) {
369 for (SomfyTahomaSubPlace place : root.getSubPlaces()) {
370 if (oid.equals(place.getOid())) {
371 return place.getLabel();
378 private boolean isStateLess(SomfyTahomaDevice device) {
379 return device.getStates().isEmpty() || (device.getStates().size() == 1 && hasState(device, STATUS_STATE));
382 private void logUnsupportedDevice(SomfyTahomaDevice device) {
383 if (!isStateLess(device)) {
384 logger.debug("Detected a new unsupported device: {} with widgetName: {}", device.getUiClass(),
386 logger.debug("If you want to add the support, please create a new issue and attach the information below");
387 logger.debug("Device definition:\n{}", device.getDefinition());
389 StringBuilder sb = new StringBuilder().append('\n');
390 for (SomfyTahomaState state : device.getStates()) {
391 sb.append(state.toString()).append('\n');
393 logger.debug("Current device states: {}", sb);
397 private boolean hasState(SomfyTahomaDevice device, String state) {
398 return device.getDefinition().getStates().stream().anyMatch(st -> state.equals(st.getQualifiedName()));
401 private boolean hasMyfoxShutter(SomfyTahomaDevice device) {
402 return hasState(device, MYFOX_SHUTTER_STATUS_STATE);
405 private boolean hasEnergyConsumption(SomfyTahomaDevice device) {
406 return hasState(device, ENERGY_CONSUMPTION_STATE);
409 private boolean isSilentRollerShutter(SomfyTahomaDevice device) {
410 return "PositionableRollerShutterWithLowSpeedManagement".equals(device.getWidget());
413 private boolean isUnoRollerShutter(SomfyTahomaDevice device) {
414 return "PositionableRollerShutterUno".equals(device.getWidget());
417 private boolean isOnOffHeatingSystem(SomfyTahomaDevice device) {
418 return hasCommmand(device, COMMAND_SET_HEATINGLEVEL);
421 private boolean isZwaveHeatingSystem(SomfyTahomaDevice device) {
422 return hasState(device, ZWAVE_SET_POINT_TYPE_STATE);
425 private boolean hasCommmand(SomfyTahomaDevice device, String command) {
426 return device.getDefinition().getCommands().stream().anyMatch(cmd -> command.equals(cmd.getCommandName()));
429 private void deviceDiscovered(SomfyTahomaDevice device, ThingTypeUID thingTypeUID, @Nullable String place) {
430 String label = device.getLabel();
431 if (place != null && !place.isBlank()) {
432 label += " (" + place + ")";
434 deviceDiscovered(label, device.getDeviceURL(), device.getOid(), thingTypeUID,
435 hasState(device, RSSI_LEVEL_STATE));
438 private void deviceDiscovered(String label, String deviceURL, String oid, ThingTypeUID thingTypeUID, boolean rssi) {
439 Map<String, Object> properties = new HashMap<>();
440 properties.put("url", deviceURL);
441 properties.put(NAME_STATE, label);
443 properties.put(RSSI_LEVEL_STATE, "-1");
446 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
447 if (localBridgeHandler != null) {
448 ThingUID thingUID = new ThingUID(thingTypeUID, localBridgeHandler.getThing().getUID(), oid);
450 logger.debug("Detected a/an {} - label: {} oid: {}", thingTypeUID.getId(), label, oid);
451 thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
452 .withProperties(properties).withRepresentationProperty("url").withLabel(label)
453 .withBridge(localBridgeHandler.getThing().getUID()).build());
457 private void actionGroupDiscovered(String label, String deviceURL, String oid) {
458 deviceDiscovered(label, deviceURL, oid, THING_TYPE_ACTIONGROUP, false);
461 private void gatewayDiscovered(SomfyTahomaGateway gw) {
462 Map<String, Object> properties = new HashMap<>(1);
463 String type = gatewayTypes.getOrDefault(gw.getType(), "UNKNOWN");
464 String id = gw.getGatewayId();
465 properties.put("id", id);
466 properties.put("type", type);
468 SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler;
469 if (localBridgeHandler != null) {
470 ThingUID thingUID = new ThingUID(THING_TYPE_GATEWAY, localBridgeHandler.getThing().getUID(), id);
472 logger.debug("Detected a gateway with id: {} and type: {}", id, type);
474 DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_GATEWAY).withProperties(properties)
475 .withRepresentationProperty("id").withLabel("Somfy Gateway (" + type + ")")
476 .withBridge(localBridgeHandler.getThing().getUID()).build());