]> git.basschouten.com Git - openhab-addons.git/blob
c73e6f6b496461c9aeffcacb05773341d94ac39c
[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.DatagramSocket;
17 import java.net.InetAddress;
18 import java.net.UnknownHostException;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 /**
25  * Takes care of the discovery communication with the MiHome gateway
26  *
27  * @author Dieter Schmidt - Initial contribution
28  *
29  */
30 @NonNullByDefault
31 public class XiaomiDiscoverySocket extends XiaomiSocket {
32
33     private static final int MCAST_PORT = 4321;
34
35     private final Logger logger = LoggerFactory.getLogger(XiaomiDiscoverySocket.class);
36
37     public XiaomiDiscoverySocket(String owner) {
38         super(owner);
39     }
40
41     /**
42      * Sets up the {@link XiaomiDiscoverySocket}.
43      *
44      * Connects the socket to the specific multicast address and port.
45      */
46     @Override
47     protected void setupSocket() {
48         synchronized (XiaomiDiscoverySocket.class) {
49             try {
50                 logger.debug("Setup discovery socket");
51                 DatagramSocket socket = new DatagramSocket(0);
52                 setSocket(socket);
53                 logger.debug("Initialized socket to {}:{} on {}:{}", socket.getInetAddress(), socket.getPort(),
54                         socket.getLocalAddress(), socket.getLocalPort());
55             } catch (IOException e) {
56                 logger.error("Setup socket error", e);
57             }
58         }
59     }
60
61     /**
62      * Sends a message through the {@link XiaomiDiscoverySocket}
63      * to the MiHome multicast address 224.0.0.50 and port 4321
64      *
65      * @param message - Message to be sent
66      */
67     public void sendMessage(String message) {
68         try {
69             sendMessage(message, InetAddress.getByName(MCAST_ADDR), MCAST_PORT);
70         } catch (UnknownHostException e) {
71             logger.error("Sending error", e);
72         }
73     }
74 }