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.boschshc.internal.discovery;
15 import java.util.AbstractMap;
16 import java.util.Date;
17 import java.util.List;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.boschshc.internal.devices.BoschSHCBindingConstants;
24 import org.openhab.binding.boschshc.internal.devices.bridge.BridgeHandler;
25 import org.openhab.binding.boschshc.internal.devices.bridge.dto.Device;
26 import org.openhab.binding.boschshc.internal.devices.bridge.dto.Room;
27 import org.openhab.core.config.discovery.AbstractDiscoveryService;
28 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
29 import org.openhab.core.thing.ThingTypeUID;
30 import org.openhab.core.thing.ThingUID;
31 import org.openhab.core.thing.binding.ThingHandler;
32 import org.openhab.core.thing.binding.ThingHandlerService;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
37 * The {@link ThingDiscoveryService} is responsible to discover Bosch Smart Home things.
38 * The paired SHC BridgeHandler is required to get the lists of rooms and devices.
39 * With this data the openhab things are discovered.
41 * The order to make this work is
42 * 1. SHC bridge is created, e.v via openhab UI
43 * 2. Service is instantiated setBridgeHandler of this service is called
44 * 3. Service is activated
45 * 4. Service registers itself as discoveryLister at the bridge
46 * 5. bridge calls startScan after bridge is paired and things can be discovered
48 * @author Gerd Zanker - Initial contribution
51 public class ThingDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
52 private static final int SEARCH_TIME = 1;
54 private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class);
55 private @Nullable BridgeHandler shcBridgeHandler;
57 protected static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(
58 BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH, BoschSHCBindingConstants.THING_TYPE_TWINGUARD,
59 BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT, BoschSHCBindingConstants.THING_TYPE_MOTION_DETECTOR,
60 BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL, BoschSHCBindingConstants.THING_TYPE_THERMOSTAT,
61 BoschSHCBindingConstants.THING_TYPE_CLIMATE_CONTROL, BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT,
62 BoschSHCBindingConstants.THING_TYPE_CAMERA_360, BoschSHCBindingConstants.THING_TYPE_CAMERA_EYES,
63 BoschSHCBindingConstants.THING_TYPE_INTRUSION_DETECTION_SYSTEM,
64 BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT, BoschSHCBindingConstants.THING_TYPE_SMART_BULB,
65 BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR);
68 protected static final Map<String, ThingTypeUID> DEVICEMODEL_TO_THINGTYPE_MAP = Map.ofEntries(
69 new AbstractMap.SimpleEntry<>("BBL", BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL),
70 new AbstractMap.SimpleEntry<>("TWINGUARD", BoschSHCBindingConstants.THING_TYPE_TWINGUARD),
71 new AbstractMap.SimpleEntry<>("PSM", BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH),
72 new AbstractMap.SimpleEntry<>("PLUG_COMPACT", BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT),
73 new AbstractMap.SimpleEntry<>("CAMERA_360", BoschSHCBindingConstants.THING_TYPE_CAMERA_360),
74 new AbstractMap.SimpleEntry<>("CAMERA_EYES", BoschSHCBindingConstants.THING_TYPE_CAMERA_EYES),
75 new AbstractMap.SimpleEntry<>("BWTH", BoschSHCBindingConstants.THING_TYPE_THERMOSTAT), // wall thermostat
76 new AbstractMap.SimpleEntry<>("THB", BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT), // wall thermostat with batteries
77 new AbstractMap.SimpleEntry<>("SD", BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR),
78 new AbstractMap.SimpleEntry<>("MD", BoschSHCBindingConstants.THING_TYPE_MOTION_DETECTOR),
79 new AbstractMap.SimpleEntry<>("ROOM_CLIMATE_CONTROL", BoschSHCBindingConstants.THING_TYPE_CLIMATE_CONTROL),
80 new AbstractMap.SimpleEntry<>("INTRUSION_DETECTION_SYSTEM", BoschSHCBindingConstants.THING_TYPE_INTRUSION_DETECTION_SYSTEM),
81 new AbstractMap.SimpleEntry<>("HUE_LIGHT", BoschSHCBindingConstants.THING_TYPE_SMART_BULB),
82 new AbstractMap.SimpleEntry<>("WRC2", BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT)
83 // Future Extension: map deviceModel names to BoschSHC Thing Types when they are supported
84 // new AbstractMap.SimpleEntry<>("SMOKE_DETECTION_SYSTEM", BoschSHCBindingConstants.),
85 // new AbstractMap.SimpleEntry<>("PRESENCE_SIMULATION_SERVICE", BoschSHCBindingConstants.),
86 // new AbstractMap.SimpleEntry<>("VENTILATION_SERVICE", BoschSHCBindingConstants.),
87 // new AbstractMap.SimpleEntry<>("HUE_BRIDGE", BoschSHCBindingConstants.)
88 // new AbstractMap.SimpleEntry<>("HUE_BRIDGE_MANAGER*", BoschSHCBindingConstants.)
89 // new AbstractMap.SimpleEntry<>("HUE_LIGHT_ROOM_CONTROL", BoschSHCBindingConstants.)
93 public ThingDiscoveryService() {
94 super(SUPPORTED_THING_TYPES, SEARCH_TIME);
98 public void activate() {
99 logger.trace("activate");
100 final BridgeHandler handler = shcBridgeHandler;
101 if (handler != null) {
102 handler.registerDiscoveryListener(this);
107 public void deactivate() {
108 logger.trace("deactivate");
109 final BridgeHandler handler = shcBridgeHandler;
110 if (handler != null) {
111 removeOlderResults(new Date().getTime(), handler.getThing().getUID());
112 handler.unregisterDiscoveryListener();
119 protected void startScan() {
120 if (shcBridgeHandler == null) {
121 logger.debug("The shcBridgeHandler is empty, no manual scan is currently possible");
127 } catch (InterruptedException e) {
128 // Restore interrupted state...
129 Thread.currentThread().interrupt();
134 protected synchronized void stopScan() {
135 logger.debug("Stop manual scan on bridge {}",
136 shcBridgeHandler != null ? shcBridgeHandler.getThing().getUID() : "?");
138 final BridgeHandler handler = shcBridgeHandler;
139 if (handler != null) {
140 removeOlderResults(getTimestampOfLastScan(), handler.getThing().getUID());
145 public void setThingHandler(@Nullable ThingHandler handler) {
146 if (handler instanceof BridgeHandler bridgeHandler) {
147 logger.trace("Set bridge handler {}", handler);
148 shcBridgeHandler = bridgeHandler;
153 public @Nullable ThingHandler getThingHandler() {
154 return shcBridgeHandler;
157 public void doScan() throws InterruptedException {
158 logger.debug("Start manual scan on bridge {}", shcBridgeHandler.getThing().getUID());
159 // use shcBridgeHandler to getDevices()
160 List<Room> rooms = shcBridgeHandler.getRooms();
161 logger.debug("SHC has {} rooms", rooms.size());
162 List<Device> devices = shcBridgeHandler.getDevices();
163 logger.debug("SHC has {} devices", devices.size());
165 // Write found devices into openhab.log to support manual configuration
166 for (Device d : devices) {
167 logger.debug("Found device: name={} id={}", d.name, d.id);
168 if (d.deviceServiceIds != null) {
169 for (String s : d.deviceServiceIds) {
170 logger.debug(".... service: {}", s);
175 addDevices(devices, rooms);
178 protected void addDevices(List<Device> devices, List<Room> rooms) {
179 for (Device device : devices) {
180 addDevice(device, getRoomNameForDevice(device, rooms));
184 protected String getRoomNameForDevice(Device device, List<Room> rooms) {
185 return rooms.stream().filter(room -> room.id.equals(device.roomId)).findAny().map(r -> r.name).orElse("");
188 protected void addDevice(Device device, String roomName) {
189 // see startScan for the runtime null check of shcBridgeHandler
190 assert shcBridgeHandler != null;
192 logger.trace("Discovering device {}", device.name);
193 logger.trace("- details: id {}, roomId {}, deviceModel {}", device.id, device.roomId, device.deviceModel);
195 ThingTypeUID thingTypeUID = getThingTypeUID(device);
196 if (thingTypeUID == null) {
200 logger.trace("- got thingTypeID '{}' for deviceModel '{}'", thingTypeUID.getId(), device.deviceModel);
202 ThingUID thingUID = new ThingUID(thingTypeUID, shcBridgeHandler.getThing().getUID(),
203 device.id.replace(':', '_'));
205 logger.trace("- got thingUID '{}' for device: '{}'", thingUID, device);
207 DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
208 .withProperty("id", device.id).withLabel(getNiceName(device.name, roomName));
209 if (null != shcBridgeHandler) {
210 discoveryResult.withBridge(shcBridgeHandler.getThing().getUID());
212 if (!roomName.isEmpty()) {
213 discoveryResult.withProperty("Location", roomName);
215 thingDiscovered(discoveryResult.build());
217 logger.debug("Discovered device '{}' with thingTypeUID={}, thingUID={}, id={}, deviceModel={}", device.name,
218 thingUID, thingTypeUID, device.id, device.deviceModel);
221 private String getNiceName(String name, String roomName) {
222 if (!name.startsWith("-")) {
226 // convert "-IntrusionDetectionSystem-" into "Intrusion Detection System"
227 // convert "-RoomClimateControl-" into "Room Climate Control myRoomName"
228 final char[] chars = name.toCharArray();
229 StringBuilder niceNameBuilder = new StringBuilder(32);
230 for (int pos = 0; pos < chars.length; pos++) {
232 if (chars[pos] == '-') {
235 // convert "CamelCase" into "Camel Case", skipping the first Uppercase after the "-"
236 if (pos > 1 && Character.getType(chars[pos]) == Character.UPPERCASE_LETTER) {
237 niceNameBuilder.append(" ");
239 niceNameBuilder.append(chars[pos]);
241 // append roomName for "Room Climate Control", because it appears for each room with a thermostat
242 if (!roomName.isEmpty() && niceNameBuilder.toString().startsWith("Room Climate Control")) {
243 niceNameBuilder.append(" ").append(roomName);
245 return niceNameBuilder.toString();
248 protected @Nullable ThingTypeUID getThingTypeUID(Device device) {
250 ThingTypeUID thingTypeId = DEVICEMODEL_TO_THINGTYPE_MAP.get(device.deviceModel);
251 if (thingTypeId != null) {
252 return new ThingTypeUID(BoschSHCBindingConstants.BINDING_ID, thingTypeId.getId());
254 logger.debug("Unknown deviceModel '{}'! Please create a support request issue for this unknown device model.",