gnu.io.factory.SerialPortRegistry Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nrjavaserial Show documentation
Show all versions of nrjavaserial Show documentation
A fork of the RXTX library with a focus on ease of use and embeddability in other libraries.
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 extends SerialPort> o1, SerialPortCreator extends SerialPort> 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 extends SerialPort> 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;
}
}