]> git.basschouten.com Git - openhab-addons.git/blob
6a8918593d57a458d8765e241e74a7332d7e3dfb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.boschshc.internal.discovery;
14
15 import java.util.AbstractMap;
16 import java.util.Date;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Set;
20
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.AbstractDiscoveryService;
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.ThingHandler;
33 import org.openhab.core.thing.binding.ThingHandlerService;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * The {@link ThingDiscoveryService} is responsible to discover Bosch Smart Home things.
39  * The paired SHC BridgeHandler is required to get the lists of rooms and devices.
40  * With this data the openhab things are discovered.
41  *
42  * The order to make this work is
43  * 1. SHC bridge is created, e.v via openhab UI
44  * 2. Service is instantiated setBridgeHandler of this service is called
45  * 3. Service is activated
46  * 4. Service registers itself as discoveryLister at the bridge
47  * 5. bridge calls startScan after bridge is paired and things can be discovered
48  *
49  * @author Gerd Zanker - Initial contribution
50  */
51 @NonNullByDefault
52 public class ThingDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
53     private static final int SEARCH_TIME = 1;
54
55     private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class);
56     private @Nullable BridgeHandler shcBridgeHandler;
57
58     protected static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(
59             BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH, BoschSHCBindingConstants.THING_TYPE_TWINGUARD,
60             BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT, BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT_2,
61             BoschSHCBindingConstants.THING_TYPE_MOTION_DETECTOR, BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL,
62             BoschSHCBindingConstants.THING_TYPE_THERMOSTAT, BoschSHCBindingConstants.THING_TYPE_CLIMATE_CONTROL,
63             BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT, BoschSHCBindingConstants.THING_TYPE_CAMERA_360,
64             BoschSHCBindingConstants.THING_TYPE_CAMERA_EYES,
65             BoschSHCBindingConstants.THING_TYPE_INTRUSION_DETECTION_SYSTEM,
66             BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT, BoschSHCBindingConstants.THING_TYPE_SMART_BULB,
67             BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR);
68
69     // @formatter:off
70     protected static final Map<String, ThingTypeUID> DEVICEMODEL_TO_THINGTYPE_MAP = Map.ofEntries(
71             new AbstractMap.SimpleEntry<>("BBL", BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL),
72             new AbstractMap.SimpleEntry<>("TWINGUARD", BoschSHCBindingConstants.THING_TYPE_TWINGUARD),
73             new AbstractMap.SimpleEntry<>("BSM", BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH),
74             new AbstractMap.SimpleEntry<>("PSM", BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT),
75             new AbstractMap.SimpleEntry<>("PLUG_COMPACT", BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT),
76             new AbstractMap.SimpleEntry<>("CAMERA_360", BoschSHCBindingConstants.THING_TYPE_CAMERA_360),
77             new AbstractMap.SimpleEntry<>("CAMERA_EYES", BoschSHCBindingConstants.THING_TYPE_CAMERA_EYES),
78             new AbstractMap.SimpleEntry<>("BWTH", BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT), // wall thermostat
79             new AbstractMap.SimpleEntry<>("THB", BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT), // wall thermostat with batteries
80             new AbstractMap.SimpleEntry<>("SD", BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR),
81             new AbstractMap.SimpleEntry<>("MD", BoschSHCBindingConstants.THING_TYPE_MOTION_DETECTOR),
82             new AbstractMap.SimpleEntry<>("ROOM_CLIMATE_CONTROL", BoschSHCBindingConstants.THING_TYPE_CLIMATE_CONTROL),
83             new AbstractMap.SimpleEntry<>("INTRUSION_DETECTION_SYSTEM", BoschSHCBindingConstants.THING_TYPE_INTRUSION_DETECTION_SYSTEM),
84             new AbstractMap.SimpleEntry<>("HUE_LIGHT", BoschSHCBindingConstants.THING_TYPE_SMART_BULB),
85             new AbstractMap.SimpleEntry<>("LEDVANCE_LIGHT", BoschSHCBindingConstants.THING_TYPE_SMART_BULB),
86             new AbstractMap.SimpleEntry<>("SWD", BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT),
87             new AbstractMap.SimpleEntry<>("SWD2", BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT_2),
88             new AbstractMap.SimpleEntry<>("TRV", BoschSHCBindingConstants.THING_TYPE_THERMOSTAT)
89 // Future Extension: map deviceModel names to BoschSHC Thing Types when they are supported
90 //            new AbstractMap.SimpleEntry<>("SMOKE_DETECTION_SYSTEM", BoschSHCBindingConstants.),
91 //            new AbstractMap.SimpleEntry<>("PRESENCE_SIMULATION_SERVICE", BoschSHCBindingConstants.),
92 //            new AbstractMap.SimpleEntry<>("VENTILATION_SERVICE", BoschSHCBindingConstants.),
93 //            new AbstractMap.SimpleEntry<>("HUE_BRIDGE", BoschSHCBindingConstants.)
94 //            new AbstractMap.SimpleEntry<>("HUE_BRIDGE_MANAGER*", BoschSHCBindingConstants.)
95 //            new AbstractMap.SimpleEntry<>("HUE_LIGHT_ROOM_CONTROL", BoschSHCBindingConstants.)
96             );
97     // @formatter:on
98
99     public ThingDiscoveryService() {
100         super(SUPPORTED_THING_TYPES, SEARCH_TIME);
101     }
102
103     @Override
104     public void activate() {
105         logger.trace("activate");
106         final BridgeHandler handler = shcBridgeHandler;
107         if (handler != null) {
108             handler.registerDiscoveryListener(this);
109         }
110     }
111
112     @Override
113     public void deactivate() {
114         logger.trace("deactivate");
115         final BridgeHandler handler = shcBridgeHandler;
116         if (handler != null) {
117             removeOlderResults(new Date().getTime(), handler.getThing().getUID());
118             handler.unregisterDiscoveryListener();
119         }
120
121         super.deactivate();
122     }
123
124     @Override
125     protected void startScan() {
126         if (shcBridgeHandler == null) {
127             logger.debug("The shcBridgeHandler is empty, no manual scan is currently possible");
128             return;
129         }
130
131         try {
132             doScan();
133         } catch (InterruptedException e) {
134             // Restore interrupted state...
135             Thread.currentThread().interrupt();
136         }
137     }
138
139     @Override
140     protected synchronized void stopScan() {
141         logger.debug("Stop manual scan on bridge {}",
142                 shcBridgeHandler != null ? shcBridgeHandler.getThing().getUID() : "?");
143         super.stopScan();
144         final BridgeHandler handler = shcBridgeHandler;
145         if (handler != null) {
146             removeOlderResults(getTimestampOfLastScan(), handler.getThing().getUID());
147         }
148     }
149
150     @Override
151     public void setThingHandler(@Nullable ThingHandler handler) {
152         if (handler instanceof BridgeHandler bridgeHandler) {
153             logger.trace("Set bridge handler {}", handler);
154             shcBridgeHandler = bridgeHandler;
155         }
156     }
157
158     @Override
159     public @Nullable ThingHandler getThingHandler() {
160         return shcBridgeHandler;
161     }
162
163     public void doScan() throws InterruptedException {
164         logger.debug("Start manual scan on bridge {}", shcBridgeHandler.getThing().getUID());
165         // use shcBridgeHandler to getDevices()
166         List<Room> rooms = shcBridgeHandler.getRooms();
167         logger.debug("SHC has {} rooms", rooms.size());
168         List<Device> devices = shcBridgeHandler.getDevices();
169         logger.debug("SHC has {} devices", devices.size());
170         List<UserDefinedState> userStates = shcBridgeHandler.getUserStates();
171         logger.debug("SHC has {} user-defined states", userStates.size());
172
173         // Write found devices into openhab.log to support manual configuration
174         for (Device d : devices) {
175             logger.debug("Found device: name={} id={}", d.name, d.id);
176             if (d.deviceServiceIds != null) {
177                 for (String s : d.deviceServiceIds) {
178                     logger.debug(".... service: {}", s);
179                 }
180             }
181         }
182         for (UserDefinedState userState : userStates) {
183             logger.debug("Found user-defined state: name={} id={} state={}", userState.getName(), userState.getId(),
184                     userState.isState());
185         }
186
187         addDevices(devices, rooms);
188         addUserStates(userStates);
189     }
190
191     protected void addUserStates(List<UserDefinedState> userStates) {
192         for (UserDefinedState userState : userStates) {
193             addUserState(userState);
194         }
195     }
196
197     private void addUserState(UserDefinedState userState) {
198         // see startScan for the runtime null check of shcBridgeHandler
199         assert shcBridgeHandler != null;
200
201         logger.trace("Discovering user-defined state {}", userState.getName());
202         logger.trace("- details: id {}, state {}", userState.getId(), userState.isState());
203
204         ThingTypeUID thingTypeUID = new ThingTypeUID(BoschSHCBindingConstants.BINDING_ID,
205                 BoschSHCBindingConstants.THING_TYPE_USER_DEFINED_STATE.getId());
206
207         logger.trace("- got thingTypeID '{}' for user-defined state '{}'", thingTypeUID.getId(), userState.getName());
208
209         ThingUID thingUID = new ThingUID(thingTypeUID, shcBridgeHandler.getThing().getUID(),
210                 userState.getId().replace(':', '_'));
211
212         logger.trace("- got thingUID '{}' for user-defined state: '{}'", thingUID, userState);
213
214         DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
215                 .withProperty("id", userState.getId()).withLabel(userState.getName());
216
217         discoveryResult.withBridge(shcBridgeHandler.getThing().getUID());
218
219         thingDiscovered(discoveryResult.build());
220
221         logger.debug("Discovered user-defined state '{}' with thingTypeUID={}, thingUID={}, id={}, state={}",
222                 userState.getName(), thingUID, thingTypeUID, userState.getId(), userState.isState());
223     }
224
225     protected void addDevices(List<Device> devices, List<Room> rooms) {
226         for (Device device : devices) {
227             addDevice(device, getRoomNameForDevice(device, rooms));
228         }
229     }
230
231     protected String getRoomNameForDevice(Device device, List<Room> rooms) {
232         return rooms.stream().filter(room -> room.id.equals(device.roomId)).findAny().map(r -> r.name).orElse("");
233     }
234
235     protected void addDevice(Device device, String roomName) {
236         // see startScan for the runtime null check of shcBridgeHandler
237         assert shcBridgeHandler != null;
238
239         logger.trace("Discovering device {}", device.name);
240         logger.trace("- details: id {}, roomId {}, deviceModel {}", device.id, device.roomId, device.deviceModel);
241
242         ThingTypeUID thingTypeUID = getThingTypeUID(device);
243         if (thingTypeUID == null) {
244             return;
245         }
246
247         logger.trace("- got thingTypeID '{}' for deviceModel '{}'", thingTypeUID.getId(), device.deviceModel);
248
249         ThingUID thingUID = new ThingUID(thingTypeUID, shcBridgeHandler.getThing().getUID(),
250                 device.id.replace(':', '_'));
251
252         logger.trace("- got thingUID '{}' for device: '{}'", thingUID, device);
253
254         DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
255                 .withProperty("id", device.id).withLabel(getNiceName(device.name, roomName));
256         if (null != shcBridgeHandler) {
257             discoveryResult.withBridge(shcBridgeHandler.getThing().getUID());
258         }
259         if (!roomName.isEmpty()) {
260             discoveryResult.withProperty("Location", roomName);
261         }
262         thingDiscovered(discoveryResult.build());
263
264         logger.debug("Discovered device '{}' with thingTypeUID={}, thingUID={}, id={}, deviceModel={}", device.name,
265                 thingUID, thingTypeUID, device.id, device.deviceModel);
266     }
267
268     private String getNiceName(String name, String roomName) {
269         if (!name.startsWith("-")) {
270             return name;
271         }
272
273         // convert "-IntrusionDetectionSystem-" into "Intrusion Detection System"
274         // convert "-RoomClimateControl-" into "Room Climate Control myRoomName"
275         final char[] chars = name.toCharArray();
276         StringBuilder niceNameBuilder = new StringBuilder(32);
277         for (int pos = 0; pos < chars.length; pos++) {
278             // skip "-"
279             if (chars[pos] == '-') {
280                 continue;
281             }
282             // convert "CamelCase" into "Camel Case", skipping the first Uppercase after the "-"
283             if (pos > 1 && Character.getType(chars[pos]) == Character.UPPERCASE_LETTER) {
284                 niceNameBuilder.append(" ");
285             }
286             niceNameBuilder.append(chars[pos]);
287         }
288         // append roomName for "Room Climate Control", because it appears for each room with a thermostat
289         if (!roomName.isEmpty() && niceNameBuilder.toString().startsWith("Room Climate Control")) {
290             niceNameBuilder.append(" ").append(roomName);
291         }
292         return niceNameBuilder.toString();
293     }
294
295     protected @Nullable ThingTypeUID getThingTypeUID(Device device) {
296         @Nullable
297         ThingTypeUID thingTypeId = DEVICEMODEL_TO_THINGTYPE_MAP.get(device.deviceModel);
298         if (thingTypeId != null) {
299             return new ThingTypeUID(BoschSHCBindingConstants.BINDING_ID, thingTypeId.getId());
300         }
301         logger.debug("Unknown deviceModel '{}'! Please create a support request issue for this unknown device model.",
302                 device.deviceModel);
303         return null;
304     }
305 }