]> git.basschouten.com Git - openhab-addons.git/blob
a647b1d6a857a1b95c5a440ba812402ff597e9a0
[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.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;
35
36 /**
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.
40  *
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
47  *
48  * @author Gerd Zanker - Initial contribution
49  */
50 @NonNullByDefault
51 public class ThingDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
52     private static final int SEARCH_TIME = 1;
53
54     private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class);
55     private @Nullable BridgeHandler shcBridgeHandler;
56
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);
66
67     // @formatter:off
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.)
90             );
91     // @formatter:on
92
93     public ThingDiscoveryService() {
94         super(SUPPORTED_THING_TYPES, SEARCH_TIME);
95     }
96
97     @Override
98     public void activate() {
99         logger.trace("activate");
100         final BridgeHandler handler = shcBridgeHandler;
101         if (handler != null) {
102             handler.registerDiscoveryListener(this);
103         }
104     }
105
106     @Override
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();
113         }
114
115         super.deactivate();
116     }
117
118     @Override
119     protected void startScan() {
120         if (shcBridgeHandler == null) {
121             logger.debug("The shcBridgeHandler is empty, no manual scan is currently possible");
122             return;
123         }
124
125         try {
126             doScan();
127         } catch (InterruptedException e) {
128             // Restore interrupted state...
129             Thread.currentThread().interrupt();
130         }
131     }
132
133     @Override
134     protected synchronized void stopScan() {
135         logger.debug("Stop manual scan on bridge {}",
136                 shcBridgeHandler != null ? shcBridgeHandler.getThing().getUID() : "?");
137         super.stopScan();
138         final BridgeHandler handler = shcBridgeHandler;
139         if (handler != null) {
140             removeOlderResults(getTimestampOfLastScan(), handler.getThing().getUID());
141         }
142     }
143
144     @Override
145     public void setThingHandler(@Nullable ThingHandler handler) {
146         if (handler instanceof BridgeHandler bridgeHandler) {
147             logger.trace("Set bridge handler {}", handler);
148             shcBridgeHandler = bridgeHandler;
149         }
150     }
151
152     @Override
153     public @Nullable ThingHandler getThingHandler() {
154         return shcBridgeHandler;
155     }
156
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());
164
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);
171                 }
172             }
173         }
174
175         addDevices(devices, rooms);
176     }
177
178     protected void addDevices(List<Device> devices, List<Room> rooms) {
179         for (Device device : devices) {
180             addDevice(device, getRoomNameForDevice(device, rooms));
181         }
182     }
183
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("");
186     }
187
188     protected void addDevice(Device device, String roomName) {
189         // see startScan for the runtime null check of shcBridgeHandler
190         assert shcBridgeHandler != null;
191
192         logger.trace("Discovering device {}", device.name);
193         logger.trace("- details: id {}, roomId {}, deviceModel {}", device.id, device.roomId, device.deviceModel);
194
195         ThingTypeUID thingTypeUID = getThingTypeUID(device);
196         if (thingTypeUID == null) {
197             return;
198         }
199
200         logger.trace("- got thingTypeID '{}' for deviceModel '{}'", thingTypeUID.getId(), device.deviceModel);
201
202         ThingUID thingUID = new ThingUID(thingTypeUID, shcBridgeHandler.getThing().getUID(),
203                 device.id.replace(':', '_'));
204
205         logger.trace("- got thingUID '{}' for device: '{}'", thingUID, device);
206
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());
211         }
212         if (!roomName.isEmpty()) {
213             discoveryResult.withProperty("Location", roomName);
214         }
215         thingDiscovered(discoveryResult.build());
216
217         logger.debug("Discovered device '{}' with thingTypeUID={}, thingUID={}, id={}, deviceModel={}", device.name,
218                 thingUID, thingTypeUID, device.id, device.deviceModel);
219     }
220
221     private String getNiceName(String name, String roomName) {
222         if (!name.startsWith("-")) {
223             return name;
224         }
225
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++) {
231             // skip "-"
232             if (chars[pos] == '-') {
233                 continue;
234             }
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(" ");
238             }
239             niceNameBuilder.append(chars[pos]);
240         }
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);
244         }
245         return niceNameBuilder.toString();
246     }
247
248     protected @Nullable ThingTypeUID getThingTypeUID(Device device) {
249         @Nullable
250         ThingTypeUID thingTypeId = DEVICEMODEL_TO_THINGTYPE_MAP.get(device.deviceModel);
251         if (thingTypeId != null) {
252             return new ThingTypeUID(BoschSHCBindingConstants.BINDING_ID, thingTypeId.getId());
253         }
254         logger.debug("Unknown deviceModel '{}'! Please create a support request issue for this unknown device model.",
255                 device.deviceModel);
256         return null;
257     }
258 }