]> git.basschouten.com Git - openhab-addons.git/blob
c3b32271008b45b0edcb676dafc0ad83423d6697
[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.DEVICE_PROPERTY_ID;
16 import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.SUPPORTED_SMART_HOME_THING_TYPES_UIDS;
17 import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.THING_TYPE_SMART_HOME_DEVICE;
18 import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.THING_TYPE_SMART_HOME_DEVICE_GROUP;
19
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.Hashtable;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
28 import java.util.stream.Stream;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.openhab.binding.amazonechocontrol.internal.Connection;
33 import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
34 import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
35 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities;
36 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.DriverIdentity;
37 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
38 import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeGroups.SmartHomeGroup;
39 import org.openhab.binding.amazonechocontrol.internal.jsons.SmartHomeBaseDevice;
40 import org.openhab.binding.amazonechocontrol.internal.smarthome.Constants;
41 import org.openhab.core.config.discovery.AbstractDiscoveryService;
42 import org.openhab.core.config.discovery.DiscoveryResult;
43 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
44 import org.openhab.core.thing.ThingUID;
45 import org.osgi.service.component.annotations.Activate;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * @author Lukas Knoeller - Initial contribution
51  */
52 @NonNullByDefault
53 public class SmartHomeDevicesDiscovery extends AbstractDiscoveryService {
54     private AccountHandler accountHandler;
55     private final Logger logger = LoggerFactory.getLogger(SmartHomeDevicesDiscovery.class);
56
57     private @Nullable ScheduledFuture<?> startScanStateJob;
58     private @Nullable Long activateTimeStamp;
59
60     public SmartHomeDevicesDiscovery(AccountHandler accountHandler) {
61         super(SUPPORTED_SMART_HOME_THING_TYPES_UIDS, 10);
62         this.accountHandler = accountHandler;
63     }
64
65     public void activate() {
66         activate(new Hashtable<String, @Nullable Object>());
67     }
68
69     @Override
70     public void deactivate() {
71         super.deactivate();
72     }
73
74     @Override
75     protected void startScan() {
76         stopScanJob();
77         Long activateTimeStamp = this.activateTimeStamp;
78         if (activateTimeStamp != null) {
79             removeOlderResults(activateTimeStamp);
80         }
81         setSmartHomeDevices(accountHandler.updateSmartHomeDeviceList(false));
82     }
83
84     protected void startAutomaticScan() {
85         if (!this.accountHandler.getThing().getThings().isEmpty()) {
86             stopScanJob();
87             return;
88         }
89         Connection connection = this.accountHandler.findConnection();
90         if (connection == null) {
91             return;
92         }
93         Date verifyTime = connection.tryGetVerifyTime();
94         if (verifyTime == null) {
95             return;
96         }
97         if (new Date().getTime() - verifyTime.getTime() < 10000) {
98             return;
99         }
100         startScan();
101     }
102
103     @Override
104     protected void startBackgroundDiscovery() {
105         stopScanJob();
106         startScanStateJob = scheduler.scheduleWithFixedDelay(this::startAutomaticScan, 3000, 1000,
107                 TimeUnit.MILLISECONDS);
108     }
109
110     @Override
111     protected void stopBackgroundDiscovery() {
112         stopScanJob();
113     }
114
115     void stopScanJob() {
116         ScheduledFuture<?> currentStartScanStateJob = startScanStateJob;
117         if (currentStartScanStateJob != null) {
118             currentStartScanStateJob.cancel(false);
119             startScanStateJob = null;
120         }
121         super.stopScan();
122     }
123
124     @Override
125     @Activate
126     public void activate(@Nullable Map<String, @Nullable Object> config) {
127         super.activate(config);
128         if (config != null) {
129             modified(config);
130         }
131         Long activateTimeStamp = this.activateTimeStamp;
132         if (activateTimeStamp == null) {
133             this.activateTimeStamp = new Date().getTime();
134         }
135     };
136
137     synchronized void setSmartHomeDevices(List<SmartHomeBaseDevice> deviceList) {
138         int smartHomeDeviceDiscoveryMode = accountHandler.getSmartHomeDevicesDiscoveryMode();
139         if (smartHomeDeviceDiscoveryMode == 0) {
140             return;
141         }
142
143         for (Object smartHomeDevice : deviceList) {
144             ThingUID bridgeThingUID = this.accountHandler.getThing().getUID();
145             ThingUID thingUID = null;
146             String deviceName = null;
147             Map<String, Object> props = new HashMap<>();
148
149             if (smartHomeDevice instanceof SmartHomeDevice) {
150                 SmartHomeDevice shd = (SmartHomeDevice) smartHomeDevice;
151
152                 String entityId = shd.entityId;
153                 if (entityId == null) {
154                     // No entity id
155                     continue;
156                 }
157                 String id = shd.findId();
158                 if (id == null) {
159                     // No id
160                     continue;
161                 }
162                 boolean isSkillDevice = false;
163                 DriverIdentity driverIdentity = shd.driverIdentity;
164                 isSkillDevice = driverIdentity != null && "SKILL".equals(driverIdentity.namespace);
165
166                 if (smartHomeDeviceDiscoveryMode == 1 && isSkillDevice) {
167                     // Connected through skill
168                     continue;
169                 }
170                 if (!(smartHomeDeviceDiscoveryMode == 2) && "openHAB".equalsIgnoreCase(shd.manufacturerName)) {
171                     // OpenHAB device
172                     continue;
173                 }
174
175                 JsonSmartHomeCapabilities.SmartHomeCapability[] capabilities = shd.capabilities;
176                 if (capabilities == null || Stream.of(capabilities).noneMatch(capability -> capability != null
177                         && Constants.SUPPORTED_INTERFACES.contains(capability.interfaceName))) {
178                     // No supported interface found
179                     continue;
180                 }
181
182                 thingUID = new ThingUID(THING_TYPE_SMART_HOME_DEVICE, bridgeThingUID, entityId.replace(".", "-"));
183
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 (shd.aliases != null && shd.aliases.length > 0 && shd.aliases[0] != null
191                         && shd.aliases[0].friendlyName != null) {
192                     deviceName = shd.aliases[0].friendlyName;
193                 } else {
194                     deviceName = shd.friendlyName;
195                 }
196                 props.put(DEVICE_PROPERTY_ID, id);
197             }
198
199             if (smartHomeDevice instanceof SmartHomeGroup) {
200                 SmartHomeGroup shg = (SmartHomeGroup) smartHomeDevice;
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 }