2 * Copyright (c) 2010-2022 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.network.internal.dhcp;
15 import java.net.SocketException;
17 import java.util.TreeMap;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * A singleton. IPRequestReceivedCallback objects can register and unregister.
26 * If the first one is registered and there is no singleton instance, an instance will be created and the
27 * receiver thread will be started. If the last IPRequestReceivedCallback is removed, the thread will be stopped
28 * after the receive socket is closed.
29 * IPRequestReceivedCallback will be called for the address that is registered and matches the
30 * DHO_DHCP_REQUESTED_ADDRESS address field.
32 * @author David Graeff - Initial contribution
35 public class DHCPListenService {
36 static @Nullable DHCPPacketListenerServer instance;
37 static Map<String, IPRequestReceivedCallback> registeredListeners = new TreeMap<>();
38 static Logger logger = LoggerFactory.getLogger(DHCPListenService.class);
40 @SuppressWarnings({ "null", "unused" })
41 public static synchronized DHCPPacketListenerServer register(String hostAddress,
42 IPRequestReceivedCallback dhcpListener) throws SocketException {
43 DHCPPacketListenerServer instance = DHCPListenService.instance;
44 if (instance == null) {
45 instance = new DHCPPacketListenerServer((String ipAddress) -> {
46 IPRequestReceivedCallback listener = registeredListeners.get(ipAddress);
47 if (listener != null) {
48 listener.dhcpRequestReceived(ipAddress);
50 logger.trace("DHCP request for unknown address: {}", ipAddress);
53 DHCPListenService.instance = instance;
56 synchronized (registeredListeners) {
57 registeredListeners.put(hostAddress, dhcpListener);
62 public static void unregister(String hostAddress) {
63 synchronized (registeredListeners) {
64 registeredListeners.remove(hostAddress);
65 if (!registeredListeners.isEmpty()) {
70 final DHCPPacketListenerServer instance = DHCPListenService.instance;
71 if (instance != null) {
74 DHCPListenService.instance = null;