]> git.basschouten.com Git - openhab-addons.git/blob
fcb9326067529fa432191a2053fe3a32b0726ba8
[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.revogi.internal.udp;
14
15 import java.io.IOException;
16 import java.net.DatagramPacket;
17 import java.net.DatagramSocket;
18 import java.net.SocketException;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22
23 /**
24  * The {@link DatagramSocketWrapper} wraps Java's DatagramSocket for better testing
25  * UdpSenderService
26  *
27  * @author Andi Bräu - Initial contribution
28  */
29 @NonNullByDefault
30 public class DatagramSocketWrapper {
31
32     @Nullable
33     private DatagramSocket datagramSocket;
34
35     public void initSocket() throws SocketException {
36         closeSocket();
37         DatagramSocket localDatagramSocket = new DatagramSocket();
38         localDatagramSocket.setBroadcast(true);
39         localDatagramSocket.setSoTimeout(3);
40         datagramSocket = localDatagramSocket;
41     }
42
43     public void closeSocket() {
44         DatagramSocket localDatagramSocket = this.datagramSocket;
45         if (localDatagramSocket != null && !localDatagramSocket.isClosed()) {
46             localDatagramSocket.close();
47         }
48     }
49
50     public void sendPacket(DatagramPacket datagramPacket) throws IOException {
51         DatagramSocket localDatagramSocket = this.datagramSocket;
52         if (localDatagramSocket != null && !localDatagramSocket.isClosed()) {
53             localDatagramSocket.send(datagramPacket);
54         } else {
55             throw new SocketException("Datagram Socket closed or not initialized");
56         }
57     }
58
59     public void receiveAnswer(DatagramPacket datagramPacket) throws IOException {
60         DatagramSocket localDatagramSocket = this.datagramSocket;
61         if (localDatagramSocket != null && !localDatagramSocket.isClosed()) {
62             localDatagramSocket.receive(datagramPacket);
63         } else {
64             throw new SocketException("Datagram Socket closed or not initialized");
65         }
66     }
67 }