2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.touchwand.internal.discovery;
15 import static org.openhab.binding.touchwand.internal.TouchWandBindingConstants.*;
17 import java.util.Arrays;
18 import java.util.Date;
19 import java.util.HashMap;
21 import java.util.concurrent.CopyOnWriteArraySet;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.touchwand.internal.TouchWandBridgeHandler;
29 import org.openhab.binding.touchwand.internal.TouchWandUnitStatusUpdateListener;
30 import org.openhab.binding.touchwand.internal.dto.TouchWandUnitData;
31 import org.openhab.binding.touchwand.internal.dto.TouchWandUnitFromJson;
32 import org.openhab.core.config.discovery.AbstractDiscoveryService;
33 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
34 import org.openhab.core.config.discovery.DiscoveryService;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingTypeUID;
37 import org.openhab.core.thing.ThingUID;
38 import org.openhab.core.thing.binding.ThingHandler;
39 import org.openhab.core.thing.binding.ThingHandlerService;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 import com.google.gson.JsonArray;
44 import com.google.gson.JsonElement;
45 import com.google.gson.JsonParser;
46 import com.google.gson.JsonSyntaxException;
49 * The {@link TouchWandUnitDiscoveryService} Discovery service for TouchWand units.
51 * @author Roie Geron - Initial contribution
54 public class TouchWandUnitDiscoveryService extends AbstractDiscoveryService
55 implements DiscoveryService, ThingHandlerService {
57 private static final int SEARCH_TIME_SEC = 10;
58 private static final int SCAN_INTERVAL_SEC = 60;
59 private static final int LINK_DISCOVERY_SERVICE_INITIAL_DELAY_SEC = 5;
60 private static final String[] CONNECTIVITY_OPTIONS = { CONNECTIVITY_KNX, CONNECTIVITY_ZWAVE };
61 private @NonNullByDefault({}) TouchWandBridgeHandler touchWandBridgeHandler;
62 private final Logger logger = LoggerFactory.getLogger(TouchWandUnitDiscoveryService.class);
64 private @Nullable ScheduledFuture<?> scanningJob;
65 private CopyOnWriteArraySet<TouchWandUnitStatusUpdateListener> listeners = new CopyOnWriteArraySet<>();
67 public TouchWandUnitDiscoveryService() {
68 super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME_SEC, true);
72 protected void startScan() {
73 if (touchWandBridgeHandler.getThing().getStatus() != ThingStatus.ONLINE) {
74 logger.debug("Could not scan units while bridge offline");
78 logger.debug("Starting TouchWand discovery on bridge {}", touchWandBridgeHandler.getThing().getUID());
79 String response = touchWandBridgeHandler.touchWandClient.cmdListUnits();
80 if (response.isEmpty()) {
85 JsonArray jsonArray = JsonParser.parseString(response).getAsJsonArray();
86 if (jsonArray.isJsonArray()) {
88 for (JsonElement unit : jsonArray) {
89 TouchWandUnitData touchWandUnit;
90 touchWandUnit = TouchWandUnitFromJson.parseResponse(unit.getAsJsonObject());
92 if (!touchWandBridgeHandler.isAddSecondaryControllerUnits()) {
93 if (!Arrays.asList(CONNECTIVITY_OPTIONS).contains(touchWandUnit.getConnectivity())) {
97 String type = touchWandUnit.getType();
98 if (!Arrays.asList(SUPPORTED_TOUCHWAND_TYPES).contains(type)) {
99 logger.debug("Unit discovery skipping unsupported unit type : {} ", type);
103 case TYPE_WALLCONTROLLER:
104 addDeviceDiscoveryResult(touchWandUnit, THING_TYPE_WALLCONTROLLER);
107 addDeviceDiscoveryResult(touchWandUnit, THING_TYPE_SWITCH);
110 addDeviceDiscoveryResult(touchWandUnit, THING_TYPE_DIMMER);
113 addDeviceDiscoveryResult(touchWandUnit, THING_TYPE_SHUTTER);
115 case TYPE_ALARMSENSOR:
116 addDeviceDiscoveryResult(touchWandUnit, THING_TYPE_ALARMSENSOR);
121 notifyListeners(touchWandUnit);
123 } catch (JsonSyntaxException e) {
124 logger.warn("Could not parse unit {}", e.getMessage());
127 } catch (JsonSyntaxException msg) {
128 logger.warn("Could not parse list units response {}", msg.getMessage());
132 private void notifyListeners(TouchWandUnitData touchWandUnit) {
133 for (TouchWandUnitStatusUpdateListener listener : listeners) {
134 listener.onDataReceived(touchWandUnit);
139 protected void stopScan() {
140 removeOlderResults(getTimestampOfLastScan());
145 public void activate() {
146 super.activate(null);
147 removeOlderResults(new Date().getTime(), touchWandBridgeHandler.getThing().getUID());
151 public void deactivate() {
152 removeOlderResults(new Date().getTime(), touchWandBridgeHandler.getThing().getUID());
157 protected void startBackgroundDiscovery() {
158 ScheduledFuture<?> localScanningJob = scanningJob;
159 if (localScanningJob == null || localScanningJob.isCancelled()) {
160 scanningJob = scheduler.scheduleWithFixedDelay(this::startScan, LINK_DISCOVERY_SERVICE_INITIAL_DELAY_SEC,
161 SCAN_INTERVAL_SEC, TimeUnit.SECONDS);
166 protected void stopBackgroundDiscovery() {
167 ScheduledFuture<?> myScanningJob = scanningJob;
168 if (myScanningJob != null) {
169 myScanningJob.cancel(true);
174 public void registerListener(TouchWandUnitStatusUpdateListener listener) {
175 if (!listeners.contains(listener)) {
176 logger.debug("Adding TouchWandWebSocket listener {}", listener);
177 listeners.add(listener);
181 public void unregisterListener(TouchWandUnitStatusUpdateListener listener) {
182 logger.debug("Removing TouchWandWebSocket listener {}", listener);
183 listeners.remove(listener);
187 public int getScanTimeout() {
188 return SEARCH_TIME_SEC;
191 private void addDeviceDiscoveryResult(TouchWandUnitData unit, ThingTypeUID typeUID) {
192 ThingUID bridgeUID = touchWandBridgeHandler.getThing().getUID();
193 ThingUID thingUID = new ThingUID(typeUID, bridgeUID, unit.getId().toString());
194 Map<String, Object> properties = new HashMap<>();
195 properties.put(HANDLER_PROPERTIES_ID, unit.getId().toString());
196 properties.put(HANDLER_PROPERTIES_NAME, unit.getName());
198 thingDiscovered(DiscoveryResultBuilder.create(thingUID)
199 .withThingType(typeUID)
200 .withLabel(unit.getName())
201 .withBridge(bridgeUID)
202 .withProperties(properties)
203 .withRepresentationProperty(HANDLER_PROPERTIES_ID)
210 public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
211 if (handler instanceof TouchWandBridgeHandler) {
212 touchWandBridgeHandler = (TouchWandBridgeHandler) handler;
213 registerListener(touchWandBridgeHandler);
218 public @NonNull ThingHandler getThingHandler() {
219 return touchWandBridgeHandler;