2 * Copyright (c) 2010-2024 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.time.Instant;
16 import java.util.AbstractMap;
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.binding.boschshc.internal.devices.bridge.dto.UserDefinedState;
28 import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService;
29 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
30 import org.openhab.core.thing.ThingTypeUID;
31 import org.openhab.core.thing.ThingUID;
32 import org.openhab.core.thing.binding.ThingHandlerService;
33 import org.osgi.service.component.annotations.Component;
34 import org.osgi.service.component.annotations.ServiceScope;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * The {@link ThingDiscoveryService} is responsible to discover Bosch Smart Home things.
40 * The paired SHC BridgeHandler is required to get the lists of rooms and devices.
41 * With this data the openhab things are discovered.
43 * The order to make this work is
44 * 1. SHC bridge is created, e.v via openhab UI
45 * 2. Service is instantiated setBridgeHandler of this service is called
46 * 3. Service is activated
47 * 4. Service registers itself as discoveryLister at the bridge
48 * 5. bridge calls startScan after bridge is paired and things can be discovered
50 * @author Gerd Zanker - Initial contribution
52 @Component(scope = ServiceScope.PROTOTYPE, service = ThingHandlerService.class)
54 public class ThingDiscoveryService extends AbstractThingHandlerDiscoveryService<BridgeHandler> {
55 private static final int SEARCH_TIME = 1;
57 private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class);
59 protected static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(
60 BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH, BoschSHCBindingConstants.THING_TYPE_TWINGUARD,
61 BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT, BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT_2,
62 BoschSHCBindingConstants.THING_TYPE_MOTION_DETECTOR, BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL,
63 BoschSHCBindingConstants.THING_TYPE_THERMOSTAT, BoschSHCBindingConstants.THING_TYPE_CLIMATE_CONTROL,
64 BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT, BoschSHCBindingConstants.THING_TYPE_CAMERA_360,
65 BoschSHCBindingConstants.THING_TYPE_CAMERA_EYES,
66 BoschSHCBindingConstants.THING_TYPE_INTRUSION_DETECTION_SYSTEM,
67 BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT, BoschSHCBindingConstants.THING_TYPE_SMART_BULB,
68 BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR);
71 protected static final Map<String, ThingTypeUID> DEVICEMODEL_TO_THINGTYPE_MAP = Map.ofEntries(
72 new AbstractMap.SimpleEntry<>("BBL", BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL),
73 new AbstractMap.SimpleEntry<>("TWINGUARD", BoschSHCBindingConstants.THING_TYPE_TWINGUARD),
74 new AbstractMap.SimpleEntry<>("BSM", BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH),
75 new AbstractMap.SimpleEntry<>("PSM", BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT),
76 new AbstractMap.SimpleEntry<>("PLUG_COMPACT", BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT),
77 new AbstractMap.SimpleEntry<>("CAMERA_360", BoschSHCBindingConstants.THING_TYPE_CAMERA_360),
78 new AbstractMap.SimpleEntry<>("CAMERA_EYES", BoschSHCBindingConstants.THING_TYPE_CAMERA_EYES),
79 new AbstractMap.SimpleEntry<>("BWTH", BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT), // wall thermostat
80 new AbstractMap.SimpleEntry<>("THB", BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT), // wall thermostat with batteries
81 new AbstractMap.SimpleEntry<>("SD", BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR),
82 new AbstractMap.SimpleEntry<>("MD", BoschSHCBindingConstants.THING_TYPE_MOTION_DETECTOR),
83 new AbstractMap.SimpleEntry<>("ROOM_CLIMATE_CONTROL", BoschSHCBindingConstants.THING_TYPE_CLIMATE_CONTROL),
84 new AbstractMap.SimpleEntry<>("INTRUSION_DETECTION_SYSTEM", BoschSHCBindingConstants.THING_TYPE_INTRUSION_DETECTION_SYSTEM),
85 new AbstractMap.SimpleEntry<>("HUE_LIGHT", BoschSHCBindingConstants.THING_TYPE_SMART_BULB),
86 new AbstractMap.SimpleEntry<>("LEDVANCE_LIGHT", BoschSHCBindingConstants.THING_TYPE_SMART_BULB),
87 new AbstractMap.SimpleEntry<>("SWD", BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT),
88 new AbstractMap.SimpleEntry<>("SWD2", BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT_2),
89 new AbstractMap.SimpleEntry<>("TRV", BoschSHCBindingConstants.THING_TYPE_THERMOSTAT),
90 new AbstractMap.SimpleEntry<>("WRC2", BoschSHCBindingConstants.THING_TYPE_UNIVERSAL_SWITCH),
91 new AbstractMap.SimpleEntry<>("SWITCH2", BoschSHCBindingConstants.THING_TYPE_UNIVERSAL_SWITCH_2)
92 // Future Extension: map deviceModel names to BoschSHC Thing Types when they are supported
93 // new AbstractMap.SimpleEntry<>("SMOKE_DETECTION_SYSTEM", BoschSHCBindingConstants.),
94 // new AbstractMap.SimpleEntry<>("PRESENCE_SIMULATION_SERVICE", BoschSHCBindingConstants.),
95 // new AbstractMap.SimpleEntry<>("VENTILATION_SERVICE", BoschSHCBindingConstants.),
96 // new AbstractMap.SimpleEntry<>("HUE_BRIDGE", BoschSHCBindingConstants.)
97 // new AbstractMap.SimpleEntry<>("HUE_BRIDGE_MANAGER*", BoschSHCBindingConstants.)
98 // new AbstractMap.SimpleEntry<>("HUE_LIGHT_ROOM_CONTROL", BoschSHCBindingConstants.)
102 public ThingDiscoveryService() {
103 super(BridgeHandler.class, SUPPORTED_THING_TYPES, SEARCH_TIME);
107 public void initialize() {
108 logger.trace("initialize");
109 thingHandler.registerDiscoveryListener(this);
114 public void dispose() {
116 logger.trace("dispose");
117 removeOlderResults(Instant.now().toEpochMilli(), thingHandler.getThing().getUID());
118 thingHandler.unregisterDiscoveryListener();
124 protected void startScan() {
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 {}", thingHandler.getThing().getUID());
137 removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID());
140 public void doScan() throws InterruptedException {
141 logger.debug("Start manual scan on bridge {}", thingHandler.getThing().getUID());
142 // use shcBridgeHandler to getDevices()
143 List<Room> rooms = thingHandler.getRooms();
144 logger.debug("SHC has {} rooms", rooms.size());
145 List<Device> devices = thingHandler.getDevices();
146 logger.debug("SHC has {} devices", devices.size());
147 List<UserDefinedState> userStates = thingHandler.getUserStates();
148 logger.debug("SHC has {} user-defined states", userStates.size());
150 // Write found devices into openhab.log to support manual configuration
151 for (Device d : devices) {
152 logger.debug("Found device: name={} id={}", d.name, d.id);
153 if (d.deviceServiceIds != null) {
154 for (String s : d.deviceServiceIds) {
155 logger.debug(".... service: {}", s);
159 for (UserDefinedState userState : userStates) {
160 logger.debug("Found user-defined state: name={} id={} state={}", userState.getName(), userState.getId(),
161 userState.isState());
164 addDevices(devices, rooms);
165 addUserStates(userStates);
168 protected void addUserStates(List<UserDefinedState> userStates) {
169 for (UserDefinedState userState : userStates) {
170 addUserState(userState);
174 private void addUserState(UserDefinedState userState) {
175 logger.trace("Discovering user-defined state {}", userState.getName());
176 logger.trace("- details: id {}, state {}", userState.getId(), userState.isState());
178 ThingTypeUID thingTypeUID = new ThingTypeUID(BoschSHCBindingConstants.BINDING_ID,
179 BoschSHCBindingConstants.THING_TYPE_USER_DEFINED_STATE.getId());
181 logger.trace("- got thingTypeID '{}' for user-defined state '{}'", thingTypeUID.getId(), userState.getName());
183 ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(),
184 userState.getId().replace(':', '_'));
186 logger.trace("- got thingUID '{}' for user-defined state: '{}'", thingUID, userState);
188 DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
189 .withProperty("id", userState.getId()).withLabel(userState.getName());
191 discoveryResult.withBridge(thingHandler.getThing().getUID());
193 thingDiscovered(discoveryResult.build());
195 logger.debug("Discovered user-defined state '{}' with thingTypeUID={}, thingUID={}, id={}, state={}",
196 userState.getName(), thingUID, thingTypeUID, userState.getId(), userState.isState());
199 protected void addDevices(List<Device> devices, List<Room> rooms) {
200 for (Device device : devices) {
201 addDevice(device, getRoomNameForDevice(device, rooms));
205 protected String getRoomNameForDevice(Device device, List<Room> rooms) {
206 return rooms.stream().filter(room -> room.id.equals(device.roomId)).findAny().map(r -> r.name).orElse("");
209 protected void addDevice(Device device, String roomName) {
210 // see startScan for the runtime null check of shcBridgeHandler
211 logger.trace("Discovering device {}", device.name);
212 logger.trace("- details: id {}, roomId {}, deviceModel {}", device.id, device.roomId, device.deviceModel);
214 ThingTypeUID thingTypeUID = getThingTypeUID(device);
215 if (thingTypeUID == null) {
219 logger.trace("- got thingTypeID '{}' for deviceModel '{}'", thingTypeUID.getId(), device.deviceModel);
221 ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(), device.id.replace(':', '_'));
223 logger.trace("- got thingUID '{}' for device: '{}'", thingUID, device);
225 DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
226 .withProperty("id", device.id).withLabel(getNiceName(device.name, roomName));
227 discoveryResult.withBridge(thingHandler.getThing().getUID());
228 if (!roomName.isEmpty()) {
229 discoveryResult.withProperty("Location", roomName);
231 thingDiscovered(discoveryResult.build());
233 logger.debug("Discovered device '{}' with thingTypeUID={}, thingUID={}, id={}, deviceModel={}", device.name,
234 thingUID, thingTypeUID, device.id, device.deviceModel);
237 private String getNiceName(String name, String roomName) {
238 if (!name.startsWith("-")) {
242 // convert "-IntrusionDetectionSystem-" into "Intrusion Detection System"
243 // convert "-RoomClimateControl-" into "Room Climate Control myRoomName"
244 final char[] chars = name.toCharArray();
245 StringBuilder niceNameBuilder = new StringBuilder(32);
246 for (int pos = 0; pos < chars.length; pos++) {
248 if (chars[pos] == '-') {
251 // convert "CamelCase" into "Camel Case", skipping the first Uppercase after the "-"
252 if (pos > 1 && Character.getType(chars[pos]) == Character.UPPERCASE_LETTER) {
253 niceNameBuilder.append(" ");
255 niceNameBuilder.append(chars[pos]);
257 // append roomName for "Room Climate Control", because it appears for each room with a thermostat
258 if (!roomName.isEmpty() && niceNameBuilder.toString().startsWith("Room Climate Control")) {
259 niceNameBuilder.append(" ").append(roomName);
261 return niceNameBuilder.toString();
264 protected @Nullable ThingTypeUID getThingTypeUID(Device device) {
266 ThingTypeUID thingTypeId = DEVICEMODEL_TO_THINGTYPE_MAP.get(device.deviceModel);
267 if (thingTypeId != null) {
268 return new ThingTypeUID(BoschSHCBindingConstants.BINDING_ID, thingTypeId.getId());
270 logger.debug("Unknown deviceModel '{}'! Please create a support request issue for this unknown device model.",