All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.refcodes.serial.LoopbackPort Maven / Gradle / Ivy

Go to download

Artifact providing generic (byte) serialization functionality including a TTY-/COM-Port implementation of the serial framework as well as a (local) loopback port.

The newest version!
// /////////////////////////////////////////////////////////////////////////////
// REFCODES.ORG
// /////////////////////////////////////////////////////////////////////////////
// This code is copyright (c) by Siegfried Steiner, Munich, Germany, distributed
// on an "AS IS" BASIS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, and licen-
// sed under the following (see "http://en.wikipedia.org/wiki/Multi-licensing")
// licenses:
// -----------------------------------------------------------------------------
// GNU General Public License, v3.0 ("http://www.gnu.org/licenses/gpl-3.0.html")
// -----------------------------------------------------------------------------
// Apache License, v2.0 ("http://www.apache.org/licenses/TEXT-2.0")
// -----------------------------------------------------------------------------
// Please contact the copyright holding author(s) of the software artifacts in
// question for licensing issues not being covered by the above listed licenses,
// also regarding commercial licensing models or regarding the compatibility
// with other open source licenses.
// /////////////////////////////////////////////////////////////////////////////

package org.refcodes.serial;

import java.io.IOException;
import java.util.concurrent.ExecutorService;

import org.refcodes.component.ConnectionStatus;
import org.refcodes.data.DaemonLoopSleepTime;

/**
 * The {@link LoopbackPort} is an in-memory implementation of a {@link Port}
 * which loops its output directly back to its input. This is suitable for
 * straight forward cases where data is first transmitted to be received in the
 * next step by the same {@link Port}. For cases using a some kind of frequent
 * handshake between a transmitter and a receiver on the same line please use
 * the {@link CrossoverLoopbackPort} as counterpart of a {@link LoopbackPort}
 * for simulating a bidirectional in-memory communication between these two
 * ports.
 */
public class LoopbackPort extends AbstractPort {

	// /////////////////////////////////////////////////////////////////////////
	// VARIABLES:
	// /////////////////////////////////////////////////////////////////////////

	protected ByteArraySequence _transmitSequence = new ByteArraySequence();
	protected LoopbackPort _crossoverPort = this;

	// /////////////////////////////////////////////////////////////////////////
	// CONSTRUCTORS:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * Constructs a {@link LoopbackPort}.
	 * 
	 * @param aAlias The alias to use for this port.
	 */
	public LoopbackPort( String aAlias ) {
		this( aAlias, null );
	}

	/**
	 * Constructs a {@link LoopbackPort}.
	 * 
	 * @param aAlias The alias to use for this port.
	 * @param aExecutorService The {@link ExecutorService} to be used when
	 *        invoking asynchronously working methods.
	 */
	public LoopbackPort( String aAlias, ExecutorService aExecutorService ) {
		super( aAlias, new PortMetrics() {}, aExecutorService );
	}

	// /////////////////////////////////////////////////////////////////////////
	// METHODS:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * {@inheritDoc}
	 */
	//	@Override
	//	public InputStream getInputStream() {
	//		return new BlockingInputStream( super.getInputStream() );
	//	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void transmitSequence( Sequence aSequence ) throws IOException {
		if ( !isOpened() ) {
			throw new IOException( "Cannot transmit data as the connection is in status <" + getConnectionStatus() + ">!" );
		}
		synchronized ( _transmitSequence ) {
			_transmitSequence.append( aSequence );
		}
		synchronized ( _crossoverPort ) {
			_crossoverPort.notifyAll();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void receiveBytes( byte[] aBuffer, int aOffset, int aLength ) throws IOException {
		if ( !isOpened() ) {
			throw new IOException( "Cannot receive data as the connection is in status <" + getConnectionStatus() + ">!" );
		}
		while ( available() < aLength && getConnectionStatus() == ConnectionStatus.OPENED ) {
			synchronized ( this ) {
				try {
					wait( DaemonLoopSleepTime.MIN.getTimeMillis() );
				}
				catch ( InterruptedException ignore ) {}
			}
		}
		if ( available() < aLength ) {
			if ( getConnectionStatus() == ConnectionStatus.CLOSED ) {
				throw new IOException( "Connection is closed and only <" + available() + "> bytes out of requested <" + aLength + "> bytes are available!" );
			}
			throw new IOException( "Only <" + available() + "> bytes out of requested <" + aLength + "> bytes are available!" );
		}
		synchronized ( _crossoverPort._transmitSequence ) {
			_crossoverPort._transmitSequence.toBytes( 0, aLength, aBuffer, aOffset );
			final byte[] theBytes = _crossoverPort._transmitSequence.toBytes( aLength, _crossoverPort._transmitSequence.getLength() - aLength );
			_crossoverPort._transmitSequence.replace( theBytes );
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public PortMetrics getPortMetrics() {
		return _portMetrics;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getAlias() {
		return _alias;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int available() {
		synchronized ( _crossoverPort._transmitSequence ) {
			return _crossoverPort._transmitSequence.getLength();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void open() throws IOException {
		super.open();
		synchronized ( this ) {
			notifyAll();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void close() throws IOException {
		super.close();
		_transmitSequence.empty();
		try {
			skipAvailable();
		}
		catch ( IOException ignore ) {}
		synchronized ( this ) {
			notifyAll();
		}
		// _executorService.shutdownNow();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public LoopbackPort withOpen() throws IOException {
		open();
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public LoopbackPort withOpen( PortMetrics aPortMetrics ) throws IOException {
		open( aPortMetrics );
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public LoopbackPort withOpenUnchecked() {
		openUnchecked();
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public LoopbackPort withOpenUnchecked( PortMetrics aPortMetrics ) {
		openUnchecked( aPortMetrics );
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toString() {
		return getClass().getSimpleName() + " [alias=" + _alias + ", transmitSequence=" + _transmitSequence + ", receiveSequence=" + _crossoverPort._transmitSequence + ", portMetrics=" + _portMetrics + "]";
	}

	// /////////////////////////////////////////////////////////////////////////
	// HOOKS:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * Hook to set a crossover loopback port in order to attach a
	 * {@link LoopbackPort} to the other end of the wire and transform a
	 * loopback device into two crossover loopback devices.
	 * 
	 * @param aPort The {@link LoopbackPort} to act as the crossover loopback
	 *        device at the other end of the wire.
	 */
	protected void setCrossoverPort( LoopbackPort aPort ) {
		_crossoverPort = aPort;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy