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.jeelink.internal.connection;
15 import java.io.IOException;
16 import java.io.OutputStream;
17 import java.io.OutputStreamWriter;
18 import java.util.concurrent.atomic.AtomicBoolean;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * Abstract base class for a connection to a JeeLink.
25 * Manages ReadingListeners, finds out the sketch name and allows to propagate read lines.
27 * @author Volker Bier - Initial contribution
29 public abstract class AbstractJeeLinkConnection implements JeeLinkConnection {
30 private final Logger logger = LoggerFactory.getLogger(AbstractJeeLinkConnection.class);
32 protected final ConnectionListener connectionListener;
34 protected String port;
36 private AtomicBoolean initialized = new AtomicBoolean(false);
38 public AbstractJeeLinkConnection(String port, ConnectionListener listener) {
40 connectionListener = listener;
44 public String getPort() {
49 * returns the stream that can be used to write the init commands to the receiver.
51 protected abstract OutputStream getInitStream() throws IOException;
53 protected void notifyOpen() {
54 connectionListener.connectionOpened();
57 protected void notifyClosed() {
58 connectionListener.connectionClosed();
61 protected void notifyAbort(String cause) {
62 connectionListener.connectionAborted(cause);
63 initialized.set(false);
66 public void propagateLine(String line) throws IOException {
67 logger.trace("Read line from port {}: {}", port, line);
69 connectionListener.handleInput(line);
73 public void sendCommands(String commands) {
75 if (commands != null && !commands.trim().isEmpty()) {
76 // do not create in try-with-resources as this will
77 // close the undelying socket for TCP connections
78 OutputStream initStream = getInitStream();
79 if (initStream == null) {
80 throw new IOException(
81 "Connection on port " + port + " did not provide an init stream for writing init commands");
84 // do not close the writer as this closes the underlying stream, and
85 // in case of tcp connections, the underlying socket
86 OutputStreamWriter w = new OutputStreamWriter(initStream);
87 for (String cmd : commands.split(";")) {
88 logger.debug("Writing to device on port {}: {} ", port, cmd);
94 } catch (IOException ex) {
95 logger.debug("Error writing to output stream!", ex);
97 notifyAbort("propagate: " + ex.getMessage());