]> git.basschouten.com Git - openhab-addons.git/blob
8b96398b197ebbd43b1350565e6dee0f52438ded
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.danfossairunit.internal.discovery;
14
15 import static org.openhab.binding.danfossairunit.internal.DanfossAirUnitBindingConstants.*;
16
17 import java.io.IOException;
18 import java.net.DatagramPacket;
19 import java.net.DatagramSocket;
20 import java.net.InetAddress;
21 import java.net.InterfaceAddress;
22 import java.net.NetworkInterface;
23 import java.net.SocketTimeoutException;
24 import java.util.Arrays;
25 import java.util.Enumeration;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Set;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.openhab.core.config.discovery.AbstractDiscoveryService;
32 import org.openhab.core.config.discovery.DiscoveryResult;
33 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
34 import org.openhab.core.config.discovery.DiscoveryService;
35 import org.openhab.core.thing.ThingTypeUID;
36 import org.openhab.core.thing.ThingUID;
37 import org.osgi.service.component.annotations.Component;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * The Discovery service implementation to scan for available air units in the network via broadcast.
43  *
44  * @author Ralf Duckstein - Initial contribution
45  * @author Robert Bach - heavy refactorings
46  */
47 @Component(service = DiscoveryService.class)
48 @NonNullByDefault
49 public class DanfossAirUnitDiscoveryService extends AbstractDiscoveryService {
50
51     private static final int BROADCAST_PORT = 30045;
52     private static final byte[] DISCOVER_SEND = { 0x0c, 0x00, 0x30, 0x00, 0x11, 0x00, 0x12, 0x00, 0x13 };
53     private static final byte[] DISCOVER_RECEIVE = { 0x0d, 0x00, 0x07, 0x00, 0x02, 0x02, 0x00 };
54     private static final int TIMEOUT_IN_SECONDS = 15;
55
56     private final Logger logger = LoggerFactory.getLogger(DanfossAirUnitDiscoveryService.class);
57
58     public DanfossAirUnitDiscoveryService() {
59         super(SUPPORTED_THING_TYPES_UIDS, TIMEOUT_IN_SECONDS, true);
60     }
61
62     @Override
63     public Set<ThingTypeUID> getSupportedThingTypes() {
64         return SUPPORTED_THING_TYPES_UIDS;
65     }
66
67     @Override
68     protected void startBackgroundDiscovery() {
69         logger.debug("Start Danfoss Air CCM background discovery");
70         scheduler.execute(this::discover);
71     }
72
73     @Override
74     public void startScan() {
75         logger.debug("Start Danfoss Air CCM scan");
76         discover();
77     }
78
79     private synchronized void discover() {
80         logger.debug("Try to discover all Danfoss Air CCM devices");
81
82         try (DatagramSocket socket = new DatagramSocket()) {
83             Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
84             while (interfaces.hasMoreElements()) {
85                 NetworkInterface networkInterface = interfaces.nextElement();
86                 if (networkInterface.isLoopback() || !networkInterface.isUp()) {
87                     continue;
88                 }
89                 for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
90                     if (interfaceAddress.getBroadcast() == null) {
91                         continue;
92                     }
93                     logger.debug("Sending broadcast on interface {} to discover Danfoss Air CCM device...",
94                             interfaceAddress.getAddress());
95                     sendBroadcastToDiscoverThing(socket, interfaceAddress.getBroadcast());
96                 }
97             }
98         } catch (IOException e) {
99             logger.debug("No Danfoss Air CCM device found. Diagnostic: {}", e.getMessage());
100         }
101     }
102
103     private void sendBroadcastToDiscoverThing(DatagramSocket socket, InetAddress broadcastAddress) throws IOException {
104         socket.setBroadcast(true);
105         socket.setSoTimeout(500);
106         // send discover
107         byte[] sendBuffer = DISCOVER_SEND;
108         DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, broadcastAddress, BROADCAST_PORT);
109         socket.send(sendPacket);
110         logger.debug("Discover message sent");
111
112         // wait for responses
113         while (true) {
114             byte[] receiveBuffer = new byte[7];
115             DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
116             try {
117                 socket.receive(receivePacket);
118             } catch (SocketTimeoutException e) {
119                 break; // leave the endless loop
120             }
121
122             byte[] data = receivePacket.getData();
123             if (Arrays.equals(data, DISCOVER_RECEIVE)) {
124                 logger.debug("Discover received correct response");
125
126                 String host = receivePacket.getAddress().getHostName();
127                 Map<String, Object> properties = new HashMap<>();
128                 properties.put("host", host);
129
130                 logger.debug("Adding a new Danfoss Air Unit CCM '{}' to inbox", host);
131
132                 ThingUID uid = new ThingUID(THING_TYPE_AIRUNIT, String.valueOf(receivePacket.getAddress().hashCode()));
133
134                 DiscoveryResult result = DiscoveryResultBuilder.create(uid).withRepresentationProperty("host")
135                         .withProperties(properties).withLabel("Danfoss HRV").build();
136                 thingDiscovered(result);
137
138                 logger.debug("Thing discovered '{}'", result);
139             }
140         }
141     }
142 }