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

gnu.io.factory.SerialPortRegistry Maven / Gradle / Ivy

Go to download

A fork of the RXTX library with a focus on ease of use and embeddability in other libraries.

There is a newer version: 5.2.1
Show newest version
package gnu.io.factory;

import java.util.Collection;
import java.util.Comparator;
import java.util.TreeSet;

import gnu.io.SerialPort;

public class SerialPortRegistry {

	private Collection> portCreators;
	
	public SerialPortRegistry() {
		// register the LOCAL PortCreator as last argument, so that is always taken into account when no other creator is applicable.
		this.portCreators = new TreeSet>(new Comparator>() {

			@Override
			public int compare(SerialPortCreator o1, SerialPortCreator o2) {
				if(o1.getProtocol().equals(SerialPortCreator.LOCAL)) {
					return 1;
				}
				if(o2.getProtocol().equals(SerialPortCreator.LOCAL)) {
					return -1;
				}
				return o1.getProtocol().compareTo(o2.getProtocol());
			}
		});
		
		registerDefaultSerialPortCreators();
	}
	
	/**
	 * Registers the {@link RxTxPortCreator} and the {@link RFC2217PortCreator}.
	 */
	protected void registerDefaultSerialPortCreators() {
		registerSerialPortCreator(new RxTxPortCreator());
		registerSerialPortCreator(new RFC2217PortCreator());
	}
	
	/**
	 * Registers a {@link SerialPortCreator}.
	 * @param creator
	 */
	public void registerSerialPortCreator(SerialPortCreator creator) {
		this.portCreators.add(creator);
	}
	
	/**
	 * Gets the best applicable {@link SerialPortCreator} for the given portName
	 * @param portName The port's name.
	 * @return A found {@link SerialPortCreator} or null if none could be found.
	 */
	@SuppressWarnings("unchecked")
	public  SerialPortCreator getPortCreatorForPortName(String portName, Class expectedClass) {
		for(@SuppressWarnings("rawtypes") SerialPortCreator creator : this.portCreators) {
			try {
				if(creator.isApplicable(portName, expectedClass))
					return (SerialPortCreator) creator;
			} catch(Exception e) {
				System.err.println("Error for SerialPortCreator#isApplicable: " + creator.getClass()+"; " + creator.getProtocol() +" -> " + e.getMessage());
			}
		}
		return null;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy