]> git.basschouten.com Git - openhab-addons.git/blob
2cb40b64069f43ff3db2b1fd548538e816d23e4a
[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.amazonechocontrol.internal.discovery;
14
15 import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.*;
16
17 import java.util.Date;
18 import java.util.HashMap;
19 import java.util.Hashtable;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.stream.Collectors;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.amazonechocontrol.internal.Connection;
30 import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
31 import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
32 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDeviceAlias;
33 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.DriverIdentity;
34 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
35 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeGroups.SmartHomeGroup;
36 import org.openhab.binding.amazonechocontrol.internal.jsons.SmartHomeBaseDevice;
37 import org.openhab.binding.amazonechocontrol.internal.smarthome.Constants;
38 import org.openhab.core.config.discovery.AbstractDiscoveryService;
39 import org.openhab.core.config.discovery.DiscoveryResult;
40 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
41 import org.openhab.core.thing.ThingUID;
42 import org.osgi.service.component.annotations.Activate;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * @author Lukas Knoeller - Initial contribution
48  */
49 @NonNullByDefault
50 public class SmartHomeDevicesDiscovery extends AbstractDiscoveryService {
51     private AccountHandler accountHandler;
52     private Logger logger = LoggerFactory.getLogger(SmartHomeDevicesDiscovery.class);
53
54     private @Nullable ScheduledFuture<?> startScanStateJob;
55     private @Nullable Long activateTimeStamp;
56
57     public SmartHomeDevicesDiscovery(AccountHandler accountHandler) {
58         super(SUPPORTED_SMART_HOME_THING_TYPES_UIDS, 10);
59         this.accountHandler = accountHandler;
60     }
61
62     public void activate() {
63         activate(new Hashtable<String, Object>());
64     }
65
66     @Override
67     public void deactivate() {
68         super.deactivate();
69     }
70
71     @Override
72     protected void startScan() {
73         stopScanJob();
74         Long activateTimeStamp = this.activateTimeStamp;
75         if (activateTimeStamp != null) {
76             removeOlderResults(activateTimeStamp);
77         }
78         setSmartHomeDevices(accountHandler.updateSmartHomeDeviceList(false));
79     }
80
81     protected void startAutomaticScan() {
82         if (!this.accountHandler.getThing().getThings().isEmpty()) {
83             stopScanJob();
84             return;
85         }
86         Connection connection = this.accountHandler.findConnection();
87         if (connection == null) {
88             return;
89         }
90         Date verifyTime = connection.tryGetVerifyTime();
91         if (verifyTime == null) {
92             return;
93         }
94         if (new Date().getTime() - verifyTime.getTime() < 10000) {
95             return;
96         }
97         startScan();
98     }
99
100     @Override
101     protected void startBackgroundDiscovery() {
102         stopScanJob();
103         startScanStateJob = scheduler.scheduleWithFixedDelay(this::startAutomaticScan, 3000, 1000,
104                 TimeUnit.MILLISECONDS);
105     }
106
107     @Override
108     protected void stopBackgroundDiscovery() {
109         stopScanJob();
110     }
111
112     void stopScanJob() {
113         ScheduledFuture<?> currentStartScanStateJob = startScanStateJob;
114         if (currentStartScanStateJob != null) {
115             currentStartScanStateJob.cancel(false);
116             startScanStateJob = null;
117         }
118         super.stopScan();
119     }
120
121     @Override
122     @Activate
123     public void activate(@Nullable Map<String, Object> config) {
124         super.activate(config);
125         if (config != null) {
126             modified(config);
127         }
128         Long activateTimeStamp = this.activateTimeStamp;
129         if (activateTimeStamp == null) {
130             this.activateTimeStamp = new Date().getTime();
131         }
132     };
133
134     synchronized void setSmartHomeDevices(List<SmartHomeBaseDevice> deviceList) {
135         int smartHomeDeviceDiscoveryMode = accountHandler.getSmartHomeDevicesDiscoveryMode();
136         if (smartHomeDeviceDiscoveryMode == 0) {
137             return;
138         }
139
140         for (Object smartHomeDevice : deviceList) {
141             ThingUID bridgeThingUID = this.accountHandler.getThing().getUID();
142             ThingUID thingUID = null;
143             String deviceName = null;
144             Map<String, Object> props = new HashMap<>();
145
146             if (smartHomeDevice instanceof SmartHomeDevice) {
147                 SmartHomeDevice shd = (SmartHomeDevice) smartHomeDevice;
148                 logger.trace("Found SmartHome device: {}", shd);
149
150                 String entityId = shd.entityId;
151                 if (entityId == null) {
152                     // No entity id
153                     continue;
154                 }
155                 String id = shd.findId();
156                 if (id == null) {
157                     // No id
158                     continue;
159                 }
160                 boolean isSkillDevice = false;
161                 DriverIdentity driverIdentity = shd.driverIdentity;
162                 isSkillDevice = driverIdentity != null && "SKILL".equals(driverIdentity.namespace);
163
164                 if (smartHomeDeviceDiscoveryMode == 1 && isSkillDevice) {
165                     // Connected through skill
166                     continue;
167                 }
168                 if (!(smartHomeDeviceDiscoveryMode == 2) && "openHAB".equalsIgnoreCase(shd.manufacturerName)) {
169                     // OpenHAB device
170                     continue;
171                 }
172
173                 if (shd.getCapabilities().stream()
174                         .noneMatch(capability -> Constants.SUPPORTED_INTERFACES.contains(capability.interfaceName))) {
175                     // No supported interface found
176                     continue;
177                 }
178
179                 thingUID = new ThingUID(THING_TYPE_SMART_HOME_DEVICE, bridgeThingUID, entityId.replace(".", "-"));
180
181                 List<JsonSmartHomeDeviceAlias> aliases = shd.aliases;
182                 if ("Amazon".equals(shd.manufacturerName) && driverIdentity != null
183                         && "SonarCloudService".equals(driverIdentity.identifier)) {
184                     List<@Nullable String> interfaces = shd.getCapabilities().stream().map(c -> c.interfaceName)
185                             .collect(Collectors.toList());
186                     if (interfaces.contains("Alexa.AcousticEventSensor")) {
187                         deviceName = "Alexa Guard on " + shd.friendlyName;
188                     } else if (interfaces.contains("Alexa.ColorController")) {
189                         deviceName = "Alexa Color Controller on " + shd.friendlyName;
190                     } else if (interfaces.contains("Alexa.PowerController")) {
191                         deviceName = "Alexa Plug on " + shd.friendlyName;
192                     } else if (interfaces.contains("Alexa.ThermostatController")) {
193                         deviceName = "Alexa Smart " + shd.friendlyName;
194                     } else {
195                         deviceName = "Unknown Device on " + shd.friendlyName;
196                     }
197                 } else if ("Amazon".equals(shd.manufacturerName) && driverIdentity != null
198                         && "OnGuardSmartHomeBridgeService".equals(driverIdentity.identifier)) {
199                     deviceName = "Alexa Guard";
200                 } else if (aliases != null && !aliases.isEmpty() && aliases.get(0).friendlyName != null) {
201                     deviceName = aliases.get(0).friendlyName;
202                 } else {
203                     deviceName = shd.friendlyName;
204                 }
205                 props.put(DEVICE_PROPERTY_ID, id);
206             } else if (smartHomeDevice instanceof SmartHomeGroup) {
207                 SmartHomeGroup shg = (SmartHomeGroup) smartHomeDevice;
208                 logger.trace("Found SmartHome device: {}", shg);
209
210                 String id = shg.findId();
211                 if (id == null) {
212                     // No id
213                     continue;
214                 }
215                 Set<SmartHomeDevice> supportedChildren = SmartHomeDeviceHandler.getSupportedSmartHomeDevices(shg,
216                         deviceList);
217                 if (supportedChildren.isEmpty()) {
218                     // No children with a supported interface
219                     continue;
220                 }
221                 thingUID = new ThingUID(THING_TYPE_SMART_HOME_DEVICE_GROUP, bridgeThingUID, id.replace(".", "-"));
222                 deviceName = shg.applianceGroupName;
223                 props.put(DEVICE_PROPERTY_ID, id);
224             }
225
226             if (thingUID != null) {
227                 DiscoveryResult result = DiscoveryResultBuilder.create(thingUID).withLabel(deviceName)
228                         .withProperties(props).withBridge(bridgeThingUID).build();
229
230                 logger.debug("Device [{}] found.", deviceName);
231
232                 thingDiscovered(result);
233             }
234         }
235     }
236 }