]> git.basschouten.com Git - openhab-addons.git/blob
b97db1390e5bb99c8df12ce03ab316618e3ca1c2
[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.mihome.internal.socket;
14
15 import java.io.IOException;
16 import java.net.InetAddress;
17 import java.net.MulticastSocket;
18 import java.net.NetworkInterface;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26  * Takes care of the multicast communication with the bridge.
27  *
28  * @author Dieter Schmidt - Initial contribution
29  *
30  */
31 @NonNullByDefault
32 public class XiaomiBridgeSocket extends XiaomiSocket {
33
34     private final Logger logger = LoggerFactory.getLogger(XiaomiBridgeSocket.class);
35     private @Nullable final String netIf;
36
37     public XiaomiBridgeSocket(int port, String netIf, String owner) {
38         super(port, owner);
39         this.netIf = netIf;
40     }
41
42     /**
43      * Sets up the {@link XiaomiBridgeSocket}.
44      *
45      * Connects the socket to the specific multicast address and port.
46      */
47     @Override
48     protected synchronized void setupSocket() {
49         MulticastSocket socket = (MulticastSocket) getSocket();
50         if (socket != null) {
51             logger.debug("Socket already setup");
52             return;
53         }
54
55         try {
56             logger.debug("Setup socket");
57             socket = new MulticastSocket(getPort());
58
59             if (netIf != null) {
60                 socket.setNetworkInterface(NetworkInterface.getByName(netIf));
61             }
62
63             setSocket(socket); // must bind receive side
64             socket.joinGroup(InetAddress.getByName(MCAST_ADDR));
65             logger.debug("Initialized socket to {}:{} on {}:{} bound to {} network interface",
66                     socket.getRemoteSocketAddress(), socket.getPort(), socket.getLocalAddress(), socket.getLocalPort(),
67                     socket.getNetworkInterface());
68         } catch (IOException e) {
69             logger.error("Setup socket error", e);
70         }
71     }
72 }