2 * Copyright (c) 2010-2023 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.pilight.internal.discovery;
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;
29 import java.util.Scanner;
31 import java.util.concurrent.ScheduledFuture;
32 import java.util.concurrent.TimeUnit;
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;
48 * The {@link PilightBridgeDiscoveryService} is responsible for discovering new pilight daemons on the network
49 * by sending a ssdp multicast request via udp.
51 * @author Niklas Dörfler - Initial contribution
54 @Component(service = DiscoveryService.class, immediate = true, configurationPid = "discovery.pilight")
55 public class PilightBridgeDiscoveryService extends AbstractDiscoveryService {
57 private static final int AUTODISCOVERY_SEARCH_TIME_SEC = 5;
58 private static final int AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC = 60 * 10;
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
67 private final Logger logger = LoggerFactory.getLogger(PilightBridgeDiscoveryService.class);
69 private @Nullable ScheduledFuture<?> backgroundDiscoveryJob;
71 public PilightBridgeDiscoveryService() throws IllegalArgumentException {
72 super(getSupportedThingTypeUIDs(), AUTODISCOVERY_SEARCH_TIME_SEC, true);
75 public static Set<ThingTypeUID> getSupportedThingTypeUIDs() {
76 return Collections.singleton(PilightBindingConstants.THING_TYPE_BRIDGE);
80 protected void startScan() {
81 logger.debug("Pilight bridge discovery scan started");
82 removeOlderResults(getTimestampOfLastScan());
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);
96 ssdp.setSoTimeout(SSDP_WAIT_TIMEOUT);
100 DatagramPacket recvPack = new DatagramPacket(new byte[1024], 1024);
101 ssdp.receive(recvPack);
102 byte[] recvData = recvPack.getData();
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;
111 logger.debug("Found pilight daemon at {}:{}", server, port);
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);
118 ThingUID uid = new ThingUID(PilightBindingConstants.THING_TYPE_BRIDGE, bridgeName);
120 DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties)
121 .withRepresentationProperty(PilightBindingConstants.PROPERTY_NAME)
122 .withLabel("Pilight Bridge (" + server + ")").build();
124 thingDiscovered(result);
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());
138 protected synchronized void stopScan() {
140 removeOlderResults(getTimestampOfLastScan());
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);
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;