]> git.basschouten.com Git - openhab-addons.git/blob
d7bef611f0ce5d4517882802ec57fc39ee4511d1
[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.lgtvserial.internal.protocol.serial;
14
15 import java.io.IOException;
16 import java.util.HashMap;
17 import java.util.Map;
18
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;
24
25 /**
26  * This class is used to create and reuse singleton objects associated to a given COM port.
27  *
28  * @author Richard Lavoie - Initial contribution
29  *
30  */
31 public class SerialCommunicatorFactory {
32
33     private final Logger logger = LoggerFactory.getLogger(SerialCommunicatorFactory.class);
34
35     private Map<SerialPortIdentifier, LGSerialCommunicator> instances = new HashMap<>();
36
37     public synchronized LGSerialCommunicator getInstance(SerialPortIdentifier serialPortIdentifier)
38             throws IOException, PortInUseException, UnsupportedCommOperationException {
39         LGSerialCommunicator comm = instances.get(serialPortIdentifier);
40         if (comm == null) {
41             comm = createCommunicator(serialPortIdentifier);
42             if (comm != null) {
43                 instances.put(serialPortIdentifier, comm);
44             }
45         }
46         return comm;
47     }
48
49     private LGSerialCommunicator createCommunicator(final SerialPortIdentifier serialPortIdentifier)
50             throws IOException, PortInUseException, UnsupportedCommOperationException {
51         return new LGSerialCommunicator(serialPortIdentifier, new RegistrationCallback() {
52             @Override
53             public void onUnregister() {
54                 logger.debug("Unregistered last handler, closing");
55                 deleteInstance(serialPortIdentifier);
56             }
57         });
58     }
59
60     protected synchronized void deleteInstance(SerialPortIdentifier serialPortIdentifier) {
61         instances.remove(serialPortIdentifier).close();
62     }
63 }