2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.revogi.internal.udp;
15 import java.io.IOException;
16 import java.net.DatagramPacket;
17 import java.net.DatagramSocket;
18 import java.net.SocketException;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
24 * The {@link DatagramSocketWrapper} wraps Java's DatagramSocket for better testing
27 * @author Andi Bräu - Initial contribution
30 public class DatagramSocketWrapper {
33 private DatagramSocket datagramSocket;
35 public void initSocket() throws SocketException {
37 DatagramSocket localDatagramSocket = new DatagramSocket();
38 localDatagramSocket.setBroadcast(true);
39 localDatagramSocket.setSoTimeout(3);
40 datagramSocket = localDatagramSocket;
43 public void closeSocket() {
44 DatagramSocket localDatagramSocket = this.datagramSocket;
45 if (localDatagramSocket != null && !localDatagramSocket.isClosed()) {
46 localDatagramSocket.close();
50 public void sendPacket(DatagramPacket datagramPacket) throws IOException {
51 DatagramSocket localDatagramSocket = this.datagramSocket;
52 if (localDatagramSocket != null && !localDatagramSocket.isClosed()) {
53 localDatagramSocket.send(datagramPacket);
55 throw new SocketException("Datagram Socket closed or not initialized");
59 public void receiveAnswer(DatagramPacket datagramPacket) throws IOException {
60 DatagramSocket localDatagramSocket = this.datagramSocket;
61 if (localDatagramSocket != null && !localDatagramSocket.isClosed()) {
62 localDatagramSocket.receive(datagramPacket);
64 throw new SocketException("Datagram Socket closed or not initialized");