]> git.basschouten.com Git - openhab-addons.git/blob
6483d42c6f24622059bb5e1abcfd6ca613aa0c01
[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.feican.internal;
14
15 import java.io.Closeable;
16 import java.io.IOException;
17 import java.net.DatagramPacket;
18 import java.net.DatagramSocket;
19 import java.net.InetAddress;
20 import java.net.SocketException;
21 import java.net.UnknownHostException;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24
25 /**
26  * Manages the connection to a Feican bulb.
27  *
28  * @author Hilbrand Bouwkamp - Initial contribution
29  */
30 @NonNullByDefault
31 public class Connection implements Closeable {
32
33     /**
34      * UDP port to send command.
35      */
36     public static final int FEICAN_SEND_PORT = 5000;
37     /**
38      * UDP port devices send discover replies back.
39      */
40     public static final int FEICAN_RECEIVE_PORT = 6000;
41
42     private final InetAddress iNetAddress;
43     private final DatagramSocket socket;
44
45     /**
46      * Initializes a connection to the given IP address.
47      *
48      * @param ipAddress IP address of the connection
49      * @throws UnknownHostException if ipAddress could not be resolved.
50      * @throws SocketException if no Datagram socket connection could be made.
51      */
52     public Connection(String ipAddress) throws SocketException, UnknownHostException {
53         iNetAddress = InetAddress.getByName(ipAddress);
54         socket = new DatagramSocket();
55     }
56
57     /**
58      * Sends the 9 bytes command to the Feican device.
59      *
60      * @param command the 9 bytes command
61      * @throws IOException Connection to the bulb failed
62      */
63     public void sendCommand(byte[] command) throws IOException {
64         DatagramPacket sendPkt = new DatagramPacket(command, command.length, iNetAddress, FEICAN_SEND_PORT);
65         socket.send(sendPkt);
66     }
67
68     @Override
69     public void close() {
70         socket.close();
71     }
72 }