NetSIDDevConnection.java

package builder.netsiddev;

import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import static server.netsiddev.NetworkSIDProtocol.MAX_INFO_NAME_LENGTH;

public class NetSIDDevConnection {
    /**
     * Timeout to establish a connection to a NetworkSIDDevice in ms.
     */
    private static final int SOCKET_CONNECT_TIMEOUT = 5000;
    /**
     * Expected string encoding read from the server.
     */
    private static final Charset ISO_8859_1 = StandardCharsets.ISO_8859_1;

    private boolean invalidated;
    private Socket connectedSocket;
    private final byte[] stringBytes = new byte[MAX_INFO_NAME_LENGTH];

    /**
     * Single instance connection.
     */
    private static NetSIDDevConnection connection;

    private NetSIDDevConnection() {
    }

    public static NetSIDDevConnection getInstance() {
        if (connection == null) {
            connection = new NetSIDDevConnection();
        }
        return connection;
    }

    /**
     * Connect to server, if not already connected or connection changed
     *
     * @param hostname server host name
     * @param port     server port address
     * @throws IOException socket I/O error
     */
    public void open(String hostname, int port) throws IOException {
        if (connection.isInvalidated()) {
            connection.close();
        }
        if (connection.isClosed()) {
            connection.connect(hostname, port);
        }
    }

    /**
     * Open connection to the server
     *
     * @param hostname server host name
     * @param port     server port address
     * @throws IOException socket I/O error
     */
    private void connect(String hostname, int port) throws IOException {
        connectedSocket = new Socket();
        System.out.printf("Try to connect to NetworkSIDDevice: %s (%d)\n", hostname, port);
        connectedSocket.connect(new InetSocketAddress(hostname, port), SOCKET_CONNECT_TIMEOUT);
        System.out.printf("Connected to NetworkSIDDevice: %s (%d)\n", hostname, port);
    }

    /**
     * Close the connection.
     */
    public void close() {
        if (!isClosed()) {
            try {
                connectedSocket.close();
                System.out.println("Disconnected from NetworkSIDDevice");
            } catch (IOException e) {
                System.err.println("NetworkSIDDevice socket cannot be closed!");
            }
        }
        invalidated = false;
    }

    /**
     * Connection has been closed?
     *
     * @return connection closed
     */
    private boolean isClosed() {
        return connectedSocket == null || connectedSocket.isClosed();
    }

    /**
     * Invalidate the connection.
     */
    public void invalidate() {
        invalidated = true;
    }

    /**
     * Connection has been invalidated?
     *
     * @return if the connection is invalid, it must be re-opened
     */
    public boolean isInvalidated() {
        return invalidated;
    }

    /**
     * Send a byte array to the server.
     *
     * @param cmd byte array to send
     * @throws IOException socket I/O error
     */
    public void send(byte[] cmd) throws IOException {
        connectedSocket.getOutputStream().write(cmd);
    }

    /**
     * Receive byte from server.
     *
     * @return received byte
     * @throws IOException socket I/O error
     */
    public int receive() throws IOException {
        return connectedSocket.getInputStream().read();
    }

    /**
     * Receive zero terminated byte array as string (ISO-8859-1).
     *
     * @return string received from server.
     * @throws IOException socket I/O error
     */
    public String receiveString() throws IOException {
        for (int length = 0; length <= MAX_INFO_NAME_LENGTH; length++) {
            int value = receive();
            if (value == -1) {
                throw new EOFException("Network SID device closed the connection during INFO");
            }
            if (value == 0) {
                return new String(stringBytes, 0, length, ISO_8859_1);
            }
            if (length == MAX_INFO_NAME_LENGTH) {
                throw new IOException("Network SID configuration name exceeds 255 bytes");
            }
            stringBytes[length] = (byte) value;
        }
        throw new IOException("Unterminated Network SID configuration name");
    }

    public boolean isDisconnected() {
        return connection.isInvalidated() || connection.isClosed();
    }

}