2 * Copyright (c) 2010-2024 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.smaenergymeter.internal.packet;
15 import java.io.IOException;
17 import java.util.Map.Entry;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.Executors;
20 import java.util.concurrent.ScheduledExecutorService;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.openhab.binding.smaenergymeter.internal.SMAEnergyMeterBindingConstants;
26 import org.openhab.binding.smaenergymeter.internal.packet.PacketListener.ReceivingTask;
27 import org.osgi.service.component.annotations.Component;
28 import org.osgi.service.component.annotations.Deactivate;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Implementation of packet listener registry which manage multicast sockets.
35 * @author Ćukasz Dywicki - Initial contribution
40 public class DefaultPacketListenerRegistry implements PacketListenerRegistry {
42 private final Logger logger = LoggerFactory.getLogger(DefaultPacketListenerRegistry.class);
43 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1,
44 (runnable) -> new Thread(runnable,
45 "OH-binding-" + SMAEnergyMeterBindingConstants.BINDING_ID + "-listener"));
46 private final Map<String, PacketListener> listeners = new ConcurrentHashMap<>();
49 public PacketListener getListener(String group, int port) throws IOException {
50 String identifier = group + ":" + port;
51 PacketListener listener = listeners.get(identifier);
52 if (listener == null) {
53 listener = new PacketListener(this, group, port);
54 listeners.put(identifier, listener);
60 protected void shutdown() throws IOException {
61 for (Entry<String, PacketListener> entry : listeners.entrySet()) {
63 entry.getValue().close();
64 } catch (IOException e) {
65 logger.warn("Multicast socket {} failed to terminate", entry.getKey(), e);
68 scheduler.shutdownNow();
71 public ScheduledFuture<?> addTask(Runnable runnable, int intervalSec) {
72 return scheduler.scheduleWithFixedDelay(runnable, 0, intervalSec, TimeUnit.SECONDS);
75 public void execute(ReceivingTask receivingTask) {
76 scheduler.execute(receivingTask);
79 public void close(String group, int port) {
80 String listenerId = group + ":" + port;
81 PacketListener listener = listeners.remove(listenerId);
82 if (listener != null) {
85 } catch (IOException e) {
86 logger.warn("Multicast socket {} failed to terminate", listenerId, e);