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.lgtvserial.internal.protocol.serial;
15 import java.io.IOException;
16 import java.util.HashMap;
19 import org.openhab.core.io.transport.serial.PortInUseException;
20 import org.openhab.core.io.transport.serial.SerialPortIdentifier;
21 import org.openhab.core.io.transport.serial.UnsupportedCommOperationException;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 * This class is used to create and reuse singleton objects associated to a given COM port.
28 * @author Richard Lavoie - Initial contribution
31 public class SerialCommunicatorFactory {
33 private final Logger logger = LoggerFactory.getLogger(SerialCommunicatorFactory.class);
35 private Map<SerialPortIdentifier, LGSerialCommunicator> instances = new HashMap<>();
37 public synchronized LGSerialCommunicator getInstance(SerialPortIdentifier serialPortIdentifier)
38 throws IOException, PortInUseException, UnsupportedCommOperationException {
39 LGSerialCommunicator comm = instances.get(serialPortIdentifier);
41 comm = createCommunicator(serialPortIdentifier);
43 instances.put(serialPortIdentifier, comm);
49 private LGSerialCommunicator createCommunicator(final SerialPortIdentifier serialPortIdentifier)
50 throws IOException, PortInUseException, UnsupportedCommOperationException {
51 return new LGSerialCommunicator(serialPortIdentifier, new RegistrationCallback() {
53 public void onUnregister() {
54 logger.debug("Unregistered last handler, closing");
55 deleteInstance(serialPortIdentifier);
60 protected synchronized void deleteInstance(SerialPortIdentifier serialPortIdentifier) {
61 instances.remove(serialPortIdentifier).close();