]> git.basschouten.com Git - openhab-addons.git/blob
423e3acee752bf670a5adfe378d589ada0084618
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.time.Instant;
16 import java.util.AbstractMap;
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.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;
37
38 /**
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.
42  *
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
49  *
50  * @author Gerd Zanker - Initial contribution
51  */
52 @Component(scope = ServiceScope.PROTOTYPE, service = ThingHandlerService.class)
53 @NonNullByDefault
54 public class ThingDiscoveryService extends AbstractThingHandlerDiscoveryService<BridgeHandler> {
55     private static final int SEARCH_TIME = 1;
56
57     private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class);
58
59     /**
60      * Device model representing logical child devices of Light Control II
61      */
62     static final String DEVICE_MODEL_LIGHT_CONTROL_CHILD_DEVICE = "MICROMODULE_LIGHT_ATTACHED";
63
64     protected static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(
65             BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH, BoschSHCBindingConstants.THING_TYPE_TWINGUARD,
66             BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT, BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT_2,
67             BoschSHCBindingConstants.THING_TYPE_MOTION_DETECTOR, BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL,
68             BoschSHCBindingConstants.THING_TYPE_THERMOSTAT, BoschSHCBindingConstants.THING_TYPE_CLIMATE_CONTROL,
69             BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT, BoschSHCBindingConstants.THING_TYPE_CAMERA_360,
70             BoschSHCBindingConstants.THING_TYPE_CAMERA_EYES,
71             BoschSHCBindingConstants.THING_TYPE_INTRUSION_DETECTION_SYSTEM,
72             BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT, BoschSHCBindingConstants.THING_TYPE_SMART_BULB,
73             BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR);
74
75     // @formatter:off
76     public static final Map<String, ThingTypeUID> DEVICEMODEL_TO_THINGTYPE_MAP = Map.ofEntries(
77             new AbstractMap.SimpleEntry<>("BBL", BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL),
78             new AbstractMap.SimpleEntry<>("TWINGUARD", BoschSHCBindingConstants.THING_TYPE_TWINGUARD),
79             new AbstractMap.SimpleEntry<>("BSM", BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH),
80             new AbstractMap.SimpleEntry<>("PSM", BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT),
81             new AbstractMap.SimpleEntry<>("PLUG_COMPACT", BoschSHCBindingConstants.THING_TYPE_SMART_PLUG_COMPACT),
82             new AbstractMap.SimpleEntry<>("CAMERA_360", BoschSHCBindingConstants.THING_TYPE_CAMERA_360),
83             new AbstractMap.SimpleEntry<>("CAMERA_EYES", BoschSHCBindingConstants.THING_TYPE_CAMERA_EYES),
84             new AbstractMap.SimpleEntry<>("BWTH", BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT), // wall thermostat
85             new AbstractMap.SimpleEntry<>("THB", BoschSHCBindingConstants.THING_TYPE_WALL_THERMOSTAT), // wall thermostat with batteries
86             new AbstractMap.SimpleEntry<>("SD", BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR),
87             new AbstractMap.SimpleEntry<>("MD", BoschSHCBindingConstants.THING_TYPE_MOTION_DETECTOR),
88             new AbstractMap.SimpleEntry<>("ROOM_CLIMATE_CONTROL", BoschSHCBindingConstants.THING_TYPE_CLIMATE_CONTROL),
89             new AbstractMap.SimpleEntry<>("INTRUSION_DETECTION_SYSTEM", BoschSHCBindingConstants.THING_TYPE_INTRUSION_DETECTION_SYSTEM),
90             new AbstractMap.SimpleEntry<>("HUE_LIGHT", BoschSHCBindingConstants.THING_TYPE_SMART_BULB),
91             new AbstractMap.SimpleEntry<>("LEDVANCE_LIGHT", BoschSHCBindingConstants.THING_TYPE_SMART_BULB),
92             new AbstractMap.SimpleEntry<>("SWD", BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT),
93             new AbstractMap.SimpleEntry<>("SWD2", BoschSHCBindingConstants.THING_TYPE_WINDOW_CONTACT_2),
94             new AbstractMap.SimpleEntry<>("TRV", BoschSHCBindingConstants.THING_TYPE_THERMOSTAT),
95             new AbstractMap.SimpleEntry<>("WRC2", BoschSHCBindingConstants.THING_TYPE_UNIVERSAL_SWITCH),
96             new AbstractMap.SimpleEntry<>("SWITCH2", BoschSHCBindingConstants.THING_TYPE_UNIVERSAL_SWITCH_2),
97             new AbstractMap.SimpleEntry<>("SMOKE_DETECTOR2", BoschSHCBindingConstants.THING_TYPE_SMOKE_DETECTOR_2),
98             new AbstractMap.SimpleEntry<>("MICROMODULE_SHUTTER", BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL_2),
99             new AbstractMap.SimpleEntry<>("MICROMODULE_AWNING", BoschSHCBindingConstants.THING_TYPE_SHUTTER_CONTROL_2),
100             new AbstractMap.SimpleEntry<>("MICROMODULE_LIGHT_CONTROL", BoschSHCBindingConstants.THING_TYPE_LIGHT_CONTROL_2),
101             new AbstractMap.SimpleEntry<>("MICROMODULE_DIMMER", BoschSHCBindingConstants.THING_TYPE_DIMMER)
102 // Future Extension: map deviceModel names to BoschSHC Thing Types when they are supported
103 //            new AbstractMap.SimpleEntry<>("SMOKE_DETECTION_SYSTEM", BoschSHCBindingConstants.),
104 //            new AbstractMap.SimpleEntry<>("PRESENCE_SIMULATION_SERVICE", BoschSHCBindingConstants.),
105 //            new AbstractMap.SimpleEntry<>("VENTILATION_SERVICE", BoschSHCBindingConstants.),
106 //            new AbstractMap.SimpleEntry<>("HUE_BRIDGE", BoschSHCBindingConstants.)
107 //            new AbstractMap.SimpleEntry<>("HUE_BRIDGE_MANAGER*", BoschSHCBindingConstants.)
108 //            new AbstractMap.SimpleEntry<>("HUE_LIGHT_ROOM_CONTROL", BoschSHCBindingConstants.)
109             );
110     // @formatter:on
111
112     public ThingDiscoveryService() {
113         super(BridgeHandler.class, SUPPORTED_THING_TYPES, SEARCH_TIME);
114     }
115
116     @Override
117     public void initialize() {
118         logger.trace("initialize");
119         thingHandler.registerDiscoveryListener(this);
120         super.initialize();
121     }
122
123     @Override
124     public void dispose() {
125         super.dispose();
126         logger.trace("dispose");
127         removeOlderResults(Instant.now().toEpochMilli(), thingHandler.getThing().getUID());
128         thingHandler.unregisterDiscoveryListener();
129
130         super.deactivate();
131     }
132
133     @Override
134     protected void startScan() {
135         try {
136             doScan();
137         } catch (InterruptedException e) {
138             // Restore interrupted state...
139             Thread.currentThread().interrupt();
140         }
141     }
142
143     @Override
144     protected synchronized void stopScan() {
145         logger.debug("Stop manual scan on bridge {}", thingHandler.getThing().getUID());
146         super.stopScan();
147         removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID());
148     }
149
150     public void doScan() throws InterruptedException {
151         logger.debug("Start manual scan on bridge {}", thingHandler.getThing().getUID());
152         // use shcBridgeHandler to getDevices()
153         List<Room> rooms = thingHandler.getRooms();
154         logger.debug("SHC has {} rooms", rooms.size());
155         List<Device> devices = thingHandler.getDevices();
156         logger.debug("SHC has {} devices", devices.size());
157         List<UserDefinedState> userStates = thingHandler.getUserStates();
158         logger.debug("SHC has {} user-defined states", userStates.size());
159
160         // Write found devices into openhab.log to support manual configuration
161         for (Device d : devices) {
162             logger.debug("Found device: name={} id={}", d.name, d.id);
163             if (d.deviceServiceIds != null) {
164                 for (String s : d.deviceServiceIds) {
165                     logger.debug(".... service: {}", s);
166                 }
167             }
168         }
169         for (UserDefinedState userState : userStates) {
170             logger.debug("Found user-defined state: name={} id={} state={}", userState.getName(), userState.getId(),
171                     userState.isState());
172         }
173
174         addDevices(devices, rooms);
175         addUserStates(userStates);
176     }
177
178     protected void addUserStates(List<UserDefinedState> userStates) {
179         for (UserDefinedState userState : userStates) {
180             addUserState(userState);
181         }
182     }
183
184     private void addUserState(UserDefinedState userState) {
185         logger.trace("Discovering user-defined state {}", userState.getName());
186         logger.trace("- details: id {}, state {}", userState.getId(), userState.isState());
187
188         ThingTypeUID thingTypeUID = new ThingTypeUID(BoschSHCBindingConstants.BINDING_ID,
189                 BoschSHCBindingConstants.THING_TYPE_USER_DEFINED_STATE.getId());
190
191         logger.trace("- got thingTypeID '{}' for user-defined state '{}'", thingTypeUID.getId(), userState.getName());
192
193         ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(),
194                 userState.getId().replace(':', '_'));
195
196         logger.trace("- got thingUID '{}' for user-defined state: '{}'", thingUID, userState);
197
198         DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
199                 .withProperty("id", userState.getId()).withLabel(userState.getName());
200
201         discoveryResult.withBridge(thingHandler.getThing().getUID());
202
203         thingDiscovered(discoveryResult.build());
204
205         logger.debug("Discovered user-defined state '{}' with thingTypeUID={}, thingUID={}, id={}, state={}",
206                 userState.getName(), thingUID, thingTypeUID, userState.getId(), userState.isState());
207     }
208
209     protected void addDevices(List<Device> devices, List<Room> rooms) {
210         for (Device device : devices) {
211             addDevice(device, getRoomNameForDevice(device, rooms));
212         }
213     }
214
215     protected String getRoomNameForDevice(Device device, List<Room> rooms) {
216         return rooms.stream().filter(room -> room.id.equals(device.roomId)).findAny().map(r -> r.name).orElse("");
217     }
218
219     protected void addDevice(Device device, String roomName) {
220         // see startScan for the runtime null check of shcBridgeHandler
221         logger.trace("Discovering device {}", device.name);
222         logger.trace("- details: id {}, roomId {}, deviceModel {}", device.id, device.roomId, device.deviceModel);
223
224         ThingTypeUID thingTypeUID = getThingTypeUID(device);
225         if (thingTypeUID == null) {
226             return;
227         }
228
229         logger.trace("- got thingTypeID '{}' for deviceModel '{}'", thingTypeUID.getId(), device.deviceModel);
230
231         ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(),
232                 buildCompliantThingID(device.id));
233
234         logger.trace("- got thingUID '{}' for device: '{}'", thingUID, device);
235
236         DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
237                 .withProperty("id", device.id).withLabel(getNiceName(device.name, roomName));
238         discoveryResult.withBridge(thingHandler.getThing().getUID());
239
240         if (!roomName.isEmpty()) {
241             discoveryResult.withProperty("Location", roomName);
242         }
243         thingDiscovered(discoveryResult.build());
244
245         logger.debug("Discovered device '{}' with thingTypeUID={}, thingUID={}, id={}, deviceModel={}", device.name,
246                 thingUID, thingTypeUID, device.id, device.deviceModel);
247     }
248
249     /**
250      * Translates a Bosch device ID to an openHAB-compliant thing ID.
251      * <p>
252      * Characters that are not allowed in thing IDs are replaced by underscores.
253      * 
254      * @param deviceId the Bosch device ID
255      * @return the translated openHAB-compliant thing ID
256      */
257     private String buildCompliantThingID(String deviceId) {
258         return deviceId.replace(':', '_').replace('#', '_');
259     }
260
261     private String getNiceName(String name, String roomName) {
262         if (!name.startsWith("-")) {
263             return name;
264         }
265
266         // convert "-IntrusionDetectionSystem-" into "Intrusion Detection System"
267         // convert "-RoomClimateControl-" into "Room Climate Control myRoomName"
268         final char[] chars = name.toCharArray();
269         StringBuilder niceNameBuilder = new StringBuilder(32);
270         for (int pos = 0; pos < chars.length; pos++) {
271             // skip "-"
272             if (chars[pos] == '-') {
273                 continue;
274             }
275             // convert "CamelCase" into "Camel Case", skipping the first Uppercase after the "-"
276             if (pos > 1 && Character.getType(chars[pos]) == Character.UPPERCASE_LETTER) {
277                 niceNameBuilder.append(" ");
278             }
279             niceNameBuilder.append(chars[pos]);
280         }
281         // append roomName for "Room Climate Control", because it appears for each room with a thermostat
282         if (!roomName.isEmpty() && niceNameBuilder.toString().startsWith("Room Climate Control")) {
283             niceNameBuilder.append(" ").append(roomName);
284         }
285         return niceNameBuilder.toString();
286     }
287
288     protected @Nullable ThingTypeUID getThingTypeUID(Device device) {
289         @Nullable
290         ThingTypeUID thingTypeId = DEVICEMODEL_TO_THINGTYPE_MAP.get(device.deviceModel);
291         if (thingTypeId != null) {
292             return new ThingTypeUID(BoschSHCBindingConstants.BINDING_ID, thingTypeId.getId());
293         }
294
295         if (DEVICE_MODEL_LIGHT_CONTROL_CHILD_DEVICE.equals(device.deviceModel)) {
296             // Light Control II exposes a parent device and two child devices.
297             // We only add one thing for the parent device and the child devices are logically included.
298             // Therefore we do not need to add separate things for the child devices and need to suppress the
299             // log entry about the unknown device model.
300             return null;
301         }
302
303         logger.debug("Unknown deviceModel '{}'! Please create a support request issue for this unknown device model.",
304                 device.deviceModel);
305         return null;
306     }
307 }