]> git.basschouten.com Git - openhab-addons.git/blob
10d88657ed4e47fe13271625b15e4ae4e6bdcfb7
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.asuswrt.internal;
14
15 import static org.openhab.binding.asuswrt.internal.constants.AsuswrtBindingConstants.*;
16 import static org.openhab.binding.asuswrt.internal.constants.AsuswrtBindingSettings.*;
17 import static org.openhab.binding.asuswrt.internal.helpers.AsuswrtUtils.*;
18
19 import java.util.Date;
20 import java.util.HashMap;
21 import java.util.Map;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.binding.asuswrt.internal.structures.AsuswrtClientInfo;
26 import org.openhab.binding.asuswrt.internal.structures.AsuswrtClientList;
27 import org.openhab.binding.asuswrt.internal.structures.AsuswrtInterfaceList;
28 import org.openhab.binding.asuswrt.internal.structures.AsuswrtIpInfo;
29 import org.openhab.binding.asuswrt.internal.things.AsuswrtRouter;
30 import org.openhab.core.config.discovery.AbstractDiscoveryService;
31 import org.openhab.core.config.discovery.DiscoveryResult;
32 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
33 import org.openhab.core.thing.Thing;
34 import org.openhab.core.thing.ThingUID;
35 import org.openhab.core.thing.binding.ThingHandler;
36 import org.openhab.core.thing.binding.ThingHandlerService;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * The {@link AsuswrtDiscoveryService} is responsible for discovering clients.
42  *
43  * @author Christian Wild - Initial contribution
44  */
45 @NonNullByDefault
46 public class AsuswrtDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
47     private final Logger logger = LoggerFactory.getLogger(AsuswrtDiscoveryService.class);
48     private String uid = "";
49     protected @NonNullByDefault({}) AsuswrtRouter router;
50
51     public AsuswrtDiscoveryService() {
52         super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_S, false);
53     }
54
55     @Override
56     public void activate() {
57     }
58
59     @Override
60     public void deactivate() {
61         super.deactivate();
62         removeAllResults();
63     }
64
65     @Override
66     public void setThingHandler(@Nullable ThingHandler handler) {
67         if (handler instanceof AsuswrtRouter router) {
68             router.setDiscoveryService(this);
69             this.router = router;
70             this.uid = router.getUID().getAsString();
71         }
72     }
73
74     @Override
75     public @Nullable ThingHandler getThingHandler() {
76         return this.router;
77     }
78
79     /*
80      * Scan handling
81      */
82
83     /**
84      * Starts a manual scan.
85      */
86     @Override
87     public void startScan() {
88         logger.trace("{} starting scan", uid);
89         if (router != null) {
90             /* query Data */
91             router.queryDeviceData(false);
92             /* discover interfaces */
93             AsuswrtInterfaceList ifList = router.getInterfaces();
94             handleInterfaceScan(ifList);
95             /* discover clients */
96             AsuswrtClientList clientList = router.getClients();
97             handleClientScan(clientList);
98         }
99     }
100
101     @Override
102     public void stopScan() {
103         super.stopScan();
104         removeOlderResults(getTimestampOfLastScan());
105     }
106
107     /**
108      * Removes all scan results.
109      */
110     private void removeAllResults() {
111         removeOlderResults(new Date().getTime());
112     }
113
114     /**
115      * Creates {@link DiscoveryResult}s from the provided {@link AsuswrtInterfaceList}.
116      */
117     private void handleInterfaceScan(AsuswrtInterfaceList ifList) {
118         try {
119             for (AsuswrtIpInfo ifInfo : ifList) {
120                 DiscoveryResult discoveryResult = createInterfaceResult(ifInfo);
121                 thingDiscovered(discoveryResult);
122             }
123         } catch (Exception e) {
124             logger.debug("Error while handling interface scan reults", e);
125         }
126     }
127
128     /**
129      * Creates {@link DiscoveryResult}s from the provided {@link AsuswrtClientList}.
130      */
131     public void handleClientScan(AsuswrtClientList clientList) {
132         try {
133             for (AsuswrtClientInfo client : clientList) {
134                 DiscoveryResult discoveryResult = createClientResult(client);
135                 thingDiscovered(discoveryResult);
136             }
137         } catch (Exception e) {
138             logger.debug("Error while handling client scan results", e);
139         }
140     }
141
142     /*
143      * Discovery result creation
144      */
145
146     /**
147      * Creates a {@link DiscoveryResult} from the provided {@link AsuswrtIpInfo}.
148      */
149     private DiscoveryResult createInterfaceResult(AsuswrtIpInfo interfaceInfo) {
150         String ifName = interfaceInfo.getName();
151         String macAddress = interfaceInfo.getMAC();
152         String label = "AwrtInterface_" + ifName;
153
154         Map<String, Object> properties = new HashMap<>();
155         properties.put(NETWORK_REPRESENTATION_PROPERTY, ifName);
156         properties.put(Thing.PROPERTY_MAC_ADDRESS, macAddress);
157
158         logger.debug("{} thing discovered: '{}", uid, label);
159         if (this.router != null) {
160             ThingUID bridgeUID = router.getUID();
161             ThingUID thingUID = new ThingUID(THING_TYPE_INTERFACE, bridgeUID, ifName);
162             return DiscoveryResultBuilder.create(thingUID).withProperties(properties)
163                     .withRepresentationProperty(NETWORK_REPRESENTATION_PROPERTY).withBridge(bridgeUID).withLabel(label)
164                     .build();
165         } else {
166             ThingUID thingUID = new ThingUID(BINDING_ID, ifName);
167             return DiscoveryResultBuilder.create(thingUID).withProperties(properties)
168                     .withRepresentationProperty(NETWORK_REPRESENTATION_PROPERTY).withLabel(label).build();
169         }
170     }
171
172     /**
173      * Creates a {@link DiscoveryResult} from the provided {@link AsuswrtClientInfo}.
174      */
175     private DiscoveryResult createClientResult(AsuswrtClientInfo clientInfo) {
176         String macAddress = clientInfo.getMac();
177         String unformatedMac = unformatMac(macAddress);
178         String clientName;
179         String nickName;
180         String label = "AwrtClient_";
181
182         // Create label and thing names
183         clientName = stringOrDefault(clientInfo.getName(), "client_" + unformatedMac);
184         nickName = stringOrDefault(clientInfo.getNickName(), clientName);
185         if (nickName.equals(clientName)) {
186             label += nickName;
187         } else {
188             label += nickName + " (" + clientName + ")";
189         }
190
191         // Create properties
192         Map<String, Object> properties = new HashMap<>();
193         properties.put(Thing.PROPERTY_MAC_ADDRESS, macAddress);
194         properties.put(Thing.PROPERTY_VENDOR, clientInfo.getVendor());
195         properties.put(PROPERTY_CLIENT_NAME, clientName);
196         properties.put(CHANNEL_CLIENT_NICKNAME, nickName);
197
198         logger.debug("{} thing discovered: '{}", uid, label);
199         if (this.router != null) {
200             ThingUID bridgeUID = router.getUID();
201             ThingUID thingUID = new ThingUID(THING_TYPE_CLIENT, bridgeUID, unformatedMac);
202             return DiscoveryResultBuilder.create(thingUID).withProperties(properties)
203                     .withRepresentationProperty(CLIENT_REPRESENTATION_PROPERTY).withTTL(DISCOVERY_AUTOREMOVE_S)
204                     .withBridge(bridgeUID).withLabel(label).build();
205         } else {
206             ThingUID thingUID = new ThingUID(BINDING_ID, unformatedMac);
207             return DiscoveryResultBuilder.create(thingUID).withProperties(properties)
208                     .withRepresentationProperty(CLIENT_REPRESENTATION_PROPERTY).withTTL(DISCOVERY_AUTOREMOVE_S)
209                     .withLabel(label).build();
210         }
211     }
212 }