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