]> git.basschouten.com Git - openhab-addons.git/blob
e79ac8e198652f1b681d132b275c13a9ebb3cf53
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.pilight.internal.discovery;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.IOException;
17 import java.net.DatagramPacket;
18 import java.net.DatagramSocket;
19 import java.net.Inet4Address;
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
22 import java.net.NetworkInterface;
23 import java.nio.charset.StandardCharsets;
24 import java.util.Collections;
25 import java.util.Enumeration;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Scanner;
30 import java.util.Set;
31 import java.util.concurrent.ScheduledFuture;
32 import java.util.concurrent.TimeUnit;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.openhab.binding.pilight.internal.PilightBindingConstants;
37 import org.openhab.core.config.discovery.AbstractDiscoveryService;
38 import org.openhab.core.config.discovery.DiscoveryResult;
39 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
40 import org.openhab.core.config.discovery.DiscoveryService;
41 import org.openhab.core.thing.ThingTypeUID;
42 import org.openhab.core.thing.ThingUID;
43 import org.osgi.service.component.annotations.Component;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * The {@link PilightBridgeDiscoveryService} is responsible for discovering new pilight daemons on the network
49  * by sending a ssdp multicast request via udp.
50  *
51  * @author Niklas Dörfler - Initial contribution
52  */
53 @NonNullByDefault
54 @Component(service = DiscoveryService.class, immediate = true, configurationPid = "discovery.pilight")
55 public class PilightBridgeDiscoveryService extends AbstractDiscoveryService {
56
57     private static final int AUTODISCOVERY_SEARCH_TIME_SEC = 5;
58     private static final int AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC = 60 * 10;
59
60     private static final String SSDP_DISCOVERY_REQUEST_MESSAGE = "M-SEARCH * HTTP/1.1\r\n"
61             + "Host:239.255.255.250:1900\r\n" + "ST:urn:schemas-upnp-org:service:pilight:1\r\n"
62             + "Man:\"ssdp:discover\"\r\n" + "MX:3\r\n\r\n";
63     public static final String SSDP_MULTICAST_ADDRESS = "239.255.255.250";
64     public static final int SSDP_PORT = 1900;
65     public static final int SSDP_WAIT_TIMEOUT = 2000; // in milliseconds
66
67     private final Logger logger = LoggerFactory.getLogger(PilightBridgeDiscoveryService.class);
68
69     private @Nullable ScheduledFuture<?> backgroundDiscoveryJob;
70
71     public PilightBridgeDiscoveryService() throws IllegalArgumentException {
72         super(getSupportedThingTypeUIDs(), AUTODISCOVERY_SEARCH_TIME_SEC, true);
73     }
74
75     public static Set<ThingTypeUID> getSupportedThingTypeUIDs() {
76         return Collections.singleton(PilightBindingConstants.THING_TYPE_BRIDGE);
77     }
78
79     @Override
80     protected void startScan() {
81         logger.debug("Pilight bridge discovery scan started");
82         removeOlderResults(getTimestampOfLastScan());
83         try {
84             List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
85             for (NetworkInterface nic : interfaces) {
86                 Enumeration<InetAddress> inetAddresses = nic.getInetAddresses();
87                 for (InetAddress inetAddress : Collections.list(inetAddresses)) {
88                     if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
89                         DatagramSocket ssdp = new DatagramSocket(
90                                 new InetSocketAddress(inetAddress.getHostAddress(), 0));
91                         byte[] buff = SSDP_DISCOVERY_REQUEST_MESSAGE.getBytes(StandardCharsets.UTF_8);
92                         DatagramPacket sendPack = new DatagramPacket(buff, buff.length);
93                         sendPack.setAddress(InetAddress.getByName(SSDP_MULTICAST_ADDRESS));
94                         sendPack.setPort(SSDP_PORT);
95                         ssdp.send(sendPack);
96                         ssdp.setSoTimeout(SSDP_WAIT_TIMEOUT);
97
98                         boolean loop = true;
99                         while (loop) {
100                             DatagramPacket recvPack = new DatagramPacket(new byte[1024], 1024);
101                             ssdp.receive(recvPack);
102                             byte[] recvData = recvPack.getData();
103
104                             final Scanner scanner = new Scanner(new ByteArrayInputStream(recvData),
105                                     StandardCharsets.UTF_8);
106                             loop = scanner.findAll("Location:([0-9.]+):(.*)").peek(matchResult -> {
107                                 final String server = matchResult.group(1);
108                                 final Integer port = Integer.parseInt(matchResult.group(2));
109                                 final String bridgeName = server.replace(".", "") + "" + port;
110
111                                 logger.debug("Found pilight daemon at {}:{}", server, port);
112
113                                 Map<String, Object> properties = new HashMap<>();
114                                 properties.put(PilightBindingConstants.PROPERTY_IP_ADDRESS, server);
115                                 properties.put(PilightBindingConstants.PROPERTY_PORT, port);
116                                 properties.put(PilightBindingConstants.PROPERTY_NAME, bridgeName);
117
118                                 ThingUID uid = new ThingUID(PilightBindingConstants.THING_TYPE_BRIDGE, bridgeName);
119
120                                 DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties)
121                                         .withRepresentationProperty(PilightBindingConstants.PROPERTY_NAME)
122                                         .withLabel("Pilight Bridge (" + server + ")").build();
123
124                                 thingDiscovered(result);
125                             }).count() == 0;
126                         }
127                     }
128                 }
129             }
130         } catch (IOException e) {
131             if (e.getMessage() != null && !"Receive timed out".equals(e.getMessage())) {
132                 logger.warn("Unable to enumerate the local network interfaces {}", e.getMessage());
133             }
134         }
135     }
136
137     @Override
138     protected synchronized void stopScan() {
139         super.stopScan();
140         removeOlderResults(getTimestampOfLastScan());
141     }
142
143     @Override
144     protected void startBackgroundDiscovery() {
145         logger.debug("Start Pilight device background discovery");
146         final @Nullable ScheduledFuture<?> backgroundDiscoveryJob = this.backgroundDiscoveryJob;
147         if (backgroundDiscoveryJob == null || backgroundDiscoveryJob.isCancelled()) {
148             this.backgroundDiscoveryJob = scheduler.scheduleWithFixedDelay(this::startScan, 5,
149                     AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC, TimeUnit.SECONDS);
150         }
151     }
152
153     @Override
154     protected void stopBackgroundDiscovery() {
155         logger.debug("Stop Pilight device background discovery");
156         final @Nullable ScheduledFuture<?> backgroundDiscoveryJob = this.backgroundDiscoveryJob;
157         if (backgroundDiscoveryJob != null) {
158             backgroundDiscoveryJob.cancel(true);
159             this.backgroundDiscoveryJob = null;
160         }
161     }
162 }