]> git.basschouten.com Git - openhab-addons.git/blob
1a1c5f1fb95480823696faa7fceef17e8291ad01
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.harmonyhub.internal.discovery;
14
15 import static org.openhab.binding.harmonyhub.internal.HarmonyHubBindingConstants.*;
16
17 import java.io.BufferedReader;
18 import java.io.IOException;
19 import java.io.InputStreamReader;
20 import java.io.Reader;
21 import java.net.DatagramPacket;
22 import java.net.DatagramSocket;
23 import java.net.InetAddress;
24 import java.net.InterfaceAddress;
25 import java.net.NetworkInterface;
26 import java.net.ServerSocket;
27 import java.net.Socket;
28 import java.util.ArrayList;
29 import java.util.Enumeration;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.concurrent.ScheduledFuture;
34 import java.util.concurrent.TimeUnit;
35 import java.util.stream.Collectors;
36 import java.util.stream.Stream;
37
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.openhab.binding.harmonyhub.internal.HarmonyHubBindingConstants;
41 import org.openhab.binding.harmonyhub.internal.handler.HarmonyHubHandler;
42 import org.openhab.core.config.discovery.AbstractDiscoveryService;
43 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
44 import org.openhab.core.config.discovery.DiscoveryService;
45 import org.openhab.core.thing.ThingTypeUID;
46 import org.openhab.core.thing.ThingUID;
47 import org.osgi.service.component.annotations.Component;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * The {@link HarmonyHubDiscoveryService} class discovers Harmony hubs and adds the results to the inbox.
53  *
54  * @author Dan Cunningham - Initial contribution
55  * @author Wouter Born - Add null annotations
56  */
57 @NonNullByDefault
58 @Component(service = DiscoveryService.class, configurationPid = "discovery.harmonyhub")
59 public class HarmonyHubDiscoveryService extends AbstractDiscoveryService {
60
61     private final Logger logger = LoggerFactory.getLogger(HarmonyHubDiscoveryService.class);
62
63     // notice the port appended to the end of the string
64     private static final String DISCOVERY_STRING = "_logitech-reverse-bonjour._tcp.local.\n%d";
65     private static final int DISCOVERY_PORT = 5224;
66     private static final int TIMEOUT = 15;
67     private static final long REFRESH = 600;
68
69     private boolean running;
70
71     private @Nullable HarmonyServer server;
72
73     private @Nullable ScheduledFuture<?> broadcastFuture;
74     private @Nullable ScheduledFuture<?> discoveryFuture;
75     private @Nullable ScheduledFuture<?> timeoutFuture;
76
77     public HarmonyHubDiscoveryService() {
78         super(HarmonyHubHandler.SUPPORTED_THING_TYPES_UIDS, TIMEOUT, true);
79     }
80
81     @Override
82     public Set<ThingTypeUID> getSupportedThingTypes() {
83         return HarmonyHubHandler.SUPPORTED_THING_TYPES_UIDS;
84     }
85
86     @Override
87     public void startScan() {
88         logger.debug("StartScan called");
89         startDiscovery();
90     }
91
92     @Override
93     protected void startBackgroundDiscovery() {
94         logger.debug("Start Harmony Hub background discovery");
95         ScheduledFuture<?> localDiscoveryFuture = discoveryFuture;
96         if (localDiscoveryFuture == null || localDiscoveryFuture.isCancelled()) {
97             logger.debug("Start Scan");
98             discoveryFuture = scheduler.scheduleWithFixedDelay(this::startScan, 0, REFRESH, TimeUnit.SECONDS);
99         }
100     }
101
102     @Override
103     protected void stopBackgroundDiscovery() {
104         logger.debug("Stop HarmonyHub background discovery");
105         ScheduledFuture<?> localDiscoveryFuture = discoveryFuture;
106         if (localDiscoveryFuture != null && !localDiscoveryFuture.isCancelled()) {
107             localDiscoveryFuture.cancel(true);
108             discoveryFuture = null;
109         }
110         stopDiscovery();
111     }
112
113     /**
114      * Starts discovery for Harmony Hubs
115      */
116     private synchronized void startDiscovery() {
117         if (running) {
118             return;
119         }
120
121         try {
122             final HarmonyServer localServer = new HarmonyServer();
123             localServer.start();
124             server = localServer;
125
126             broadcastFuture = scheduler.scheduleWithFixedDelay(() -> {
127                 sendDiscoveryMessage(String.format(DISCOVERY_STRING, localServer.getPort()));
128             }, 0, 2, TimeUnit.SECONDS);
129
130             timeoutFuture = scheduler.schedule(this::stopDiscovery, TIMEOUT, TimeUnit.SECONDS);
131
132             running = true;
133         } catch (IOException e) {
134             logger.error("Could not start Harmony discovery server ", e);
135         }
136     }
137
138     /**
139      * Stops discovery of Harmony Hubs
140      */
141     private synchronized void stopDiscovery() {
142         ScheduledFuture<?> localBroadcastFuture = broadcastFuture;
143         if (localBroadcastFuture != null) {
144             localBroadcastFuture.cancel(true);
145         }
146
147         ScheduledFuture<?> localTimeoutFuture = timeoutFuture;
148         if (localTimeoutFuture != null) {
149             localTimeoutFuture.cancel(true);
150         }
151
152         HarmonyServer localServer = server;
153         if (localServer != null) {
154             localServer.stop();
155         }
156
157         running = false;
158     }
159
160     /**
161      * Send broadcast message over all active interfaces
162      *
163      * @param discoverString
164      *            String to be used for the discovery
165      */
166     private void sendDiscoveryMessage(String discoverString) {
167         try (DatagramSocket bcSend = new DatagramSocket()) {
168             bcSend.setBroadcast(true);
169             byte[] sendData = discoverString.getBytes();
170
171             // Broadcast the message over all the network interfaces
172             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
173             while (interfaces.hasMoreElements()) {
174                 NetworkInterface networkInterface = interfaces.nextElement();
175                 if (networkInterface.isLoopback() || !networkInterface.isUp()) {
176                     continue;
177                 }
178                 for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
179                     InetAddress[] broadcast = new InetAddress[] { InetAddress.getByName("224.0.0.1"),
180                             InetAddress.getByName("255.255.255.255"), interfaceAddress.getBroadcast() };
181                     for (InetAddress bc : broadcast) {
182                         // Send the broadcast package!
183                         if (bc != null) {
184                             try {
185                                 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc,
186                                         DISCOVERY_PORT);
187                                 bcSend.send(sendPacket);
188                             } catch (IOException e) {
189                                 logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
190                             } catch (Exception e) {
191                                 logger.debug("{}", e.getMessage(), e);
192                             }
193                             logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(),
194                                     networkInterface.getDisplayName());
195                         }
196                     }
197                 }
198             }
199         } catch (IOException e) {
200             logger.debug("IO error during HarmonyHub discovery: {}", e.getMessage());
201         }
202     }
203
204     /**
205      * Server which accepts TCP connections from Harmony Hubs during the discovery process
206      *
207      * @author Dan Cunningham - Initial contribution
208      *
209      */
210     private class HarmonyServer {
211         private final ServerSocket serverSocket;
212         private final List<String> responses = new ArrayList<>();
213         private boolean running;
214
215         public HarmonyServer() throws IOException {
216             serverSocket = new ServerSocket(0);
217             logger.debug("Creating Harmony server on port {}", getPort());
218         }
219
220         public int getPort() {
221             return serverSocket.getLocalPort();
222         }
223
224         public void start() {
225             running = true;
226             Thread localThread = new Thread(this::run,
227                     "OH-binding-" + HarmonyHubBindingConstants.BINDING_ID + "discoveryServer");
228             localThread.setDaemon(true);
229             localThread.start();
230         }
231
232         public void stop() {
233             running = false;
234             try {
235                 serverSocket.close();
236             } catch (IOException e) {
237                 logger.error("Could not stop harmony discovery socket", e);
238             }
239         }
240
241         private void run() {
242             while (running) {
243                 try (Socket socket = serverSocket.accept();
244                         Reader isr = new InputStreamReader(socket.getInputStream());
245                         BufferedReader in = new BufferedReader(isr)) {
246                     String input;
247                     while ((input = in.readLine()) != null) {
248                         if (!running) {
249                             break;
250                         }
251                         logger.trace("READ {}", input);
252                         // response format is key1:value1;key2:value2;key3:value3;
253                         Map<String, String> properties = Stream.of(input.split(";")).map(line -> line.split(":", 2))
254                                 .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
255                         String friendlyName = properties.get("friendlyName");
256                         String hostName = properties.get("host_name");
257                         String ip = properties.get("ip");
258                         String uuid = properties.get("uuid");
259                         if (friendlyName != null && !friendlyName.isBlank() && hostName != null && !hostName.isBlank()
260                                 && ip != null && !ip.isBlank() && uuid != null && !uuid.isBlank()
261                                 && !responses.contains(hostName)) {
262                             responses.add(hostName);
263                             hubDiscovered(ip, friendlyName, hostName, uuid);
264                         }
265                     }
266                 } catch (IOException | IndexOutOfBoundsException e) {
267                     if (running) {
268                         logger.debug("Error connecting with found hub", e);
269                     }
270                 }
271             }
272         }
273     }
274
275     private void hubDiscovered(String ip, String friendlyName, String hostName, String uuid) {
276         String thingId = hostName.replaceAll("[^A-Za-z0-9\\-_]", "");
277         logger.trace("Adding HarmonyHub {} ({}) at host {}", friendlyName, thingId, ip);
278         ThingUID uid = new ThingUID(HARMONY_HUB_THING_TYPE, thingId);
279         // @formatter:off
280         thingDiscovered(DiscoveryResultBuilder.create(uid)
281                 .withLabel("HarmonyHub " + friendlyName)
282                 .withProperty(HUB_PROPERTY_HOST, ip)
283                 .withProperty(HUB_PROPERTY_NAME, friendlyName)
284                 .withProperty(HUB_PROPERTY_ID, uuid)
285                 .withRepresentationProperty(HUB_PROPERTY_ID)
286                 .build());
287         // @formatter:on
288     }
289 }