From e2c32b8666cfcf5a368f002207702c3e5eef2bf4 Mon Sep 17 00:00:00 2001 From: Samuel Coleman Date: Sun, 24 Jan 2021 16:15:44 +0000 Subject: [PATCH 1/2] Apply automatic formatting. --- build.gradle | 1 + src/main/java/gnu/io/CommPort.java | 46 +- src/main/java/gnu/io/CommPortEnumerator.java | 76 +- src/main/java/gnu/io/CommPortIdentifier.java | 549 ++-- src/main/java/gnu/io/NRSerialPort.java | 532 ++-- src/main/java/gnu/io/NativeResource.java | 139 +- src/main/java/gnu/io/RXTXCommDriver.java | 1119 ++++---- src/main/java/gnu/io/RXTXPort.java | 2503 ++++++++--------- src/main/java/gnu/io/Zystem.java | 379 +-- .../gnu/io/factory/SerialPortRegistry.java | 64 +- .../gnu/io/rfc2217/ComPortOptionHandler.java | 76 +- .../java/gnu/io/rfc2217/TelnetSerialPort.java | 1941 ++++++------- test/src/test/NRJavaSerialTest.java | 199 +- test/src/test/ReadTest.java | 76 +- 14 files changed, 3547 insertions(+), 4153 deletions(-) diff --git a/build.gradle b/build.gradle index 03ad1753..06987b31 100644 --- a/build.gradle +++ b/build.gradle @@ -91,6 +91,7 @@ spotless { java { importOrder() removeUnusedImports() + endWithNewline() eclipse() } } diff --git a/src/main/java/gnu/io/CommPort.java b/src/main/java/gnu/io/CommPort.java index 7674c9f9..961e3c8a 100644 --- a/src/main/java/gnu/io/CommPort.java +++ b/src/main/java/gnu/io/CommPort.java @@ -57,10 +57,9 @@ --------------------------------------------------------------------------*/ package gnu.io; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.IOException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,60 +69,49 @@ * @since JDK1.0 */ - /** - * CommPort - */ + * CommPort + */ public abstract class CommPort extends Object { private static final Logger log = LoggerFactory.getLogger(CommPort.class); protected String name; - public abstract void enableReceiveFraming( int f ) - throws UnsupportedCommOperationException; + public abstract void enableReceiveFraming(int f) throws UnsupportedCommOperationException; public abstract void disableReceiveFraming(); public abstract boolean isReceiveFramingEnabled(); public abstract int getReceiveFramingByte(); public abstract void disableReceiveTimeout(); - public abstract void enableReceiveTimeout( int time ) - throws UnsupportedCommOperationException; + public abstract void enableReceiveTimeout(int time) throws UnsupportedCommOperationException; public abstract boolean isReceiveTimeoutEnabled(); public abstract int getReceiveTimeout(); - public abstract void enableReceiveThreshold( int thresh ) - throws UnsupportedCommOperationException; + public abstract void enableReceiveThreshold(int thresh) throws UnsupportedCommOperationException; public abstract void disableReceiveThreshold(); public abstract int getReceiveThreshold(); public abstract boolean isReceiveThresholdEnabled(); - public abstract void setInputBufferSize( int size ); + public abstract void setInputBufferSize(int size); public abstract int getInputBufferSize(); - public abstract void setOutputBufferSize( int size ); + public abstract void setOutputBufferSize(int size); public abstract int getOutputBufferSize(); @SuppressWarnings("static-access") - public void close() - { + public void close() { log.trace("CommPort:close()"); - try - { - CommPortIdentifier cp = - CommPortIdentifier.getPortIdentifier(this); - if ( cp != null ) + try { + CommPortIdentifier cp = CommPortIdentifier.getPortIdentifier(this); + if (cp != null) cp.getPortIdentifier(this).internalClosePort(); - } - catch (NoSuchPortException e) - { + } catch (NoSuchPortException e) { } }; public abstract InputStream getInputStream() throws IOException; public abstract OutputStream getOutputStream() throws IOException; - public String getName() - { - return( name ); + public String getName() { + return (name); } - public String toString() - { - return( name ); + public String toString() { + return (name); } } diff --git a/src/main/java/gnu/io/CommPortEnumerator.java b/src/main/java/gnu/io/CommPortEnumerator.java index 6910023a..1cd4961c 100644 --- a/src/main/java/gnu/io/CommPortEnumerator.java +++ b/src/main/java/gnu/io/CommPortEnumerator.java @@ -55,57 +55,53 @@ | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | All trademarks belong to their respective owners. --------------------------------------------------------------------------*/ -package gnu.io; +package gnu.io; import java.util.Enumeration; /** -* @author Trent Jarvi -* @version %I%, %G% -* @since JDK1.0 -*/ - + * @author Trent Jarvi + * @version %I%, %G% + * @since JDK1.0 + */ @SuppressWarnings("unchecked") -class CommPortEnumerator implements Enumeration -{ +class CommPortEnumerator implements Enumeration { private CommPortIdentifier index; - CommPortEnumerator() - { + CommPortEnumerator() { } -/*------------------------------------------------------------------------------ - nextElement() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - public Object nextElement() - { - synchronized (CommPortIdentifier.Sync) - { - if(index != null) index = index.next; - else index=CommPortIdentifier.CommPortIndex; - return(index); + /*------------------------------------------------------------------------------ + nextElement() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + public Object nextElement() { + synchronized (CommPortIdentifier.Sync) { + if (index != null) + index = index.next; + else + index = CommPortIdentifier.CommPortIndex; + return (index); } } -/*------------------------------------------------------------------------------ - hasMoreElements() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - public boolean hasMoreElements() - { - synchronized (CommPortIdentifier.Sync) - { - if(index != null) return index.next == null ? false : true; - else return CommPortIdentifier.CommPortIndex == null ? - false : true; + /*------------------------------------------------------------------------------ + hasMoreElements() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + public boolean hasMoreElements() { + synchronized (CommPortIdentifier.Sync) { + if (index != null) + return index.next == null ? false : true; + else + return CommPortIdentifier.CommPortIndex == null ? false : true; } } } diff --git a/src/main/java/gnu/io/CommPortIdentifier.java b/src/main/java/gnu/io/CommPortIdentifier.java index 99a34728..bb40ed3d 100644 --- a/src/main/java/gnu/io/CommPortIdentifier.java +++ b/src/main/java/gnu/io/CommPortIdentifier.java @@ -55,284 +55,256 @@ | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | All trademarks belong to their respective owners. --------------------------------------------------------------------------*/ -package gnu.io; +package gnu.io; -import java.io.FileDescriptor; -import java.util.ArrayList; +import java.io.FileDescriptor; +import java.util.Enumeration; import java.util.HashMap; -import java.util.Vector; -import java.util.Enumeration; - +import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** -* @author Trent Jarvi -* @version %I%, %G% -* @since JDK1.0 -*/ + * @author Trent Jarvi + * @version %I%, %G% + * @since JDK1.0 + */ public class CommPortIdentifier extends Object /* extends Vector? */ { private static final Logger log = LoggerFactory.getLogger(CommPortIdentifier.class); - public static final int PORT_SERIAL = 1; // rs232 Port - public static final int PORT_PARALLEL = 2; // Parallel Port - public static final int PORT_I2C = 3; // i2c Port - public static final int PORT_RS485 = 4; // rs485 Port - public static final int PORT_RAW = 5; // Raw Port + public static final int PORT_SERIAL = 1; // rs232 Port + public static final int PORT_PARALLEL = 2; // Parallel Port + public static final int PORT_I2C = 3; // i2c Port + public static final int PORT_RS485 = 4; // rs485 Port + public static final int PORT_RAW = 5; // Raw Port private String PortName; - private boolean Available = true; - private String Owner; + private boolean Available = true; + private String Owner; private RXTXPort commport; private CommDriver RXTXDriver; - static CommPortIdentifier CommPortIndex; + static CommPortIdentifier CommPortIndex; CommPortIdentifier next; private int PortType; static Object Sync; @SuppressWarnings("unchecked") Vector ownershipListener; - - -/*------------------------------------------------------------------------------ - static {} aka initialization - accept: - - perform: load the rxtx driver - return: - - exceptions: Throwable - comments: static block to initialize the class -------------------------------------------------------------------------------*/ + /*------------------------------------------------------------------------------ + static {} aka initialization + accept: - + perform: load the rxtx driver + return: - + exceptions: Throwable + comments: static block to initialize the class + ------------------------------------------------------------------------------*/ // initialization only done once.... - static - { + static { Sync = new Object(); - try - { + try { CommDriver RXTXDriver = (CommDriver) Class.forName("gnu.io.RXTXCommDriver").newInstance(); RXTXDriver.initialize(); - } - catch (Throwable e) - { + } catch (Throwable e) { log.error("Failed to load gnu.io.RXTXCommDriver: {}", e.getMessage()); } String OS; OS = System.getProperty("os.name"); - if(OS.toLowerCase().indexOf("linux") == -1) - { + if (OS.toLowerCase().indexOf("linux") == -1) { log.debug("Have not implemented native_psmisc_report_owner(PortName)); in CommPortIdentifier"); } - //System.loadLibrary( "rxtxSerial" ); + // System.loadLibrary( "rxtxSerial" ); SerialManager.getInstance(); } - CommPortIdentifier ( String pn, RXTXPort cp, int pt, CommDriver driver) - { - PortName = pn; - commport = cp; - PortType = pt; - next = null; - RXTXDriver = driver; + CommPortIdentifier(String pn, RXTXPort cp, int pt, CommDriver driver) { + PortName = pn; + commport = cp; + PortType = pt; + next = null; + RXTXDriver = driver; } -/*------------------------------------------------------------------------------ - addPortName() - accept: Name of the port s, Port type, - reverence to RXTXCommDriver. - perform: place a new CommPortIdentifier in the linked list - return: none. - exceptions: none. - comments: -------------------------------------------------------------------------------*/ - public static void addPortName(String s, int type, CommDriver c) - { + /*------------------------------------------------------------------------------ + addPortName() + accept: Name of the port s, Port type, + reverence to RXTXCommDriver. + perform: place a new CommPortIdentifier in the linked list + return: none. + exceptions: none. + comments: + ------------------------------------------------------------------------------*/ + public static void addPortName(String s, int type, CommDriver c) { - log.trace("CommPortIdentifier:addPortName("+s+")"); + log.trace("CommPortIdentifier:addPortName(" + s + ")"); AddIdentifierToList(new CommPortIdentifier(s, null, type, c)); } -/*------------------------------------------------------------------------------ - AddIdentifierToList() - accept: The cpi to add to the list. - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - private static void AddIdentifierToList( CommPortIdentifier cpi) - { - synchronized (Sync) - { - if (CommPortIndex == null) - { + /*------------------------------------------------------------------------------ + AddIdentifierToList() + accept: The cpi to add to the list. + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + private static void AddIdentifierToList(CommPortIdentifier cpi) { + synchronized (Sync) { + if (CommPortIndex == null) { CommPortIndex = cpi; log.trace("CommPortIdentifier:AddIdentifierToList() null"); - } - else - { - CommPortIdentifier index = CommPortIndex; - while (index.next != null) - { + } else { + CommPortIdentifier index = CommPortIndex; + while (index.next != null) { index = index.next; } index.next = cpi; - } + } } } -/*------------------------------------------------------------------------------ - addPortOwnershipListener() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ + /*------------------------------------------------------------------------------ + addPortOwnershipListener() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ @SuppressWarnings("unchecked") - public void addPortOwnershipListener(CommPortOwnershipListener c) - { - /* is the Vector instantiated? */ + public void addPortOwnershipListener(CommPortOwnershipListener c) { + /* is the Vector instantiated? */ - if( ownershipListener == null ) - { + if (ownershipListener == null) { ownershipListener = new Vector(); } /* is the ownership listener already in the list? */ - if ( ownershipListener.contains(c) == false) - { + if (ownershipListener.contains(c) == false) { ownershipListener.addElement(c); } } -/*------------------------------------------------------------------------------ - getCurrentOwner() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - public String getCurrentOwner() - { - return( Owner ); + /*------------------------------------------------------------------------------ + getCurrentOwner() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + public String getCurrentOwner() { + return (Owner); } -/*------------------------------------------------------------------------------ - getName() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - public String getName() - { - return( PortName ); + /*------------------------------------------------------------------------------ + getName() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + public String getName() { + return (PortName); } -/*------------------------------------------------------------------------------ - getPortIdentifier() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - static public CommPortIdentifier getPortIdentifier(String s) throws NoSuchPortException - { + /*------------------------------------------------------------------------------ + getPortIdentifier() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + static public CommPortIdentifier getPortIdentifier(String s) throws NoSuchPortException { CommPortIdentifier.getPortIdentifiers(); CommPortIdentifier index; - synchronized (Sync) - { - index = CommPortIndex; - while (index != null && !index.PortName.equals(s)) { + synchronized (Sync) { + index = CommPortIndex; + while (index != null && !index.PortName.equals(s)) { index = index.next; } if (index == null) { - /* This may slow things down but if you pass the string for the port after - a device is plugged in, you can find it now. - - http://bugzilla.qbang.org/show_bug.cgi?id=48 - */ + /* + * This may slow things down but if you pass the string for the port after a + * device is plugged in, you can find it now. + * + * http://bugzilla.qbang.org/show_bug.cgi?id=48 + */ getPortIdentifiers(); - index = CommPortIndex; - while (index != null && !index.PortName.equals(s)) { + index = CommPortIndex; + while (index != null && !index.PortName.equals(s)) { index = index.next; } } } - if (index != null) return index; - else - { + if (index != null) + return index; + else { throw new NoSuchPortException(); } } -/*------------------------------------------------------------------------------ - getPortIdentifier() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - static public CommPortIdentifier getPortIdentifier(CommPort p) - throws NoSuchPortException - { + /*------------------------------------------------------------------------------ + getPortIdentifier() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + static public CommPortIdentifier getPortIdentifier(CommPort p) throws NoSuchPortException { CommPortIdentifier.getPortIdentifiers(); CommPortIdentifier c; - synchronized( Sync ) - { + synchronized (Sync) { c = CommPortIndex; - while ( c != null && c.commport != p ) + while (c != null && c.commport != p) c = c.next; } - if ( c != null ) + if (c != null) return (c); throw new NoSuchPortException(); } -/*------------------------------------------------------------------------------ - getPortIdentifiers() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ + /*------------------------------------------------------------------------------ + getPortIdentifiers() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ @SuppressWarnings("unchecked") - static public Enumeration getPortIdentifiers() - { - //Do not allow anybody get any ports while we are re-initializing - //because the CommPortIndex points to invalid instances during that time - synchronized(Sync) { - //Remember old ports in order to restore them for ownership events later + static public Enumeration getPortIdentifiers() { + // Do not allow anybody get any ports while we are re-initializing + // because the CommPortIndex points to invalid instances during that time + synchronized (Sync) { + // Remember old ports in order to restore them for ownership events later HashMap oldPorts = new HashMap(); CommPortIdentifier p = CommPortIndex; - while(p!=null) { + while (p != null) { oldPorts.put(p.PortName, p); p = p.next; } CommPortIndex = null; - try - { - //Initialize RXTX: This leads to detecting all ports - //and writing them into our CommPortIndex through our method - //{@link #addPortName(java.lang.String, int, gnu.io.CommDriver)} - //This works while lock on Sync is held + try { + // Initialize RXTX: This leads to detecting all ports + // and writing them into our CommPortIndex through our method + // {@link #addPortName(java.lang.String, int, gnu.io.CommDriver)} + // This works while lock on Sync is held RXTXCommDriver RXTXDriver = new RXTXCommDriver(); RXTXDriver.initialize(); - //Restore old CommPortIdentifier objects where possible, - //in order to support proper ownership event handling. - //Clients might still have references to old identifiers! + // Restore old CommPortIdentifier objects where possible, + // in order to support proper ownership event handling. + // Clients might still have references to old identifiers! CommPortIdentifier curPort = CommPortIndex; CommPortIdentifier prevPort = null; - while(curPort!=null) { - CommPortIdentifier matchingOldPort = (CommPortIdentifier)oldPorts.get(curPort.PortName); - if(matchingOldPort!=null && matchingOldPort.PortType == curPort.PortType) { - //replace new port by old one + while (curPort != null) { + CommPortIdentifier matchingOldPort = (CommPortIdentifier) oldPorts.get(curPort.PortName); + if (matchingOldPort != null && matchingOldPort.PortType == curPort.PortType) { + // replace new port by old one matchingOldPort.RXTXDriver = curPort.RXTXDriver; matchingOldPort.next = curPort.next; - if(prevPort==null) { + if (prevPort == null) { CommPortIndex = matchingOldPort; } else { prevPort.next = matchingOldPort; @@ -343,189 +315,166 @@ static public Enumeration getPortIdentifiers() } curPort = curPort.next; } - } - catch (Throwable e) - { + } catch (Throwable e) { log.error("Exception thrown while loading gnu.io.RXTXCommDriver", e); } } return new CommPortEnumerator(); } - -/*------------------------------------------------------------------------------ - getPortType() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - public int getPortType() - { - return( PortType ); + + /*------------------------------------------------------------------------------ + getPortType() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + public int getPortType() { + return (PortType); } -/*------------------------------------------------------------------------------ - isCurrentlyOwned() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - public synchronized boolean isCurrentlyOwned() - { - return(!Available); + /*------------------------------------------------------------------------------ + isCurrentlyOwned() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + public synchronized boolean isCurrentlyOwned() { + return (!Available); } -/*------------------------------------------------------------------------------ - open() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - public synchronized CommPort open(FileDescriptor f) throws UnsupportedCommOperationException - { + /*------------------------------------------------------------------------------ + open() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + public synchronized CommPort open(FileDescriptor f) throws UnsupportedCommOperationException { throw new UnsupportedCommOperationException(); } private native String native_psmisc_report_owner(String PortName); -/*------------------------------------------------------------------------------ - open() - accept: application making the call and milliseconds to block - during open. - perform: open the port if possible - return: CommPort if successful - exceptions: PortInUseException if in use. - comments: -------------------------------------------------------------------------------*/ + /*------------------------------------------------------------------------------ + open() + accept: application making the call and milliseconds to block + during open. + perform: open the port if possible + return: CommPort if successful + exceptions: PortInUseException if in use. + comments: + ------------------------------------------------------------------------------*/ @SuppressWarnings("unused") private boolean HideOwnerEvents; - public RXTXPort open(String TheOwner, int i) - throws gnu.io.PortInUseException - { - log.trace("CommPortIdentifier:open("+TheOwner + ", " +i+")"); + public RXTXPort open(String TheOwner, int i) throws gnu.io.PortInUseException { + log.trace("CommPortIdentifier:open(" + TheOwner + ", " + i + ")"); boolean isAvailable; - synchronized(this) { + synchronized (this) { isAvailable = this.Available; if (isAvailable) { - //assume ownership inside the synchronized block - this.Available = false; - this.Owner = TheOwner; + // assume ownership inside the synchronized block + this.Available = false; + this.Owner = TheOwner; } } - if (!isAvailable) - { + if (!isAvailable) { long waitTimeEnd = System.currentTimeMillis() + i; - //fire the ownership event outside the synchronized block + // fire the ownership event outside the synchronized block fireOwnershipEvent(CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED); long waitTimeCurr; - synchronized(this) { - while(!Available && (waitTimeCurr=System.currentTimeMillis()) < waitTimeEnd) { - try - { + synchronized (this) { + while (!Available && (waitTimeCurr = System.currentTimeMillis()) < waitTimeEnd) { + try { wait(waitTimeEnd - waitTimeCurr); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } isAvailable = this.Available; if (isAvailable) { - //assume ownership inside the synchronized block + // assume ownership inside the synchronized block this.Available = false; this.Owner = TheOwner; } } } - if (!isAvailable) - { + if (!isAvailable) { throw new gnu.io.PortInUseException(getCurrentOwner()); } - //At this point, the CommPortIdentifier is owned by us. + // At this point, the CommPortIdentifier is owned by us. try { - if(commport == null) - { - commport = (RXTXPort) RXTXDriver.getCommPort(PortName,PortType); + if (commport == null) { + commport = (RXTXPort) RXTXDriver.getCommPort(PortName, PortType); } - if(commport != null) - { + if (commport != null) { fireOwnershipEvent(CommPortOwnershipListener.PORT_OWNED); log.debug("Opened {} ({}) by {}", PortName, commport, Owner); return commport; - } - else - { + } else { throw new gnu.io.PortInUseException("Unknown Owner"); } } finally { - if(commport == null) { - //something went wrong reserving the commport -> unown the port - synchronized(this) { + if (commport == null) { + // something went wrong reserving the commport -> unown the port + synchronized (this) { this.Available = true; this.Owner = null; } } } } -/*------------------------------------------------------------------------------ - removePortOwnership() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ - public void removePortOwnershipListener(CommPortOwnershipListener c) - { + /*------------------------------------------------------------------------------ + removePortOwnership() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ + public void removePortOwnershipListener(CommPortOwnershipListener c) { /* why is this called twice? */ - if(ownershipListener != null) + if (ownershipListener != null) ownershipListener.removeElement(c); } -/*------------------------------------------------------------------------------ - internalClosePort() - accept: None - perform: clean up the Ownership information and send the event - return: None - exceptions: None - comments: None -------------------------------------------------------------------------------*/ - void internalClosePort() - { - synchronized(this) { + /*------------------------------------------------------------------------------ + internalClosePort() + accept: None + perform: clean up the Ownership information and send the event + return: None + exceptions: None + comments: None + ------------------------------------------------------------------------------*/ + void internalClosePort() { + synchronized (this) { Owner = null; Available = true; commport = null; - /* this tosses null pointer?? */ + /* this tosses null pointer?? */ notifyAll(); } fireOwnershipEvent(CommPortOwnershipListener.PORT_UNOWNED); } -/*------------------------------------------------------------------------------ - fireOwnershipEvent() - accept: - perform: - return: - exceptions: - comments: -------------------------------------------------------------------------------*/ + /*------------------------------------------------------------------------------ + fireOwnershipEvent() + accept: + perform: + return: + exceptions: + comments: + ------------------------------------------------------------------------------*/ @SuppressWarnings("unchecked") - void fireOwnershipEvent(int eventType) - { + void fireOwnershipEvent(int eventType) { log.trace("CommPortIdentifier:fireOwnershipEvent( " + eventType + " )"); - if (ownershipListener != null) - { + if (ownershipListener != null) { CommPortOwnershipListener c; - for ( Enumeration e = ownershipListener.elements(); - e.hasMoreElements(); - c.ownershipChange(eventType)) + for (Enumeration e = ownershipListener.elements(); e.hasMoreElements(); c.ownershipChange(eventType)) c = (CommPortOwnershipListener) e.nextElement(); } } } - diff --git a/src/main/java/gnu/io/NRSerialPort.java b/src/main/java/gnu/io/NRSerialPort.java index 23fda9e5..2e2d5509 100644 --- a/src/main/java/gnu/io/NRSerialPort.java +++ b/src/main/java/gnu/io/NRSerialPort.java @@ -57,6 +57,9 @@ --------------------------------------------------------------------------*/ package gnu.io; +import gnu.io.factory.RFC2217PortCreator; +import gnu.io.factory.RxTxPortCreator; +import gnu.io.rfc2217.TelnetSerialPort; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -64,308 +67,257 @@ import java.util.HashSet; import java.util.Set; import java.util.TooManyListenersException; - -import gnu.io.factory.RFC2217PortCreator; -import gnu.io.factory.RxTxPortCreator; -import gnu.io.rfc2217.TelnetSerialPort; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class NRSerialPort -{ - private static final Logger log = LoggerFactory.getLogger(NRSerialPort.class); - - private SerialPort serial; - private String port = null; - private boolean connected = false; - private int baud = 115200; - private int parity = SerialPort.PARITY_NONE; - private int dataBits = SerialPort.DATABITS_8; - private int stopBits = SerialPort.STOPBITS_1; - - /** - * Class Constructor for a NRSerialPort with a given port and baudrate. - * - * @param port the port to connect to (i.e. COM6 or /dev/ttyUSB0) - */ - - public NRSerialPort(String port) - { - setPort(port); - } - - public NRSerialPort(String port, int baud) - { - setPort(port); - setBaud(baud); - } - - public NRSerialPort(String port, int baud, int parity) - { - setPort(port); - setBaud(baud); - setParity(parity); - } - - public NRSerialPort(String port, int baud, int parity, int dataBits) - { - setPort(port); - setBaud(baud); - setParity(parity); - setDataBits(dataBits); - } - - public NRSerialPort(String port, int baud, int parity, int dataBits, int stopBits) - { - setPort(port); - setBaud(baud); - setParity(parity); - setDataBits(dataBits); - setStopBits(stopBits); - } - - public boolean connect() - { - if (isConnected()) - { - log.warn(port + " is already connected."); - return true; - } - - try - { - if(port.toLowerCase().startsWith("rfc2217")) - serial = new RFC2217PortCreator().createPort(port); - else - serial = new RxTxPortCreator().createPort(port); - serial.setSerialPortParams(getBaud(), getDataBits(), getStopBits(), getParity()); - setConnected(true); - } - catch (NativeResourceException e) - { - throw new NativeResourceException(e.getMessage()); - } - catch (Exception e) - { - log.error("Failed to connect on port: " + port, e); - setConnected(false); - } - - if (isConnected()) - { - serial.notifyOnDataAvailable(true); - } - return isConnected(); - } - - - public InputStream getInputStream() - { +public class NRSerialPort { + private static final Logger log = LoggerFactory.getLogger(NRSerialPort.class); + + private SerialPort serial; + private String port = null; + private boolean connected = false; + private int baud = 115200; + private int parity = SerialPort.PARITY_NONE; + private int dataBits = SerialPort.DATABITS_8; + private int stopBits = SerialPort.STOPBITS_1; + + /** + * Class Constructor for a NRSerialPort with a given port and baudrate. + * + * @param port + * the port to connect to (i.e. COM6 or /dev/ttyUSB0) + */ + + public NRSerialPort(String port) { + setPort(port); + } + + public NRSerialPort(String port, int baud) { + setPort(port); + setBaud(baud); + } + + public NRSerialPort(String port, int baud, int parity) { + setPort(port); + setBaud(baud); + setParity(parity); + } + + public NRSerialPort(String port, int baud, int parity, int dataBits) { + setPort(port); + setBaud(baud); + setParity(parity); + setDataBits(dataBits); + } + + public NRSerialPort(String port, int baud, int parity, int dataBits, int stopBits) { + setPort(port); + setBaud(baud); + setParity(parity); + setDataBits(dataBits); + setStopBits(stopBits); + } + + public boolean connect() { + if (isConnected()) { + log.warn(port + " is already connected."); + return true; + } + + try { + if (port.toLowerCase().startsWith("rfc2217")) + serial = new RFC2217PortCreator().createPort(port); + else + serial = new RxTxPortCreator().createPort(port); + serial.setSerialPortParams(getBaud(), getDataBits(), getStopBits(), getParity()); + setConnected(true); + } catch (NativeResourceException e) { + throw new NativeResourceException(e.getMessage()); + } catch (Exception e) { + log.error("Failed to connect on port: " + port, e); + setConnected(false); + } + + if (isConnected()) { + serial.notifyOnDataAvailable(true); + } + return isConnected(); + } + + public InputStream getInputStream() { try { return serial.getInputStream(); } catch (IOException e) { throw new RuntimeException(e); } - } - + } - public OutputStream getOutputStream() - { + public OutputStream getOutputStream() { try { return serial.getOutputStream(); } catch (IOException e) { throw new RuntimeException(e); } - } - - - /** - * Set the port to use (i.e. COM6 or /dev/ttyUSB0) - * - * @param port the serial port to use - */ - private void setPort(String port) - { - this.port = port; - } - - - public void disconnect() - { - try - { - try - { - getInputStream().close(); - getOutputStream().close(); - serial.close(); - } - catch (Exception e) - { - e.printStackTrace(); - throw new RuntimeException(e); - } - serial = null; - setConnected(false); - } - catch (UnsatisfiedLinkError e) - { - throw new NativeResourceException(e.getMessage()); - } - } - - - public static Set getAvailableSerialPorts() - { - Set available = new HashSet(); - try - { - RXTXCommDriver d = new RXTXCommDriver(); - Set av = d.getPortIdentifiers(); - ArrayList strs = new ArrayList(); - for (String s : av) - { - strs.add(0, s); - } - for (String s : strs) - { - available.add(s); - } - } - catch (UnsatisfiedLinkError e) - { - e.printStackTrace(); - throw new NativeResourceException(e.getMessage()); - } - - return available; - } - - - public boolean isConnected() - { - return connected; - } - - - public void setConnected(boolean connected) - { - if (this.connected == connected) - return; - this.connected = connected; - } - - - public void setBaud(int baud) - { - - this.baud = baud; - return; - - } - - - public int getBaud() - { - return baud; - } - - public void setParity(int parity) - { - this.parity = parity; - } - - public int getParity() - { - return this.parity; - } - - public void setStopBits(int stopBits) - { - this.stopBits = stopBits; - } - - public int getStopBits() - { - return this.stopBits; - } - - public void setDataBits(int dataBits) - { - this.dataBits = dataBits; - } - - public int getDataBits() - { - return this.dataBits; - } - - /** - * Enables RS485 half-duplex bus communication for Linux. The Linux kernel uses the RTS pin as bus enable. If you use a device that is configured via the Linux - * device tree, take care to add "uart-has-rtscts" and to configure the RTS GPIO correctly. - * - * Before enabling RS485, the serial port must be connected/opened. - * - * See also: - *
    - *
  • https://www.kernel.org/doc/Documentation/serial/serial-rs485.txt - *
  • https://www.kernel.org/doc/Documentation/devicetree/bindings/serial/serial.txt - *
- * - * @param busEnableActiveLow - * true, if the bus enable signal (RTS) shall be low during transmission - * @param delayBusEnableBeforeSendMs - * delay of bus enable signal (RTS) edge to first data edge in ms (not supported by all serial drivers) - * @param delayBusEnableAfterSendMs - * delay of bus enable signal (RTS) edge after end of transmission in ms (not supported by all serial drivers) - * @return the ioctl() return value - */ - public int enableRs485(boolean busEnableActiveLow, int delayBusEnableBeforeSendMs, int delayBusEnableAfterSendMs) { - if(serial == null) - return -1; - if(RXTXPort.class.isInstance(serial)) - return ((RXTXPort) serial).enableRs485(busEnableActiveLow, delayBusEnableBeforeSendMs, delayBusEnableAfterSendMs); - return -1; - } - - public void notifyOnDataAvailable(boolean b) - { - serial.notifyOnDataAvailable(b); - } - - - public void addEventListener(SerialPortEventListener lsnr) throws TooManyListenersException - { - serial.addEventListener(lsnr); - } - - - public void removeEventListener() - { - serial.removeEventListener(); - } - - /** - * Gets the {@link SerialPort} instance. - * This will return null until {@link #connect()} is successfully called. - * @return The {@link SerialPort} instance or null. - */ - public RXTXPort getSerialPortInstance() - { - if(RXTXPort.class.isInstance(serial)) - return (RXTXPort) serial; - return null; - } - /** - * Gets the {@link SerialPort} instance. - * This will return null until {@link #connect()} is successfully called. - * @return The {@link SerialPort} instance or null. - */ - public TelnetSerialPort getTelnetSerialPortInstance() - { - if(TelnetSerialPort.class.isInstance(serial)) - return (TelnetSerialPort) serial; - return null; - } + } + + /** + * Set the port to use (i.e. COM6 or /dev/ttyUSB0) + * + * @param port + * the serial port to use + */ + private void setPort(String port) { + this.port = port; + } + + public void disconnect() { + try { + try { + getInputStream().close(); + getOutputStream().close(); + serial.close(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + serial = null; + setConnected(false); + } catch (UnsatisfiedLinkError e) { + throw new NativeResourceException(e.getMessage()); + } + } + + public static Set getAvailableSerialPorts() { + Set available = new HashSet(); + try { + RXTXCommDriver d = new RXTXCommDriver(); + Set av = d.getPortIdentifiers(); + ArrayList strs = new ArrayList(); + for (String s : av) { + strs.add(0, s); + } + for (String s : strs) { + available.add(s); + } + } catch (UnsatisfiedLinkError e) { + e.printStackTrace(); + throw new NativeResourceException(e.getMessage()); + } + + return available; + } + + public boolean isConnected() { + return connected; + } + + public void setConnected(boolean connected) { + if (this.connected == connected) + return; + this.connected = connected; + } + + public void setBaud(int baud) { + + this.baud = baud; + return; + + } + + public int getBaud() { + return baud; + } + + public void setParity(int parity) { + this.parity = parity; + } + + public int getParity() { + return this.parity; + } + + public void setStopBits(int stopBits) { + this.stopBits = stopBits; + } + + public int getStopBits() { + return this.stopBits; + } + + public void setDataBits(int dataBits) { + this.dataBits = dataBits; + } + + public int getDataBits() { + return this.dataBits; + } + + /** + * Enables RS485 half-duplex bus communication for Linux. The Linux kernel uses + * the RTS pin as bus enable. If you use a device that is configured via the + * Linux device tree, take care to add "uart-has-rtscts" and to configure the + * RTS GPIO correctly. + * + * Before enabling RS485, the serial port must be connected/opened. + * + * See also: + *
    + *
  • https://www.kernel.org/doc/Documentation/serial/serial-rs485.txt + *
  • https://www.kernel.org/doc/Documentation/devicetree/bindings/serial/serial.txt + *
+ * + * @param busEnableActiveLow + * true, if the bus enable signal (RTS) shall be low during + * transmission + * @param delayBusEnableBeforeSendMs + * delay of bus enable signal (RTS) edge to first data edge in ms + * (not supported by all serial drivers) + * @param delayBusEnableAfterSendMs + * delay of bus enable signal (RTS) edge after end of transmission in + * ms (not supported by all serial drivers) + * @return the ioctl() return value + */ + public int enableRs485(boolean busEnableActiveLow, int delayBusEnableBeforeSendMs, int delayBusEnableAfterSendMs) { + if (serial == null) + return -1; + if (RXTXPort.class.isInstance(serial)) + return ((RXTXPort) serial).enableRs485(busEnableActiveLow, delayBusEnableBeforeSendMs, + delayBusEnableAfterSendMs); + return -1; + } + + public void notifyOnDataAvailable(boolean b) { + serial.notifyOnDataAvailable(b); + } + + public void addEventListener(SerialPortEventListener lsnr) throws TooManyListenersException { + serial.addEventListener(lsnr); + } + + public void removeEventListener() { + serial.removeEventListener(); + } + + /** + * Gets the {@link SerialPort} instance. This will return null until + * {@link #connect()} is successfully called. + * + * @return The {@link SerialPort} instance or null. + */ + public RXTXPort getSerialPortInstance() { + if (RXTXPort.class.isInstance(serial)) + return (RXTXPort) serial; + return null; + } + /** + * Gets the {@link SerialPort} instance. This will return null until + * {@link #connect()} is successfully called. + * + * @return The {@link SerialPort} instance or null. + */ + public TelnetSerialPort getTelnetSerialPortInstance() { + if (TelnetSerialPort.class.isInstance(serial)) + return (TelnetSerialPort) serial; + return null; + } } diff --git a/src/main/java/gnu/io/NativeResource.java b/src/main/java/gnu/io/NativeResource.java index dad659c4..41c33d8b 100644 --- a/src/main/java/gnu/io/NativeResource.java +++ b/src/main/java/gnu/io/NativeResource.java @@ -61,7 +61,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,27 +69,28 @@ public class NativeResource { private boolean loaded = false; public synchronized void load(String libraryName) throws NativeResourceException { - if(loaded) { + if (loaded) { return; } loaded = true; - if(System.getProperty(libraryName + ".userlib") != null) { + if (System.getProperty(libraryName + ".userlib") != null) { try { - if(System.getProperty(libraryName + ".userlib").equalsIgnoreCase("sys")) { + if (System.getProperty(libraryName + ".userlib").equalsIgnoreCase("sys")) { System.loadLibrary(libraryName); } else { System.load(System.getProperty(libraryName + ".userlib")); } return; - } catch (Exception e){ - throw new NativeResourceException("Unable to load native resource from given path: " + e.getLocalizedMessage()); + } catch (Exception e) { + throw new NativeResourceException( + "Unable to load native resource from given path: " + e.getLocalizedMessage()); } } loadLib(libraryName); } - private void inJarLoad(String name)throws UnsatisfiedLinkError, NativeResourceException{ - //start by assuming the library can be loaded from the jar + private void inJarLoad(String name) throws UnsatisfiedLinkError, NativeResourceException { + // start by assuming the library can be loaded from the jar InputStream resourceSource = locateResource(name); File resourceLocation = prepResourceLocation(name); try { @@ -102,56 +102,58 @@ private void inJarLoad(String name)throws UnsatisfiedLinkError, NativeResourceEx testNativeCode(); } - private static final String[] ARM32_LIBS = {"libNRJavaSerialv8_HF","libNRJavaSerialv8","libNRJavaSerialv7_HF","libNRJavaSerialv7","libNRJavaSerialv6_HF","libNRJavaSerialv6","libNRJavaSerialv5"}; + private static final String[] ARM32_LIBS = {"libNRJavaSerialv8_HF", "libNRJavaSerialv8", "libNRJavaSerialv7_HF", + "libNRJavaSerialv7", "libNRJavaSerialv6_HF", "libNRJavaSerialv6", "libNRJavaSerialv5"}; private static final String[] ARM64_LIBS = {"libNRJavaSerialv8"}; private void loadLib(String name) throws NativeResourceException { try { - if(OSUtil.isARM()) { - for(String libName : OSUtil.is64Bit() ? ARM64_LIBS : ARM32_LIBS) { + if (OSUtil.isARM()) { + for (String libName : OSUtil.is64Bit() ? ARM64_LIBS : ARM32_LIBS) { try { inJarLoad(libName); log.debug("Loaded native ARM library: {}", libName); return; - }catch(UnsatisfiedLinkError e) { + } catch (UnsatisfiedLinkError e) { // nothing } } log.error("No library found for ARM"); - }else { + } else { inJarLoad(name); log.debug("Loaded native library: {}", name); } return; } catch (UnsatisfiedLinkError ex) { - if(OSUtil.isOSX() || OSUtil.isLinux()){ - try{ + if (OSUtil.isOSX() || OSUtil.isLinux()) { + try { inJarLoad("libNRJavaSerial_legacy"); log.debug("Normal lib failed, using legacy..OK!"); return; - }catch(UnsatisfiedLinkError er){ + } catch (UnsatisfiedLinkError er) { log.error("Failed to load library", er); } - }else{ + } else { log.error("Failed to load library", ex); } - try{ - //check to see if the library is available in standard locations - String libName = name.substring(name.indexOf("lib")+3); + try { + // check to see if the library is available in standard locations + String libName = name.substring(name.indexOf("lib") + 3); System.loadLibrary(libName); testNativeCode(); log.debug("Loaded native library fallback: {}", name); return; - }catch(UnsatisfiedLinkError e){ - try{ + } catch (UnsatisfiedLinkError e) { + try { name = "rxtxSerial"; - //last ditch effort to load + // last ditch effort to load System.loadLibrary(name); testNativeCode(); log.debug("Loaded native library RXTX: {}", name); return; - }catch(UnsatisfiedLinkError err){ - log.error("Failed to load all possible JNI local and from: {}", System.getProperty("java.library.path")); + } catch (UnsatisfiedLinkError err) { + log.error("Failed to load all possible JNI local and from: {}", + System.getProperty("java.library.path")); throw new NativeResourceException("Unable to load deployed native resource"); } } @@ -159,59 +161,59 @@ private void loadLib(String name) throws NativeResourceException { } } - private void testNativeCode()throws UnsatisfiedLinkError { + private void testNativeCode() throws UnsatisfiedLinkError { CommPortIdentifier.getPortIdentifiers(); } private InputStream locateResource(String name) { name += OSUtil.getExtension(); - String file=""; - if(OSUtil.isOSX()) { - file="/native/osx/" + name; - }else if(OSUtil.isWindows()) { - if(OSUtil.is64Bit()){ - file="/native/windows/x86_64/" + name; - }else { - file="/native/windows/x86_32/" + name; + String file = ""; + if (OSUtil.isOSX()) { + file = "/native/osx/" + name; + } else if (OSUtil.isWindows()) { + if (OSUtil.is64Bit()) { + file = "/native/windows/x86_64/" + name; + } else { + file = "/native/windows/x86_32/" + name; } - }else if(OSUtil.isLinux()) { - if(OSUtil.isARM()) { - if(OSUtil.is64Bit()) { - file="/native/linux/ARM_64/" + name; - }else { - file="/native/linux/ARM_32/" + name; + } else if (OSUtil.isLinux()) { + if (OSUtil.isARM()) { + if (OSUtil.is64Bit()) { + file = "/native/linux/ARM_64/" + name; + } else { + file = "/native/linux/ARM_32/" + name; } - }else if(OSUtil.isPPC()) { + } else if (OSUtil.isPPC()) { file = "/native/linux/PPC/" + name; - }else { - if(OSUtil.is64Bit()) { - file="/native/linux/x86_64/" + name; - }else { - file="/native/linux/x86_32/" + name; + } else { + if (OSUtil.is64Bit()) { + file = "/native/linux/x86_64/" + name; + } else { + file = "/native/linux/x86_32/" + name; } } - }else if(OSUtil.isFreeBSD()) { - if(OSUtil.is64Bit()) { - file="/native/freebsd/x86_64/" + name; - }else { - file="/native/freebsd/x86_32/" + name; + } else if (OSUtil.isFreeBSD()) { + if (OSUtil.is64Bit()) { + file = "/native/freebsd/x86_64/" + name; + } else { + file = "/native/freebsd/x86_32/" + name; } - }else{ - log.error("Can't load native file: "+name+" for os arch: "+OSUtil.getOsArch()); + } else { + log.error("Can't load native file: " + name + " for os arch: " + OSUtil.getOsArch()); return null; } - log.trace("Loading "+file); + log.trace("Loading " + file); return getClass().getResourceAsStream(file); } private void loadResource(File resource) { - if(!resource.canRead()) { - throw new RuntimeException("Cant open JNI file: "+resource.getAbsolutePath()); + if (!resource.canRead()) { + throw new RuntimeException("Cant open JNI file: " + resource.getAbsolutePath()); } - log.trace("Loading: "+resource.getAbsolutePath()); + log.trace("Loading: " + resource.getAbsolutePath()); try { System.load(resource.getAbsolutePath()); - } catch(UnsatisfiedLinkError e){ + } catch (UnsatisfiedLinkError e) { throw e; } } @@ -219,7 +221,6 @@ private void loadResource(File resource) { private void copyResource(InputStream io, File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); - byte[] buf = new byte[256]; int read = 0; while ((read = io.read(buf)) > 0) { @@ -231,7 +232,7 @@ private void copyResource(InputStream io, File file) throws IOException { private File prepResourceLocation(String fileName) throws NativeResourceException { String tmpDir = System.getProperty("java.io.tmpdir"); - //String tmpDir = "M:\\"; + // String tmpDir = "M:\\"; if ((tmpDir == null) || (tmpDir.length() == 0)) { tmpDir = "tmp"; } @@ -243,7 +244,7 @@ private File prepResourceLocation(String fileName) throws NativeResourceExceptio File fd = null; File dir = null; - for(int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) { dir = new File(tmpDir, displayName + "_" + user + "_" + (i)); if (dir.exists()) { if (!dir.isDirectory()) { @@ -290,16 +291,17 @@ private File prepResourceLocation(String fileName) throws NativeResourceExceptio break; } - if(fd == null || !fd.canRead()) { + if (fd == null || !fd.canRead()) { throw new NativeResourceException("Unable to deploy native resource"); } - log.trace("Local file: "+fd.getAbsolutePath()); + log.trace("Local file: " + fd.getAbsolutePath()); return fd; } private static class OSUtil { public static boolean is64Bit() { - return getOsArch().startsWith("x86_64") || getOsArch().startsWith("amd64") || getOsArch().startsWith("aarch64"); + return getOsArch().startsWith("x86_64") || getOsArch().startsWith("amd64") + || getOsArch().startsWith("aarch64"); } public static boolean isARM() { return getOsArch().startsWith("arm") || getOsArch().startsWith("aarch"); @@ -308,7 +310,8 @@ public static boolean isPPC() { return getOsArch().toLowerCase().contains("ppc"); } public static boolean isWindows() { - return getOsName().toLowerCase().startsWith("windows") ||getOsName().toLowerCase().startsWith("microsoft") || getOsName().toLowerCase().startsWith("ms"); + return getOsName().toLowerCase().startsWith("windows") || getOsName().toLowerCase().startsWith("microsoft") + || getOsName().toLowerCase().startsWith("ms"); } public static boolean isLinux() { @@ -324,15 +327,15 @@ public static boolean isOSX() { } public static String getExtension() { - if(isWindows()) { + if (isWindows()) { return ".dll"; } - if(isLinux() || isFreeBSD()) { + if (isLinux() || isFreeBSD()) { return ".so"; } - if(isOSX()) { + if (isOSX()) { return ".jnilib"; } diff --git a/src/main/java/gnu/io/RXTXCommDriver.java b/src/main/java/gnu/io/RXTXCommDriver.java index 1bb5e2f6..2e6007ba 100644 --- a/src/main/java/gnu/io/RXTXCommDriver.java +++ b/src/main/java/gnu/io/RXTXCommDriver.java @@ -76,44 +76,39 @@ import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - This is the JavaComm for Linux driver. -*/ -public class RXTXCommDriver implements CommDriver -{ + * This is the JavaComm for Linux driver. + */ +public class RXTXCommDriver implements CommDriver { private static final Logger log = LoggerFactory.getLogger(RXTXCommDriver.class); - private static Set ports =new HashSet(); + private static Set ports = new HashSet(); private final static boolean devel = false; - private final static boolean noVersionOutput = "true".equals( System.getProperty( "gnu.io.rxtx.NoVersionOutput" ) ); + private final static boolean noVersionOutput = "true".equals(System.getProperty("gnu.io.rxtx.NoVersionOutput")); - static - { - if(ports==null) - ports =new HashSet(); - //System.loadLibrary( "rxtxSerial" ); + static { + if (ports == null) + ports = new HashSet(); + // System.loadLibrary( "rxtxSerial" ); SerialManager.getInstance(); /* - Perform a crude check to make sure people don't mix - versions of the Jar and native lib - - Mixing the libs can create a nightmare. - - It could be possible to move this over to RXTXVersion - but All we want to do is warn people when first loading - the Library. - */ + * Perform a crude check to make sure people don't mix versions of the Jar and + * native lib + * + * Mixing the libs can create a nightmare. + * + * It could be possible to move this over to RXTXVersion but All we want to do + * is warn people when first loading the Library. + */ String JarVersion = RXTXVersion.getVersion(); String LibVersion; try { - LibVersion = RXTXVersion.nativeGetVersion(); - } catch ( Error UnsatisfiedLinkError ) - { + LibVersion = RXTXVersion.nativeGetVersion(); + } catch (Error UnsatisfiedLinkError) { // for rxtx prior to 2.1.7 LibVersion = nativeGetVersion(); } @@ -128,197 +123,157 @@ public class RXTXCommDriver implements CommDriver private native String getDeviceDirectory(); // for rxtx prior to 2.1.7 private static native String nativeGetVersion(); - + public static String nativeGetVersionWrapper() throws UnsatisfiedLinkError { return nativeGetVersion(); } public Set getPortIdentifiers() { - ports =new HashSet(); + ports = new HashSet(); registerScannedPorts(CommPortIdentifier.PORT_SERIAL); - Enumeration pe; - try{ - pe = CommPortIdentifier.getPortIdentifiers(); - }catch( UnsatisfiedLinkError e){ - e.printStackTrace(); - return null; - } - if(pe != null){ - while (pe.hasMoreElements()) { - CommPortIdentifier com = (CommPortIdentifier) pe.nextElement(); - switch (com.getPortType()) { - case CommPortIdentifier.PORT_SERIAL: - if(com.getName().matches("^/.+/cu\\..+$")) { - continue; - } - if(com.getName().matches("^/.+/tty\\.Bluetooth.+$")) { - continue; - } - boolean inList=false; - for(String s:ports){ - if(com.getName().contains(s)){ - inList=true; - } - } - if(!inList){ - ports.add(com.getName()); - } - } - } - } + Enumeration pe; + try { + pe = CommPortIdentifier.getPortIdentifiers(); + } catch (UnsatisfiedLinkError e) { + e.printStackTrace(); + return null; + } + if (pe != null) { + while (pe.hasMoreElements()) { + CommPortIdentifier com = (CommPortIdentifier) pe.nextElement(); + switch (com.getPortType()) { + case CommPortIdentifier.PORT_SERIAL : + if (com.getName().matches("^/.+/cu\\..+$")) { + continue; + } + if (com.getName().matches("^/.+/tty\\.Bluetooth.+$")) { + continue; + } + boolean inList = false; + for (String s : ports) { + if (com.getName().contains(s)) { + inList = true; + } + } + if (!inList) { + ports.add(com.getName()); + } + } + } + } return ports; } - private final String[] getValidPortPrefixes(String CandidatePortPrefixes[]) - { + private final String[] getValidPortPrefixes(String CandidatePortPrefixes[]) { /* - getScannedBufferSize() is the number of prefixes ( COM, cua, ttyS, ...) not - the number of devices (ttyS0, ttyS1, ttyS2, ...) - - On a Linux system there are about 400 prefixes in - deviceDirectory. - registerScannedPorts() assigns CandidatePortPrefixes to - something less than 50 prefixes. - - Trent - */ - - String ValidPortPrefixes[]=new String [getScannedBufferSize()]; + * getScannedBufferSize() is the number of prefixes ( COM, cua, ttyS, ...) not + * the number of devices (ttyS0, ttyS1, ttyS2, ...) + * + * On a Linux system there are about 400 prefixes in deviceDirectory. + * registerScannedPorts() assigns CandidatePortPrefixes to something less than + * 50 prefixes. + * + * Trent + */ + + String ValidPortPrefixes[] = new String[getScannedBufferSize()]; log.trace("RXTXCommDriver:getValidPortPrefixes()"); - if(CandidatePortPrefixes==null) - { - log.debug("RXTXCommDriver:getValidPortPrefixes() No ports prefixes known for this System. Please check the port prefixes listed for {} in RXTXCommDriver:registerScannedPorts()", osName); + if (CandidatePortPrefixes == null) { + log.debug( + "RXTXCommDriver:getValidPortPrefixes() No ports prefixes known for this System. Please check the port prefixes listed for {} in RXTXCommDriver:registerScannedPorts()", + osName); } - int i=0; - for(int j=0;j foundDevices = new ArrayList<>(); - if ( CandidateDeviceNames!=null && ValidPortPrefixes!=null) - { - for( i = 0;i 0 ) - term[l++] ="term/"; - /* - dev = new File( "/dev/cua0" ); - if( dev.list().length > 0 ) - term[l++] = "cua/"; - */ - String[] temp = new String[l]; - for(l--;l >= 0;l--) - temp[l] = term[l]; - CandidateDeviceNames=temp; - } - else - { - File dev = new File( deviceDirectory ); - String[] temp = dev.list(); - CandidateDeviceNames=temp; - } - if (CandidateDeviceNames==null) - { - log.debug("RXTXCommDriver:registerScannedPorts() no Device files to check "); - return; - } + /* + * + * ok.. Look the the dirctories representing the port kernel driver interface. + * + * If there are entries there are possibly ports we can use and need to + * enumerate. + */ + + String term[] = new String[2]; + int l = 0; + File dev = null; + + dev = new File("/dev/term"); + if (dev.list().length > 0) + term[l++] = "term/"; + /* + * dev = new File( "/dev/cua0" ); if( dev.list().length > 0 ) term[l++] = + * "cua/"; + */ + String[] temp = new String[l]; + for (l--; l >= 0; l--) + temp[l] = term[l]; + CandidateDeviceNames = temp; + } else { + File dev = new File(deviceDirectory); + String[] temp = dev.list(); + CandidateDeviceNames = temp; + } + if (CandidateDeviceNames == null) { + log.debug("RXTXCommDriver:registerScannedPorts() no Device files to check "); + return; + } - String CandidatePortPrefixes[] = {}; - switch (PortType) { - case CommPortIdentifier.PORT_SERIAL: - /* There are _many_ possible ports that can be used - on Linux. See below in the fake Linux-all-ports - case for a list. You may add additional ports - here but be warned that too many will significantly - slow down port enumeration. Linux 2.6 has udev - support which should be faster as only ports the - kernel finds should be exposed in /dev - - See also how to override port enumeration and - specifying port in INSTALL. - - taj - */ - - if(osName.equals("Linux")) - { - String[] Temp = { - "ttyS", // linux Serial Ports - "ttySA", // for the IPAQs - "ttyUSB", // for USB frobs - "ttyAMA", // Raspberry Pi - "rfcomm", // bluetooth serial device - "ttyircomm", // linux IrCommdevices (IrDA serial emu) - "ttyACM",// linux CDC ACM devices - "DyIO",// NRDyIO - "Bootloader",// NRDyIO bootloader - "BowlerDevice",// Generic Bowler Device - "DeltaDoodle",// DeltaDoodle Printer - "dyio"// linux CDC ACM devices - }; - CandidatePortPrefixes=Temp; - } - else if(osName.equals("Linux-all-ports")) - { - /* if you want to enumerate all ports ~5000 - possible, then replace the above with this - */ - String[] Temp = { - "comx", // linux COMMX synchronous serial card - "holter", // custom card for heart monitoring - "modem", // linux symbolic link to modem. - "rfcomm", // bluetooth serial device - "ttyircomm", // linux IrCommdevices (IrDA serial emu) - "ttycosa0c", // linux COSA/SRP synchronous serial card - "ttycosa1c", // linux COSA/SRP synchronous serial card - "ttyACM",// linux CDC ACM devices - "DyIO",// linux CDC ACM devices - "Bootloader",// linux CDC ACM devices - "BowlerDevice",// Generic Bowler Device - "DeltaDoodle",// DeltaDoodle Printer - "dyio",// linux CDC ACM devices - "ttyC", // linux cyclades cards - "ttyCH",// linux Chase Research AT/PCI-Fast serial card - "ttyD", // linux Digiboard serial card - "ttyE", // linux Stallion serial card - "ttyF", // linux Computone IntelliPort serial card - "ttyH", // linux Chase serial card - "ttyI", // linux virtual modems - "ttyL", // linux SDL RISCom serial card - "ttyM", // linux PAM Software's multimodem boards + String CandidatePortPrefixes[] = {}; + switch (PortType) { + case CommPortIdentifier.PORT_SERIAL : + /* + * There are _many_ possible ports that can be used on Linux. See below in the + * fake Linux-all-ports case for a list. You may add additional ports here but + * be warned that too many will significantly slow down port enumeration. Linux + * 2.6 has udev support which should be faster as only ports the kernel finds + * should be exposed in /dev + * + * See also how to override port enumeration and specifying port in INSTALL. + * + * taj + */ + + if (osName.equals("Linux")) { + String[] Temp = {"ttyS", // linux Serial Ports + "ttySA", // for the IPAQs + "ttyUSB", // for USB frobs + "ttyAMA", // Raspberry Pi + "rfcomm", // bluetooth serial device + "ttyircomm", // linux IrCommdevices (IrDA serial emu) + "ttyACM", // linux CDC ACM devices + "DyIO", // NRDyIO + "Bootloader", // NRDyIO bootloader + "BowlerDevice", // Generic Bowler Device + "DeltaDoodle", // DeltaDoodle Printer + "dyio"// linux CDC ACM devices + }; + CandidatePortPrefixes = Temp; + } else if (osName.equals("Linux-all-ports")) { + /* + * if you want to enumerate all ports ~5000 possible, then replace the above + * with this + */ + String[] Temp = {"comx", // linux COMMX synchronous serial card + "holter", // custom card for heart monitoring + "modem", // linux symbolic link to modem. + "rfcomm", // bluetooth serial device + "ttyircomm", // linux IrCommdevices (IrDA serial emu) + "ttycosa0c", // linux COSA/SRP synchronous serial card + "ttycosa1c", // linux COSA/SRP synchronous serial card + "ttyACM", // linux CDC ACM devices + "DyIO", // linux CDC ACM devices + "Bootloader", // linux CDC ACM devices + "BowlerDevice", // Generic Bowler Device + "DeltaDoodle", // DeltaDoodle Printer + "dyio", // linux CDC ACM devices + "ttyC", // linux cyclades cards + "ttyCH", // linux Chase Research AT/PCI-Fast serial card + "ttyD", // linux Digiboard serial card + "ttyE", // linux Stallion serial card + "ttyF", // linux Computone IntelliPort serial card + "ttyH", // linux Chase serial card + "ttyI", // linux virtual modems + "ttyL", // linux SDL RISCom serial card + "ttyM", // linux PAM Software's multimodem boards // linux ISI serial card - "ttyMX",// linux Moxa Smart IO cards - "ttyP", // linux Hayes ESP serial card - "ttyR", // linux comtrol cards + "ttyMX", // linux Moxa Smart IO cards + "ttyP", // linux Hayes ESP serial card + "ttyR", // linux comtrol cards // linux Specialix RIO serial card - "ttyS", // linux Serial Ports - "ttySI",// linux SmartIO serial card - "ttySR",// linux Specialix RIO serial card 257+ - "ttyT", // linux Technology Concepts serial card - "ttyUSB",//linux USB serial converters - "ttyV", // linux Comtrol VS-1000 serial controller - "ttyW", // linux specialix cards - "ttyX" // linux SpecialX serial card - }; - CandidatePortPrefixes=Temp; - } - else if(osName.toLowerCase().indexOf("qnx") != -1 ) - { - String[] Temp = { - "ser" - }; - CandidatePortPrefixes=Temp; - } - else if(osName.equals("Irix")) - { - String[] Temp = { - "ttyc", // irix raw character devices + "ttyS", // linux Serial Ports + "ttySI", // linux SmartIO serial card + "ttySR", // linux Specialix RIO serial card 257+ + "ttyT", // linux Technology Concepts serial card + "ttyUSB", // linux USB serial converters + "ttyV", // linux Comtrol VS-1000 serial controller + "ttyW", // linux specialix cards + "ttyX" // linux SpecialX serial card + }; + CandidatePortPrefixes = Temp; + } else if (osName.toLowerCase().indexOf("qnx") != -1) { + String[] Temp = {"ser"}; + CandidatePortPrefixes = Temp; + } else if (osName.equals("Irix")) { + String[] Temp = {"ttyc", // irix raw character devices "ttyd", // irix basic serial ports "ttyf", // irix serial ports with hardware flow "ttym", // irix modems "ttyq", // irix pseudo ttys - "tty4d",// irix RS422 - "tty4f",// irix RS422 with HSKo/HSki + "tty4d", // irix RS422 + "tty4f", // irix RS422 with HSKo/HSki "midi", // irix serial midi - "us" // irix mapped interface - }; - CandidatePortPrefixes=Temp; - } - else if(osName.equals("FreeBSD")) //FIXME this is probably wrong - { - String[] Temp = { - "ttyd", //general purpose serial ports - "cuaa", //dialout serial ports - "ttyA", //Specialix SI/XIO dialin ports - "cuaA", //Specialix SI/XIO dialout ports - "ttyu", //general purpose usb serial ports - "cuau", //dialout usb serial ports - "ttyU", //Specialix SI/XIO usb dialin ports - "cuaU", //Specialix SI/XIO usb dialout ports - "ttyD", //Digiboard - 16 dialin ports - "cuaD", //Digiboard - 16 dialout ports - "ttyE", //Stallion EasyIO (stl) dialin ports - "cuaE", //Stallion EasyIO (stl) dialout ports - "ttyF", //Stallion Brumby (stli) dialin ports - "cuaF", //Stallion Brumby (stli) dialout ports - "ttyR", //Rocketport dialin ports - "cuaR", //Rocketport dialout ports - "stl" //Stallion EasyIO board or Brumby N - }; - CandidatePortPrefixes=Temp; - } - else if(osName.equals("NetBSD")) // FIXME this is probably wrong - { - String[] Temp = { - "tty0" // netbsd serial ports - }; - CandidatePortPrefixes=Temp; - } - else if ( osName.equals("Solaris") - || osName.equals("SunOS")) - { - String[] Temp = { - "term/", - "cua/" - }; - CandidatePortPrefixes=Temp; - } - else if(osName.equals("HP-UX")) - { - String[] Temp = { - "tty0p",// HP-UX serial ports + "us" // irix mapped interface + }; + CandidatePortPrefixes = Temp; + } else if (osName.equals("FreeBSD")) // FIXME this is probably wrong + { + String[] Temp = {"ttyd", // general purpose serial ports + "cuaa", // dialout serial ports + "ttyA", // Specialix SI/XIO dialin ports + "cuaA", // Specialix SI/XIO dialout ports + "ttyu", // general purpose usb serial ports + "cuau", // dialout usb serial ports + "ttyU", // Specialix SI/XIO usb dialin ports + "cuaU", // Specialix SI/XIO usb dialout ports + "ttyD", // Digiboard - 16 dialin ports + "cuaD", // Digiboard - 16 dialout ports + "ttyE", // Stallion EasyIO (stl) dialin ports + "cuaE", // Stallion EasyIO (stl) dialout ports + "ttyF", // Stallion Brumby (stli) dialin ports + "cuaF", // Stallion Brumby (stli) dialout ports + "ttyR", // Rocketport dialin ports + "cuaR", // Rocketport dialout ports + "stl" // Stallion EasyIO board or Brumby N + }; + CandidatePortPrefixes = Temp; + } else if (osName.equals("NetBSD")) // FIXME this is probably wrong + { + String[] Temp = {"tty0" // netbsd serial ports + }; + CandidatePortPrefixes = Temp; + } else if (osName.equals("Solaris") || osName.equals("SunOS")) { + String[] Temp = {"term/", "cua/"}; + CandidatePortPrefixes = Temp; + } else if (osName.equals("HP-UX")) { + String[] Temp = {"tty0p", // HP-UX serial ports "tty1p" // HP-UX serial ports - }; - CandidatePortPrefixes=Temp; - } + }; + CandidatePortPrefixes = Temp; + } - else if(osName.equals("UnixWare") || - osName.equals("OpenUNIX")) - { - String[] Temp = { - "tty00s", // UW7/OU8 serial ports - "tty01s", - "tty02s", - "tty03s" - }; - CandidatePortPrefixes=Temp; - } + else if (osName.equals("UnixWare") || osName.equals("OpenUNIX")) { + String[] Temp = {"tty00s", // UW7/OU8 serial ports + "tty01s", "tty02s", "tty03s"}; + CandidatePortPrefixes = Temp; + } - else if (osName.equals("OpenServer")) - { - String[] Temp = { - "tty1A", // OSR5 serial ports - "tty2A", - "tty3A", - "tty4A", - "tty5A", - "tty6A", - "tty7A", - "tty8A", - "tty9A", - "tty10A", - "tty11A", - "tty12A", - "tty13A", - "tty14A", - "tty15A", - "tty16A", - "ttyu1A", // OSR5 USB-serial ports - "ttyu2A", - "ttyu3A", - "ttyu4A", - "ttyu5A", - "ttyu6A", - "ttyu7A", - "ttyu8A", - "ttyu9A", - "ttyu10A", - "ttyu11A", - "ttyu12A", - "ttyu13A", - "ttyu14A", - "ttyu15A", - "ttyu16A" - }; - CandidatePortPrefixes=Temp; - } - else if (osName.equals("Compaq's Digital UNIX") || osName.equals("OSF1")) - { - String[] Temp = { - "tty0" // Digital Unix serial ports - }; - CandidatePortPrefixes=Temp; - } + else if (osName.equals("OpenServer")) { + String[] Temp = {"tty1A", // OSR5 serial ports + "tty2A", "tty3A", "tty4A", "tty5A", "tty6A", "tty7A", "tty8A", "tty9A", "tty10A", "tty11A", + "tty12A", "tty13A", "tty14A", "tty15A", "tty16A", "ttyu1A", // OSR5 USB-serial ports + "ttyu2A", "ttyu3A", "ttyu4A", "ttyu5A", "ttyu6A", "ttyu7A", "ttyu8A", "ttyu9A", "ttyu10A", + "ttyu11A", "ttyu12A", "ttyu13A", "ttyu14A", "ttyu15A", "ttyu16A"}; + CandidatePortPrefixes = Temp; + } else if (osName.equals("Compaq's Digital UNIX") || osName.equals("OSF1")) { + String[] Temp = {"tty0" // Digital Unix serial ports + }; + CandidatePortPrefixes = Temp; + } - else if(osName.equals("BeOS")) - { - String[] Temp = { - "serial" // BeOS serial ports - }; - CandidatePortPrefixes=Temp; - } - else if(osName.equals("Mac OS X")) - { - String[] Temp = { - // Keyspan USA-28X adapter, USB port 1 + else if (osName.equals("BeOS")) { + String[] Temp = {"serial" // BeOS serial ports + }; + CandidatePortPrefixes = Temp; + } else if (osName.equals("Mac OS X")) { + String[] Temp = { + // Keyspan USA-28X adapter, USB port 1 "cu.KeyUSA28X191.", - // Keyspan USA-28X adapter, USB port 1 + // Keyspan USA-28X adapter, USB port 1 "tty.KeyUSA28X191.", - // Keyspan USA-28X adapter, USB port 2 + // Keyspan USA-28X adapter, USB port 2 "cu.KeyUSA28X181.", - // Keyspan USA-28X adapter, USB port 2 + // Keyspan USA-28X adapter, USB port 2 "tty.KeyUSA28X181.", - // Keyspan USA-19 adapter + // Keyspan USA-19 adapter "cu.KeyUSA19181.", - // Keyspan USA-19 adapter - "tty.KeyUSA19181." - }; - CandidatePortPrefixes=Temp; - } - else if(osName.toLowerCase().indexOf("windows") != -1 ) - { - String[] Temp = { - "COM" // win32 serial ports - //"//./COM" // win32 serial ports + // Keyspan USA-19 adapter + "tty.KeyUSA19181."}; + CandidatePortPrefixes = Temp; + } else if (osName.toLowerCase().indexOf("windows") != -1) { + String[] Temp = {"COM" // win32 serial ports + // "//./COM" // win32 serial ports }; - CandidatePortPrefixes=Temp; - } - else - { - log.debug("No valid prefixes for serial ports have been entered for "+osName + " in RXTXCommDriver.java. This may just be a typo in the method registerScanPorts()."); + CandidatePortPrefixes = Temp; + } else { + log.debug("No valid prefixes for serial ports have been entered for " + osName + + " in RXTXCommDriver.java. This may just be a typo in the method registerScanPorts()."); } break; - case CommPortIdentifier.PORT_PARALLEL: - log.debug("Scanning for parallel ports for os "+osName); - /** Get the Parallel port prefixes for the running os - * Holger Lehmann - * July 12, 1999 - * IBM - */ - if(osName.equals("Linux") - /* - || osName.equals("NetBSD") FIXME - || osName.equals("HP-UX") FIXME - || osName.equals("Irix") FIXME - || osName.equals("BeOS") FIXME - || osName.equals("Compaq's Digital UNIX") FIXME - */ - ) - { - String[] temp={ - "lp" // linux printer port - }; - CandidatePortPrefixes=temp; - } - else if(osName.equals("FreeBSD")) - { - String[] temp={ - "lpt" + case CommPortIdentifier.PORT_PARALLEL : + log.debug("Scanning for parallel ports for os " + osName); + /** + * Get the Parallel port prefixes for the running os Holger Lehmann July 12, + * 1999 IBM + */ + if (osName.equals("Linux") + /* + * || osName.equals("NetBSD") FIXME || osName.equals("HP-UX") FIXME || + * osName.equals("Irix") FIXME || osName.equals("BeOS") FIXME || + * osName.equals("Compaq's Digital UNIX") FIXME + */ + ) { + String[] temp = {"lp" // linux printer port }; - CandidatePortPrefixes=temp; - } - else if(osName.toLowerCase().indexOf("windows") != -1 ) + CandidatePortPrefixes = temp; + } else if (osName.equals("FreeBSD")) { + String[] temp = {"lpt"}; + CandidatePortPrefixes = temp; + } else if (osName.toLowerCase().indexOf("windows") != -1) { + String[] temp = {"LPT"}; + CandidatePortPrefixes = temp; + } else /* printer support is green */ { - String[] temp={ - "LPT" - }; - CandidatePortPrefixes=temp; - } - else /* printer support is green */ - { - String [] temp={}; - CandidatePortPrefixes=temp; + String[] temp = {}; + CandidatePortPrefixes = temp; } break; - default: - log.debug("Unknown PortType "+PortType+" passed to RXTXCommDriver.registerScannedPorts()"); + default : + log.debug("Unknown PortType " + PortType + " passed to RXTXCommDriver.registerScannedPorts()"); } registerValidPorts(CandidateDeviceNames, CandidatePortPrefixes, PortType, performTestRead); } - + /** - * @return an array containing the serial ports, taken from registry HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM - * @throws Exception in case something goes wrong with the registry + * @return an array containing the serial ports, taken from registry + * HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM + * @throws Exception + * in case something goes wrong with the registry */ private String[] windowsGetSerialPortsFromRegistry() throws Exception { - final TreeMap map = com.sun.jna.platform.win32.Advapi32Util.registryGetValues(com.sun.jna.platform.win32.WinReg.HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM"); - + final TreeMap map = com.sun.jna.platform.win32.Advapi32Util.registryGetValues( + com.sun.jna.platform.win32.WinReg.HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM"); + final List ports = new ArrayList(map.size()); for (Object p : map.values()) { if (p != null && p.toString().startsWith("COM")) @@ -878,58 +713,56 @@ private String[] windowsGetSerialPortsFromRegistry() throws Exception { /** * Function to test if a given class is currently present - * @param className The desired class name + * + * @param className + * The desired class name * @return true, if class found, false otherwise */ private static boolean isClassPresent(final String className) { - try { - Class.forName(className); - return true; - } catch (Throwable ex) { - // Class or one of its dependencies is not present... - return false; - } + try { + Class.forName(className); + return true; + } catch (Throwable ex) { + // Class or one of its dependencies is not present... + return false; + } } - + /* - * From the NullDriver.java CommAPI sample. + * From the NullDriver.java CommAPI sample. */ /** - * @param PortName The name of the port the OS recognizes - * @param PortType CommPortIdentifier.PORT_SERIAL or PORT_PARALLEL - * @return CommPort - * getCommPort() will be called by CommPortIdentifier from its - * openPort() method. PortName is a string that was registered earlier - * using the CommPortIdentifier.addPortName() method. getCommPort() - * returns an object that extends either SerialPort or ParallelPort. - */ - public CommPort getCommPort( String PortName, int PortType ) - { - log.trace("RXTXCommDriver:getCommPort("+PortName+","+PortType+")"); + * @param PortName + * The name of the port the OS recognizes + * @param PortType + * CommPortIdentifier.PORT_SERIAL or PORT_PARALLEL + * @return CommPort getCommPort() will be called by CommPortIdentifier from its + * openPort() method. PortName is a string that was registered earlier + * using the CommPortIdentifier.addPortName() method. getCommPort() + * returns an object that extends either SerialPort or ParallelPort. + */ + public CommPort getCommPort(String PortName, int PortType) { + log.trace("RXTXCommDriver:getCommPort(" + PortName + "," + PortType + ")"); try { switch (PortType) { - case CommPortIdentifier.PORT_SERIAL: - if(osName.toLowerCase().indexOf("windows") == -1 ) - { - - return new RXTXPort( PortName ); - } - else - { - return new RXTXPort( deviceDirectory + PortName ); + case CommPortIdentifier.PORT_SERIAL : + if (osName.toLowerCase().indexOf("windows") == -1) { + + return new RXTXPort(PortName); + } else { + return new RXTXPort(deviceDirectory + PortName); } - default: - log.debug("Unknown PortType "+PortType+" passed to RXTXCommDriver.getCommPort()"); + default : + log.debug("Unknown PortType " + PortType + " passed to RXTXCommDriver.getCommPort()"); } - } catch( PortInUseException e ) { - log.warn("Port "+PortName+" in use by another application"); + } catch (PortInUseException e) { + log.warn("Port " + PortName + " in use by another application"); } return null; } - /* Yikes. Trying to call println from C for odd reasons */ - public void Report( String arg ) - { + /* Yikes. Trying to call println from C for odd reasons */ + public void Report(String arg) { log.debug(arg); } } diff --git a/src/main/java/gnu/io/RXTXPort.java b/src/main/java/gnu/io/RXTXPort.java index 1ef2e7e5..e2a53807 100644 --- a/src/main/java/gnu/io/RXTXPort.java +++ b/src/main/java/gnu/io/RXTXPort.java @@ -56,137 +56,136 @@ | All trademarks belong to their respective owners. --------------------------------------------------------------------------*/ package gnu.io; + +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.IOException; import java.util.TooManyListenersException; -import java.lang.Math; import java.util.concurrent.*; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** -* An extension of gnu.io.SerialPort -* @see gnu.io.SerialPort -*/ + * An extension of gnu.io.SerialPort + * + * @see gnu.io.SerialPort + */ -public class RXTXPort extends SerialPort -{ +public class RXTXPort extends SerialPort { private static final Logger log = LoggerFactory.getLogger(RXTXPort.class); - /* I had a report that some JRE's complain when MonitorThread - tries to access private variables - */ + /* + * I had a report that some JRE's complain when MonitorThread tries to access + * private variables + */ /** */ - class MonitorThread extends Thread - { - /** Note: these have to be separate boolean flags because the - SerialPortEvent constants are NOT bit-flags, they are just - defined as integers from 1 to 10 -DPL */ - private volatile boolean CTS=false; - private volatile boolean DSR=false; - private volatile boolean RI=false; - private volatile boolean CD=false; - private volatile boolean OE=false; - private volatile boolean PE=false; - private volatile boolean FE=false; - private volatile boolean BI=false; - private volatile boolean Data=false; - private volatile boolean Output=false; - - /** - * run the thread and call the event loop. - */ - public void run() - { + class MonitorThread extends Thread { + /** + * Note: these have to be separate boolean flags because the SerialPortEvent + * constants are NOT bit-flags, they are just defined as integers from 1 to 10 + * -DPL + */ + private volatile boolean CTS = false; + private volatile boolean DSR = false; + private volatile boolean RI = false; + private volatile boolean CD = false; + private volatile boolean OE = false; + private volatile boolean PE = false; + private volatile boolean FE = false; + private volatile boolean BI = false; + private volatile boolean Data = false; + private volatile boolean Output = false; + + /** + * run the thread and call the event loop. + */ + public void run() { try { - log.trace( "RXTXPort:MonitorThread:run()"); - monThreadisInterrupted=false; + log.trace("RXTXPort:MonitorThread:run()"); + monThreadisInterrupted = false; eventLoop(); - eis = 0; - log.trace( "eventLoop() finished"); - }catch(Throwable ex) { - HARDWARE_FAULT=true; + eis = 0; + log.trace("eventLoop() finished"); + } catch (Throwable ex) { + HARDWARE_FAULT = true; sendEvent(SerialPortEvent.HARDWARE_ERROR, true); } } - protected void finalize() throws Throwable - { - log.trace( "RXTXPort:MonitorThread exiting"); + protected void finalize() throws Throwable { + log.trace("RXTXPort:MonitorThread exiting"); } } - protected boolean HARDWARE_FAULT=false; + protected boolean HARDWARE_FAULT = false; private static Zystem z; - static - { + static { try { z = new Zystem(Zystem.SILENT_MODE); - } catch ( Exception e ) {} + } catch (Exception e) { + } - log.trace( "RXTXPort {}"); - //System.loadLibrary( "rxtxSerial" ); + log.trace("RXTXPort {}"); + // System.loadLibrary( "rxtxSerial" ); SerialManager.getInstance(); - + Initialize(); } /** Initialize the native library */ private native static void Initialize(); - boolean MonitorThreadAlive=false; + boolean MonitorThreadAlive = false; - /** - * Open the named port - * @param name the name of the device to open - * PortInUseException - * @see gnu.io.SerialPort - */ - public RXTXPort( String name ) throws PortInUseException - { - log.trace( "RXTXPort:RXTXPort("+name+") called"); - /* - commapi/javadocs/API_users_guide.html specifies that whenever - an application tries to open a port in use by another application - the PortInUseException will be thrown - - I know some didnt like it this way but I'm not sure how to avoid - it. We will just be writing to a bogus fd if we catch the - exeption - - Trent - */ - // try { - fd = open( name ); - this.name = name; + /** + * Open the named port + * + * @param name + * the name of the device to open PortInUseException + * @see gnu.io.SerialPort + */ + public RXTXPort(String name) throws PortInUseException { + log.trace("RXTXPort:RXTXPort(" + name + ") called"); + /* + * commapi/javadocs/API_users_guide.html specifies that whenever an application + * tries to open a port in use by another application the PortInUseException + * will be thrown + * + * I know some didnt like it this way but I'm not sure how to avoid it. We will + * just be writing to a bogus fd if we catch the exeption + * + * Trent + */ + // try { + fd = open(name); + this.name = name; - MonitorThreadLock = true; - monThread = new MonitorThread(); - monThread.setName("RXTXPortMonitor("+name+")"); - monThread.start(); - waitForTheNativeCodeSilly(); - MonitorThreadAlive=true; - // } catch ( PortInUseException e ){} - timeout = -1; /* default disabled timeout */ - log.trace( "RXTXPort:RXTXPort("+name+") returns with fd = " + fd); + MonitorThreadLock = true; + monThread = new MonitorThread(); + monThread.setName("RXTXPortMonitor(" + name + ")"); + monThread.start(); + waitForTheNativeCodeSilly(); + MonitorThreadAlive = true; + // } catch ( PortInUseException e ){} + timeout = -1; /* default disabled timeout */ + log.trace("RXTXPort:RXTXPort(" + name + ") returns with fd = " + fd); } - private native synchronized int open( String name )throws PortInUseException; - + private native synchronized int open(String name) throws PortInUseException; /* dont close the file while accessing the fd */ - private final java.util.concurrent.locks.ReentrantReadWriteLock IOLockedMutex = new java.util.concurrent.locks.ReentrantReadWriteLock(true); + private final java.util.concurrent.locks.ReentrantReadWriteLock IOLockedMutex = new java.util.concurrent.locks.ReentrantReadWriteLock( + true); /** File descriptor */ private int fd = 0; - /** a pointer to the event info structure used to share information - between threads so write threads can send output buffer empty - from a pthread if need be. - - long for 64 bit pointers. - */ + /** + * a pointer to the event info structure used to share information between + * threads so write threads can send output buffer empty from a pthread if need + * be. + * + * long for 64 bit pointers. + */ long eis = 0; /** pid for lock files */ int pid = 0; @@ -196,403 +195,350 @@ public RXTXPort( String name ) throws PortInUseException /** Output stream */ private final SerialOutputStream out = new SerialOutputStream(); - /** - * get the OutputStream - * @return OutputStream - */ - public OutputStream getOutputStream() - { + /** + * get the OutputStream + * + * @return OutputStream + */ + public OutputStream getOutputStream() { return out; } /** Input stream */ private final SerialInputStream in = new SerialInputStream(); - /** - * get the InputStream - * @return InputStream - * @see java.io.InputStream - */ - public InputStream getInputStream() - { + /** + * get the InputStream + * + * @return InputStream + * @see java.io.InputStream + */ + public InputStream getInputStream() { return in; } - /** - * Set the SerialPort parameters - * 1.5 stop bits requires 5 databits - * @param b baudrate - * @param d databits - * @param s stopbits - * @param p parity - * UnsupportedCommOperationException - * @see gnu.io.UnsupportedCommOperationException - - * If speed is not a predifined speed it is assumed to be - * the actual speed desired. - */ - private native int nativeGetParity( int fd ); - private native int nativeGetFlowControlMode( int fd ); - public synchronized void setSerialPortParams( int b, int d, int s, - int p ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:setSerialPortParams(" + - b + " " + d + " " + s + " " + p + ") called"); - if ( nativeSetSerialPortParams( b, d, s, p ) ) - throw new UnsupportedCommOperationException( - "Invalid Parameter" ); + /** + * Set the SerialPort parameters 1.5 stop bits requires 5 databits + * + * @param b + * baudrate + * @param d + * databits + * @param s + * stopbits + * @param p + * parity UnsupportedCommOperationException + * @see gnu.io.UnsupportedCommOperationException + * + * If speed is not a predifined speed it is assumed to be the actual speed + * desired. + */ + private native int nativeGetParity(int fd); + private native int nativeGetFlowControlMode(int fd); + public synchronized void setSerialPortParams(int b, int d, int s, int p) throws UnsupportedCommOperationException { + log.trace("RXTXPort:setSerialPortParams(" + b + " " + d + " " + s + " " + p + ") called"); + if (nativeSetSerialPortParams(b, d, s, p)) + throw new UnsupportedCommOperationException("Invalid Parameter"); speed = b; - if( s== STOPBITS_1_5 ) dataBits = DATABITS_5; - else dataBits = d; + if (s == STOPBITS_1_5) + dataBits = DATABITS_5; + else + dataBits = d; stopBits = s; parity = p; - log.trace( "RXTXPort:setSerialPortParams(" + - b + " " + d + " " + s + " " + p + - ") returning"); + log.trace("RXTXPort:setSerialPortParams(" + b + " " + d + " " + s + " " + p + ") returning"); } /** - * Set the native serial port parameters - * If speed is not a predifined speed it is assumed to be - * the actual speed desired. - */ - private native boolean nativeSetSerialPortParams( int speed, - int dataBits, int stopBits, int parity ) - throws UnsupportedCommOperationException; + * Set the native serial port parameters If speed is not a predifined speed it + * is assumed to be the actual speed desired. + */ + private native boolean nativeSetSerialPortParams(int speed, int dataBits, int stopBits, int parity) + throws UnsupportedCommOperationException; /** Line speed in bits-per-second */ - private int speed=9600; - /** - * @return int representing the baudrate - * This will not behave as expected with custom speeds - */ - public int getBaudRate() - { + private int speed = 9600; + /** + * @return int representing the baudrate This will not behave as expected with + * custom speeds + */ + public int getBaudRate() { return speed; } /** Data bits port parameter */ - private int dataBits=DATABITS_8; - /** - * @return int representing the databits - */ - public int getDataBits() - { + private int dataBits = DATABITS_8; + /** + * @return int representing the databits + */ + public int getDataBits() { return dataBits; } /** Stop bits port parameter */ - private int stopBits=SerialPort.STOPBITS_1; - /** - * @return int representing the stopbits - */ - public int getStopBits() - { + private int stopBits = SerialPort.STOPBITS_1; + /** + * @return int representing the stopbits + */ + public int getStopBits() { return stopBits; } /** Parity port parameter */ - private int parity= SerialPort.PARITY_NONE; - /** - * @return int representing the parity - */ - public int getParity() - { + private int parity = SerialPort.PARITY_NONE; + /** + * @return int representing the parity + */ + public int getParity() { return parity; } - /** Flow control */ private int flowmode = SerialPort.FLOWCONTROL_NONE; - /** - * @param flowcontrol FLOWCONTROL_NONE is default - * @see gnu.io.SerialPort#FLOWCONTROL_NONE - */ - public void setFlowControlMode( int flowcontrol ) - { - log.trace( "RXTXPort:setFlowControlMode( " + flowcontrol + " ) called"); - if(monThreadisInterrupted) - { - log.trace( "RXTXPort:setFlowControlMode MonThread was interrupted" ); + /** + * @param flowcontrol + * FLOWCONTROL_NONE is default + * @see gnu.io.SerialPort#FLOWCONTROL_NONE + */ + public void setFlowControlMode(int flowcontrol) { + log.trace("RXTXPort:setFlowControlMode( " + flowcontrol + " ) called"); + if (monThreadisInterrupted) { + log.trace("RXTXPort:setFlowControlMode MonThread was interrupted"); return; } try { - setflowcontrol( flowcontrol ); - } - catch( IOException e ) - { + setflowcontrol(flowcontrol); + } catch (IOException e) { e.printStackTrace(); return; } - flowmode=flowcontrol; - log.trace( "RXTXPort:setFlowControlMode( " + flowcontrol + " ) returning"); + flowmode = flowcontrol; + log.trace("RXTXPort:setFlowControlMode( " + flowcontrol + " ) returning"); } - /** - * @return int representing the flowmode - */ - public int getFlowControlMode() - { + /** + * @return int representing the flowmode + */ + public int getFlowControlMode() { return flowmode; } - native void setflowcontrol( int flowcontrol ) throws IOException; - + native void setflowcontrol(int flowcontrol) throws IOException; /* - linux/drivers/char/n_hdlc.c? FIXME - taj@www.linux.org.uk - */ + * linux/drivers/char/n_hdlc.c? FIXME taj@www.linux.org.uk + */ /** - * Receive framing control - * @param f framming - * UnsupportedCommOperationException - */ - public void enableReceiveFraming( int f ) - throws UnsupportedCommOperationException - { - throw new UnsupportedCommOperationException( "Not supported" ); + * Receive framing control + * + * @param f + * framming UnsupportedCommOperationException + */ + public void enableReceiveFraming(int f) throws UnsupportedCommOperationException { + throw new UnsupportedCommOperationException("Not supported"); } /** */ - public void disableReceiveFraming() - { - log.trace( "RXTXPort:disableReceiveFramming() called and returning (noop)"); + public void disableReceiveFraming() { + log.trace("RXTXPort:disableReceiveFramming() called and returning (noop)"); } - /** - * @return true if framing is enabled - */ - public boolean isReceiveFramingEnabled() - { + /** + * @return true if framing is enabled + */ + public boolean isReceiveFramingEnabled() { return false; } - /** - * @return int representing the framing byte - */ - public int getReceiveFramingByte() - { + /** + * @return int representing the framing byte + */ + public int getReceiveFramingByte() { return 0; } - /** Receive timeout control */ private int timeout; - /** - * @return int the timeout - */ + /** + * @return int the timeout + */ public native int NativegetReceiveTimeout(); - /** - * @return bloolean true if recieve timeout is enabled - */ + /** + * @return bloolean true if recieve timeout is enabled + */ private native boolean NativeisReceiveTimeoutEnabled(); - /** - * @param time - * @param threshold - * @param InputBuffer - */ - private native void NativeEnableReceiveTimeoutThreshold(int time, - int threshold,int InputBuffer); + /** + * @param time + * @param threshold + * @param InputBuffer + */ + private native void NativeEnableReceiveTimeoutThreshold(int time, int threshold, int InputBuffer); /** */ - public void disableReceiveTimeout() - { - log.trace( "RXTXPort:disableReceiveTimeout() called"); + public void disableReceiveTimeout() { + log.trace("RXTXPort:disableReceiveTimeout() called"); timeout = -1; - NativeEnableReceiveTimeoutThreshold( timeout , threshold, InputBuffer ); - log.trace( "RXTXPort:disableReceiveTimeout() returning"); + NativeEnableReceiveTimeoutThreshold(timeout, threshold, InputBuffer); + log.trace("RXTXPort:disableReceiveTimeout() returning"); } - /** - * @param time - */ - public void enableReceiveTimeout( int time ) - { - //log.trace("Enabling receive timeout: "+time); - log.trace( "RXTXPort:enableReceiveTimeout() called"); - if( time >= 0 ) - { + /** + * @param time + */ + public void enableReceiveTimeout(int time) { + // log.trace("Enabling receive timeout: "+time); + log.trace("RXTXPort:enableReceiveTimeout() called"); + if (time >= 0) { timeout = time; - NativeEnableReceiveTimeoutThreshold( time , threshold, - InputBuffer ); - } - else - { - throw new IllegalArgumentException - ( - "Unexpected negative timeout value" - ); + NativeEnableReceiveTimeoutThreshold(time, threshold, InputBuffer); + } else { + throw new IllegalArgumentException("Unexpected negative timeout value"); } - log.trace( "RXTXPort:enableReceiveTimeout() returning"); + log.trace("RXTXPort:enableReceiveTimeout() returning"); } - /** - * @return boolean true if recieve timeout is enabled - */ - public boolean isReceiveTimeoutEnabled() - { - return( NativeisReceiveTimeoutEnabled() ); + /** + * @return boolean true if recieve timeout is enabled + */ + public boolean isReceiveTimeoutEnabled() { + return (NativeisReceiveTimeoutEnabled()); } - /** - * @return int the timeout - */ - public int getReceiveTimeout() - { - return(NativegetReceiveTimeout( )); + /** + * @return int the timeout + */ + public int getReceiveTimeout() { + return (NativegetReceiveTimeout()); } /** Receive threshold control */ private int threshold = 0; - /** - * @param thresh threshold - */ - public void enableReceiveThreshold( int thresh ) - { - log.trace( "RXTXPort:enableReceiveThreshold( " + thresh + " ) called"); - if(thresh >=0) - { - threshold=thresh; - NativeEnableReceiveTimeoutThreshold(timeout, threshold, - InputBuffer); - } - else /* invalid thresh */ + /** + * @param thresh + * threshold + */ + public void enableReceiveThreshold(int thresh) { + log.trace("RXTXPort:enableReceiveThreshold( " + thresh + " ) called"); + if (thresh >= 0) { + threshold = thresh; + NativeEnableReceiveTimeoutThreshold(timeout, threshold, InputBuffer); + } else /* invalid thresh */ { - throw new IllegalArgumentException - ( - "Unexpected negative threshold value" - ); + throw new IllegalArgumentException("Unexpected negative threshold value"); } - log.trace( "RXTXPort:enableReceiveThreshold( " + thresh + " ) returned"); + log.trace("RXTXPort:enableReceiveThreshold( " + thresh + " ) returned"); } /** */ - public void disableReceiveThreshold() - { + public void disableReceiveThreshold() { enableReceiveThreshold(0); } - /** - * @return int the recieve threshold - */ - public int getReceiveThreshold() - { + /** + * @return int the recieve threshold + */ + public int getReceiveThreshold() { return threshold; } - /** - * @return boolean true if receive threshold is enabled - */ - public boolean isReceiveThresholdEnabled() - { - return(threshold>0); + /** + * @return boolean true if receive threshold is enabled + */ + public boolean isReceiveThresholdEnabled() { + return (threshold > 0); } /** Input/output buffers */ - /** FIXME I think this refers to - FOPEN(3)/SETBUF(3)/FREAD(3)/FCLOSE(3) - taj@www.linux.org.uk - - These are native stubs... - */ - private int InputBuffer=0; - private int OutputBuffer=0; - /** - * @param size - */ - public void setInputBufferSize( int size ) - { - log.trace( "RXTXPort:setInputBufferSize( " + size + ") called"); - if( size < 0 ) - throw new IllegalArgumentException - ( - "Unexpected negative buffer size value" - ); - else InputBuffer=size; - log.trace( "RXTXPort:setInputBufferSize( " + size + ") returning"); + /** + * FIXME I think this refers to FOPEN(3)/SETBUF(3)/FREAD(3)/FCLOSE(3) + * taj@www.linux.org.uk + * + * These are native stubs... + */ + private int InputBuffer = 0; + private int OutputBuffer = 0; + /** + * @param size + */ + public void setInputBufferSize(int size) { + log.trace("RXTXPort:setInputBufferSize( " + size + ") called"); + if (size < 0) + throw new IllegalArgumentException("Unexpected negative buffer size value"); + else + InputBuffer = size; + log.trace("RXTXPort:setInputBufferSize( " + size + ") returning"); } /** */ - public int getInputBufferSize() - { - return(InputBuffer); + public int getInputBufferSize() { + return (InputBuffer); } - /** - * @param size - */ - public void setOutputBufferSize( int size ) - { - log.trace( "RXTXPort:setOutputBufferSize( " + size + ") called"); - if( size < 0 ) - throw new IllegalArgumentException - ( - "Unexpected negative buffer size value" - ); - else OutputBuffer=size; - log.trace( "RXTXPort:setOutputBufferSize( " + size + ") returned"); - + /** + * @param size + */ + public void setOutputBufferSize(int size) { + log.trace("RXTXPort:setOutputBufferSize( " + size + ") called"); + if (size < 0) + throw new IllegalArgumentException("Unexpected negative buffer size value"); + else + OutputBuffer = size; + log.trace("RXTXPort:setOutputBufferSize( " + size + ") returned"); + } - /** - * @return in the output buffer size - */ - public int getOutputBufferSize() - { - return(OutputBuffer); + /** + * @return in the output buffer size + */ + public int getOutputBufferSize() { + return (OutputBuffer); } /* =================== cleaned messages to here */ /** - * Line status methods - */ + * Line status methods + */ /** - * @return true if DTR is set - */ + * @return true if DTR is set + */ public native boolean isDTR(); - /** - * @param state - */ - public native void setDTR( boolean state ); - /** - * @param state - */ - public native void setRTS( boolean state ); - private native void setDSR( boolean state ); - /** - * @return boolean true if CTS is set - */ + /** + * @param state + */ + public native void setDTR(boolean state); + /** + * @param state + */ + public native void setRTS(boolean state); + private native void setDSR(boolean state); + /** + * @return boolean true if CTS is set + */ public native boolean isCTS(); - /** - * @return boolean true if DSR is set - */ + /** + * @return boolean true if DSR is set + */ public native boolean isDSR(); - /** - * @return boolean true if CD is set - */ + /** + * @return boolean true if CD is set + */ public native boolean isCD(); - /** - * @return boolean true if RI is set - */ + /** + * @return boolean true if RI is set + */ public native boolean isRI(); - /** - * @return boolean true if RTS is set - */ + /** + * @return boolean true if RTS is set + */ public native boolean isRTS(); - /** - * Write to the port - * @param duration - */ - public native void sendBreak( int duration ); - protected native void writeByte( int b, boolean i ) throws IOException; - protected native void writeArray( byte b[], int off, int len, boolean i ) - throws IOException; - protected native boolean nativeDrain( boolean i ) throws IOException; + * Write to the port + * + * @param duration + */ + public native void sendBreak(int duration); + protected native void writeByte(int b, boolean i) throws IOException; + protected native void writeArray(byte b[], int off, int len, boolean i) throws IOException; + protected native boolean nativeDrain(boolean i) throws IOException; /** RXTXPort read methods */ protected native int nativeavailable() throws IOException; protected native int readByte() throws IOException; - protected native int readArray( byte b[], int off, int len ) - throws IOException; - protected native int readTerminatedArray( byte b[], int off, int len, byte t[] ) - throws IOException; - + protected native int readArray(byte b[], int off, int len) throws IOException; + protected native int readTerminatedArray(byte b[], int off, int len, byte t[]) throws IOException; /** Serial Port Event listener */ private SerialPortEventListener SPEventListener; @@ -603,443 +549,411 @@ protected native int readTerminatedArray( byte b[], int off, int len, byte t[] ) /** Process SerialPortEvents */ native void eventLoop(); - /** - * @return boolean true if monitor thread is interrupted - */ - boolean monThreadisInterrupted=true; - private native void interruptEventLoop( ); - public boolean checkMonitorThread() - { - log.trace( "RXTXPort:checkMonitorThread()"); - if(monThread != null) - { - log.trace( "monThreadisInterrupted = " + monThreadisInterrupted ); + /** + * @return boolean true if monitor thread is interrupted + */ + boolean monThreadisInterrupted = true; + private native void interruptEventLoop(); + public boolean checkMonitorThread() { + log.trace("RXTXPort:checkMonitorThread()"); + if (monThread != null) { + log.trace("monThreadisInterrupted = " + monThreadisInterrupted); return monThreadisInterrupted; } - log.trace( "monThread is null " ); - return(true); + log.trace("monThread is null "); + return (true); } - /** - * @param event - * @param state - * @return boolean true if the port is closing - */ - public boolean sendEvent( int event, boolean state ) - { + /** + * @param event + * @param state + * @return boolean true if the port is closing + */ + public boolean sendEvent(int event, boolean state) { /* Let the native side know its time to die */ - if ( fd == 0 || SPEventListener == null || monThread == null) - { - return(true); + if (fd == 0 || SPEventListener == null || monThread == null) { + return (true); } - switch( event ) - { - case SerialPortEvent.HARDWARE_ERROR: - log.warn( "RXTXPort:sendEvent: HARDWARE_ERROR " + - monThread.Data + ")" ); - break; - case SerialPortEvent.DATA_AVAILABLE: - log.trace( "RXTXPort:sendEvent: DATA_AVAILABLE " + monThread.Data); + switch (event) { + case SerialPortEvent.HARDWARE_ERROR : + log.warn("RXTXPort:sendEvent: HARDWARE_ERROR " + monThread.Data + ")"); + break; + case SerialPortEvent.DATA_AVAILABLE : + log.trace("RXTXPort:sendEvent: DATA_AVAILABLE " + monThread.Data); break; - case SerialPortEvent.OUTPUT_BUFFER_EMPTY: - log.trace( "RXTXPort:sendEvent: OUTPUT_BUFFER_EMPTY " + monThread.Output); + case SerialPortEvent.OUTPUT_BUFFER_EMPTY : + log.trace("RXTXPort:sendEvent: OUTPUT_BUFFER_EMPTY " + monThread.Output); break; - case SerialPortEvent.CTS: - log.trace( "RXTXPort:sendEvent: CTS " + monThread.CTS); + case SerialPortEvent.CTS : + log.trace("RXTXPort:sendEvent: CTS " + monThread.CTS); break; - case SerialPortEvent.DSR: - log.trace( "RXTXPort:sendEvent: DSR " + monThread.Output); + case SerialPortEvent.DSR : + log.trace("RXTXPort:sendEvent: DSR " + monThread.Output); break; - case SerialPortEvent.RI: - log.trace( "RXTXPort:sendEvent: RI " + monThread.RI); + case SerialPortEvent.RI : + log.trace("RXTXPort:sendEvent: RI " + monThread.RI); break; - case SerialPortEvent.CD: - log.trace( "RXTXPort:sendEvent: CD " + monThread.CD); + case SerialPortEvent.CD : + log.trace("RXTXPort:sendEvent: CD " + monThread.CD); break; - case SerialPortEvent.OE: - log.trace( "RXTXPort:sendEvent: OE " + monThread.OE); + case SerialPortEvent.OE : + log.trace("RXTXPort:sendEvent: OE " + monThread.OE); break; - case SerialPortEvent.PE: - log.trace( "RXTXPort:sendEvent: PE " + monThread.PE); + case SerialPortEvent.PE : + log.trace("RXTXPort:sendEvent: PE " + monThread.PE); break; - case SerialPortEvent.FE: - log.trace( "RXTXPort:sendEvent: FE " + monThread.FE); + case SerialPortEvent.FE : + log.trace("RXTXPort:sendEvent: FE " + monThread.FE); break; - case SerialPortEvent.BI: - log.trace( "RXTXPort:sendEvent: BI " + monThread.BI); + case SerialPortEvent.BI : + log.trace("RXTXPort:sendEvent: BI " + monThread.BI); break; - default: - log.debug( "RXTXPort:sendEvent: " + event); + default : + log.debug("RXTXPort:sendEvent: " + event); break; } - switch( event ) - { - case SerialPortEvent.DATA_AVAILABLE: - if( monThread.Data ) break; - return(false); - case SerialPortEvent.OUTPUT_BUFFER_EMPTY: - if( monThread.Output ) break; - return(false); - case SerialPortEvent.CTS: - if( monThread.CTS ) break; - return(false); - case SerialPortEvent.DSR: - if( monThread.DSR ) break; - return(false); - case SerialPortEvent.RI: - if( monThread.RI ) break; - return(false); - case SerialPortEvent.CD: - if( monThread.CD ) break; - return(false); - case SerialPortEvent.OE: - if( monThread.OE ) break; - return(false); - case SerialPortEvent.PE: - if( monThread.PE ) break; - return(false); - case SerialPortEvent.FE: - if( monThread.FE ) break; - return(false); - case SerialPortEvent.BI: - if( monThread.BI ) break; - return(false); - case SerialPortEvent.HARDWARE_ERROR: + switch (event) { + case SerialPortEvent.DATA_AVAILABLE : + if (monThread.Data) + break; + return (false); + case SerialPortEvent.OUTPUT_BUFFER_EMPTY : + if (monThread.Output) + break; + return (false); + case SerialPortEvent.CTS : + if (monThread.CTS) + break; + return (false); + case SerialPortEvent.DSR : + if (monThread.DSR) + break; + return (false); + case SerialPortEvent.RI : + if (monThread.RI) + break; + return (false); + case SerialPortEvent.CD : + if (monThread.CD) + break; + return (false); + case SerialPortEvent.OE : + if (monThread.OE) + break; + return (false); + case SerialPortEvent.PE : + if (monThread.PE) + break; + return (false); + case SerialPortEvent.FE : + if (monThread.FE) + break; + return (false); + case SerialPortEvent.BI : + if (monThread.BI) + break; + return (false); + case SerialPortEvent.HARDWARE_ERROR : break; - default: - return(false); + default : + return (false); } - SerialPortEvent e = new SerialPortEvent(this, event, !state, - state ); - if(monThreadisInterrupted) - { - return(true); + SerialPortEvent e = new SerialPortEvent(this, event, !state, state); + if (monThreadisInterrupted) { + return (true); } - if( SPEventListener != null ) - { - SPEventListener.serialEvent( e ); + if (SPEventListener != null) { + SPEventListener.serialEvent(e); } - if (fd == 0 || SPEventListener == null || monThread == null) - { - return(true); - } - else - { - return(false); + if (fd == 0 || SPEventListener == null || monThread == null) { + return (true); + } else { + return (false); } } /** - * Add an event listener - * @param lsnr SerialPortEventListener - * TooManyListenersException - */ + * Add an event listener + * + * @param lsnr + * SerialPortEventListener TooManyListenersException + */ boolean MonitorThreadLock = true; - public void addEventListener( - SerialPortEventListener lsnr ) throws TooManyListenersException - { - /* Don't let and notification requests happen until the - Eventloop is ready - */ + public void addEventListener(SerialPortEventListener lsnr) throws TooManyListenersException { + /* + * Don't let and notification requests happen until the Eventloop is ready + */ - log.trace( "RXTXPort:addEventListener()"); - if( SPEventListener != null ) - { + log.trace("RXTXPort:addEventListener()"); + if (SPEventListener != null) { throw new TooManyListenersException(); } SPEventListener = lsnr; - if( !MonitorThreadAlive ) - { + if (!MonitorThreadAlive) { MonitorThreadLock = true; monThread = new MonitorThread(); - monThread.setName("RXTXPortMonitor("+name+")"); + monThread.setName("RXTXPortMonitor(" + name + ")"); monThread.start(); waitForTheNativeCodeSilly(); - MonitorThreadAlive=true; + MonitorThreadAlive = true; } - log.trace( "RXTXPort:Interrupt=false"); + log.trace("RXTXPort:Interrupt=false"); } /** - * Remove the serial port event listener - */ - public void removeEventListener() - { - log.trace( "RXTXPort:removeEventListener() called"); + * Remove the serial port event listener + */ + public void removeEventListener() { + log.trace("RXTXPort:removeEventListener() called"); waitForTheNativeCodeSilly(); - //if( monThread != null && monThread.isAlive() ) - if( monThreadisInterrupted == true ) - { - log.debug( " RXTXPort:removeEventListener() already interrupted"); + // if( monThread != null && monThread.isAlive() ) + if (monThreadisInterrupted == true) { + log.debug(" RXTXPort:removeEventListener() already interrupted"); monThread = null; SPEventListener = null; return; - } - else if( monThread != null && monThread.isAlive() && !HARDWARE_FAULT) - { - log.trace( " RXTXPort:Interrupt=true"); - monThreadisInterrupted=true; + } else if (monThread != null && monThread.isAlive() && !HARDWARE_FAULT) { + log.trace(" RXTXPort:Interrupt=true"); + monThreadisInterrupted = true; /* - Notify all threads in this PID that something is up - They will call back to see if its their thread - using isInterrupted(). - */ - log.trace( " RXTXPort:calling interruptEventLoop"); - interruptEventLoop( ); - - log.trace( " RXTXPort:calling monThread.join()"); + * Notify all threads in this PID that something is up They will call back to + * see if its their thread using isInterrupted(). + */ + log.trace(" RXTXPort:calling interruptEventLoop"); + interruptEventLoop(); + + log.trace(" RXTXPort:calling monThread.join()"); try { // wait a reasonable moment for the death of the monitor thread monThread.join(3000); } catch (InterruptedException ex) { // somebody called interrupt() on us (ie wants us to abort) - // we dont propagate InterruptedExceptions so lets re-set the flag + // we dont propagate InterruptedExceptions so lets re-set the flag Thread.currentThread().interrupt(); return; - } - + } + if (monThread.isAlive()) { - log.warn( "Failed to cancel monitor thread"); + log.warn("Failed to cancel monitor thread"); } - + } monThread = null; SPEventListener = null; MonitorThreadLock = false; - MonitorThreadAlive=false; - monThreadisInterrupted=true; - log.trace( "RXTXPort:removeEventListener() returning"); + MonitorThreadAlive = false; + monThreadisInterrupted = true; + log.trace("RXTXPort:removeEventListener() returning"); } /** - * Give the native code a chance to start listening to the hardware - * or should we say give the native code control of the issue. + * Give the native code a chance to start listening to the hardware or should we + * say give the native code control of the issue. * - * This is important for applications that flicker the Monitor - * thread while keeping the port open. - * In worst case test cases this loops once or twice every time. + * This is important for applications that flicker the Monitor thread while + * keeping the port open. In worst case test cases this loops once or twice + * every time. */ - protected void waitForTheNativeCodeSilly() - { - while( MonitorThreadLock ) - { + protected void waitForTheNativeCodeSilly() { + while (MonitorThreadLock) { try { Thread.sleep(5); - } catch( Exception e ) {} + } catch (Exception e) { + } } } /** - * @param enable - */ - private native void nativeSetEventFlag( int fd, int event, - boolean flag ); - public void notifyOnDataAvailable( boolean enable ) - { + * @param enable + */ + private native void nativeSetEventFlag(int fd, int event, boolean flag); + public void notifyOnDataAvailable(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.DATA_AVAILABLE, - enable ); + nativeSetEventFlag(fd, SerialPortEvent.DATA_AVAILABLE, enable); monThread.Data = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnOutputEmpty( boolean enable ) - { + * @param enable + */ + public void notifyOnOutputEmpty(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.OUTPUT_BUFFER_EMPTY, - enable ); + nativeSetEventFlag(fd, SerialPortEvent.OUTPUT_BUFFER_EMPTY, enable); monThread.Output = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnCTS( boolean enable ) - { + * @param enable + */ + public void notifyOnCTS(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.CTS, enable ); + nativeSetEventFlag(fd, SerialPortEvent.CTS, enable); monThread.CTS = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnDSR( boolean enable ) - { + * @param enable + */ + public void notifyOnDSR(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.DSR, enable ); + nativeSetEventFlag(fd, SerialPortEvent.DSR, enable); monThread.DSR = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnRingIndicator( boolean enable ) - { + * @param enable + */ + public void notifyOnRingIndicator(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.RI, enable ); + nativeSetEventFlag(fd, SerialPortEvent.RI, enable); monThread.RI = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnCarrierDetect( boolean enable ) - { + * @param enable + */ + public void notifyOnCarrierDetect(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.CD, enable ); + nativeSetEventFlag(fd, SerialPortEvent.CD, enable); monThread.CD = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnOverrunError( boolean enable ) - { + * @param enable + */ + public void notifyOnOverrunError(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.OE, enable ); + nativeSetEventFlag(fd, SerialPortEvent.OE, enable); monThread.OE = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnParityError( boolean enable ) - { + * @param enable + */ + public void notifyOnParityError(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.PE, enable ); + nativeSetEventFlag(fd, SerialPortEvent.PE, enable); monThread.PE = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnFramingError( boolean enable ) - { + * @param enable + */ + public void notifyOnFramingError(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.FE, enable ); + nativeSetEventFlag(fd, SerialPortEvent.FE, enable); monThread.FE = enable; MonitorThreadLock = false; } /** - * @param enable - */ - public void notifyOnBreakInterrupt( boolean enable ) - { + * @param enable + */ + public void notifyOnBreakInterrupt(boolean enable) { waitForTheNativeCodeSilly(); MonitorThreadLock = true; - nativeSetEventFlag( fd, SerialPortEvent.BI, enable ); + nativeSetEventFlag(fd, SerialPortEvent.BI, enable); monThread.BI = enable; MonitorThreadLock = false; } /** Close the port */ - private native void nativeClose( String name ); - - public void close() - { - log.trace( "RXTXPort:close( " + this.name + " )"); - log.debug("Closing port: {}", name); - - try { - while( !IOLockedMutex.writeLock().tryLock(500, TimeUnit.MILLISECONDS) ) - { - log.debug("IO is locked " + IOLockedMutex.getReadLockCount()); - } - - if ( fd <= 0 ) - { - log.debug( "RXTXPort:close detected bad File Descriptor" ); - return; - } - disableRs485(); - if(!HARDWARE_FAULT) setDTR(false); - if(!HARDWARE_FAULT) setDSR(false); - log.trace( "RXTXPort:close( " + this.name + " ) setting monThreadisInterrupted"); - if ( ! monThreadisInterrupted ) - { - removeEventListener(); - } - log.trace( "RXTXPort:close( " + this.name + " ) calling nativeClose"); - nativeClose( this.name ); - log.trace( "RXTXPort:close( " + this.name + " ) calling super.close"); - super.close(); - fd = 0; - log.trace( "RXTXPort:close( " + this.name + " ) leaving"); - } catch( InterruptedException ie ) { - // somebody called interrupt() on us - // we obey and return without closing the socket - Thread.currentThread().interrupt(); - return; - } - finally - { - if (IOLockedMutex.writeLock().isHeldByCurrentThread()) { - IOLockedMutex.writeLock().unlock(); - } - log.debug("Closed port: {}", name); - } + private native void nativeClose(String name); - } + public void close() { + log.trace("RXTXPort:close( " + this.name + " )"); + log.debug("Closing port: {}", name); + + try { + while (!IOLockedMutex.writeLock().tryLock(500, TimeUnit.MILLISECONDS)) { + log.debug("IO is locked " + IOLockedMutex.getReadLockCount()); + } + + if (fd <= 0) { + log.debug("RXTXPort:close detected bad File Descriptor"); + return; + } + disableRs485(); + if (!HARDWARE_FAULT) + setDTR(false); + if (!HARDWARE_FAULT) + setDSR(false); + log.trace("RXTXPort:close( " + this.name + " ) setting monThreadisInterrupted"); + if (!monThreadisInterrupted) { + removeEventListener(); + } + log.trace("RXTXPort:close( " + this.name + " ) calling nativeClose"); + nativeClose(this.name); + log.trace("RXTXPort:close( " + this.name + " ) calling super.close"); + super.close(); + fd = 0; + log.trace("RXTXPort:close( " + this.name + " ) leaving"); + } catch (InterruptedException ie) { + // somebody called interrupt() on us + // we obey and return without closing the socket + Thread.currentThread().interrupt(); + return; + } finally { + if (IOLockedMutex.writeLock().isHeldByCurrentThread()) { + IOLockedMutex.writeLock().unlock(); + } + log.debug("Closed port: {}", name); + } + } /** Finalize the port */ - protected void finalize() - { - log.trace( "RXTXPort:finalize()"); - if( fd > 0 ) - { - log.trace( "RXTXPort:calling close()"); + protected void finalize() { + log.trace("RXTXPort:finalize()"); + if (fd > 0) { + log.trace("RXTXPort:calling close()"); close(); } z.finalize(); } private String getParityAsString() { - switch(parity) { - case PARITY_NONE: + switch (parity) { + case PARITY_NONE : return "N"; - case PARITY_ODD: + case PARITY_ODD : return "O"; - case PARITY_EVEN: + case PARITY_EVEN : return "E"; - case PARITY_MARK: + case PARITY_MARK : return "M"; - case PARITY_SPACE: + case PARITY_SPACE : return "S"; - default: + default : return "?"; } } private String getStopBitsAsString() { - switch(stopBits) { - case STOPBITS_1: + switch (stopBits) { + case STOPBITS_1 : return "1"; - case STOPBITS_1_5: + case STOPBITS_1_5 : return "1.5"; - case STOPBITS_2: + case STOPBITS_2 : return "2"; - default: + default : return "?"; } } @@ -1050,238 +964,205 @@ public String toString() { } /** Inner class for SerialOutputStream */ - class SerialOutputStream extends OutputStream - { - /** - * @param b - * IOException - */ - public void write( int b ) throws IOException - { - log.trace( "RXTXPort:SerialOutputStream:write(int)"); - if( speed == 0 ) return; - if ( monThreadisInterrupted == true ) - { + class SerialOutputStream extends OutputStream { + /** + * @param b + * IOException + */ + public void write(int b) throws IOException { + log.trace("RXTXPort:SerialOutputStream:write(int)"); + if (speed == 0) + return; + if (monThreadisInterrupted == true) { return; } IOLockedMutex.readLock().lock(); try { waitForTheNativeCodeSilly(); - if ( fd == 0 ) - { + if (fd == 0) { log.error("File Descriptor for prot zero!!"); throw new IOException(); } - writeByte( b, monThreadisInterrupted ); - log.trace( "Leaving RXTXPort:SerialOutputStream:write( int )"); + writeByte(b, monThreadisInterrupted); + log.trace("Leaving RXTXPort:SerialOutputStream:write( int )"); } finally { IOLockedMutex.readLock().unlock(); } } - /** - * @param b[] - * IOException - */ - public void write( byte b[] ) throws IOException - { - log.trace( "Entering RXTXPort:SerialOutputStream:write(" + b.length + ") "/* + new String(b)*/ ); - if( speed == 0 ) return; - if ( monThreadisInterrupted == true ) - { + /** + * @param b[] + * IOException + */ + public void write(byte b[]) throws IOException { + log.trace("Entering RXTXPort:SerialOutputStream:write(" + b.length + ") "/* + new String(b) */ ); + if (speed == 0) + return; + if (monThreadisInterrupted == true) { return; } - if ( fd == 0 ) throw new IOException(); + if (fd == 0) + throw new IOException(); IOLockedMutex.readLock().lock(); try { waitForTheNativeCodeSilly(); - writeArray( b, 0, b.length, monThreadisInterrupted ); - log.trace( "Leaving RXTXPort:SerialOutputStream:write(" +b.length +")"); + writeArray(b, 0, b.length, monThreadisInterrupted); + log.trace("Leaving RXTXPort:SerialOutputStream:write(" + b.length + ")"); } finally { IOLockedMutex.readLock().unlock(); } - + } - /** - * @param b[] - * @param off - * @param len - * IOException - */ - public void write( byte b[], int off, int len ) - throws IOException - { - if( speed == 0 ) return; - if( off + len > b.length ) - { - throw new IndexOutOfBoundsException( - "Invalid offset/length passed to read" - ); + /** + * @param b[] + * @param off + * @param len + * IOException + */ + public void write(byte b[], int off, int len) throws IOException { + if (speed == 0) + return; + if (off + len > b.length) { + throw new IndexOutOfBoundsException("Invalid offset/length passed to read"); } - + byte send[] = new byte[len]; - System.arraycopy( b, off, send, 0, len ); - log.trace( "Entering RXTXPort:SerialOutputStream:write(" + send.length + " " + off + " " + len + " " +") " /*+ new String(send) */ ); - if ( fd == 0 ) throw new IOException(); - if ( monThreadisInterrupted == true ) - { + System.arraycopy(b, off, send, 0, len); + log.trace("Entering RXTXPort:SerialOutputStream:write(" + send.length + " " + off + " " + len + " " + + ") " /* + new String(send) */ ); + if (fd == 0) + throw new IOException(); + if (monThreadisInterrupted == true) { return; } IOLockedMutex.readLock().lock(); - try - { + try { waitForTheNativeCodeSilly(); - writeArray( send, 0, len, monThreadisInterrupted ); - log.trace( "Leaving RXTXPort:SerialOutputStream:write(" + send.length + " " + off + " " + len + " " +") " /*+ new String(send)*/ ); + writeArray(send, 0, len, monThreadisInterrupted); + log.trace("Leaving RXTXPort:SerialOutputStream:write(" + send.length + " " + off + " " + len + " " + + ") " /* + new String(send) */ ); } finally { IOLockedMutex.readLock().unlock(); } } - /** - */ - public void flush() throws IOException - { - log.trace( "RXTXPort:SerialOutputStream:flush() enter"); - if( speed == 0 ) return; - if ( fd == 0 ) throw new IOException(); - if ( monThreadisInterrupted == true ) - { - log.trace( "RXTXPort:SerialOutputStream:flush() Leaving Interrupted"); + /** + */ + public void flush() throws IOException { + log.trace("RXTXPort:SerialOutputStream:flush() enter"); + if (speed == 0) + return; + if (fd == 0) + throw new IOException(); + if (monThreadisInterrupted == true) { + log.trace("RXTXPort:SerialOutputStream:flush() Leaving Interrupted"); return; } IOLockedMutex.readLock().lock(); - try - { + try { waitForTheNativeCodeSilly(); - /* - this is probably good on all OS's but for now - just sendEvent from java on Sol - */ - if ( nativeDrain( monThreadisInterrupted ) ) - sendEvent( SerialPortEvent.OUTPUT_BUFFER_EMPTY, true ); - log.trace( "RXTXPort:SerialOutputStream:flush() leave"); - } - finally - { + /* + * this is probably good on all OS's but for now just sendEvent from java on Sol + */ + if (nativeDrain(monThreadisInterrupted)) + sendEvent(SerialPortEvent.OUTPUT_BUFFER_EMPTY, true); + log.trace("RXTXPort:SerialOutputStream:flush() leave"); + } finally { IOLockedMutex.readLock().unlock(); } } } /** Inner class for SerialInputStream */ - class SerialInputStream extends InputStream - { - /** - * @return int the int read - * IOException - * @see java.io.InputStream -* -*timeout threshold Behavior -*------------------------------------------------------------------------ -*0 0 blocks until 1 byte is available timeout > 0, -* threshold = 0, blocks until timeout occurs, returns -1 -* on timeout -*>0 >0 blocks until timeout, returns - 1 on timeout, magnitude -* of threshold doesn't play a role. -*0 >0 Blocks until 1 byte, magnitude of threshold doesn't -* play a role - */ - public synchronized int read() throws IOException - { - if ( fd == 0 ) throw new IOException(); - if ( monThreadisInterrupted ) - { - log.debug( "read(): monThreadisInterrupted" ); + class SerialInputStream extends InputStream { + /** + * @return int the int read IOException + * @see java.io.InputStream + * + * timeout threshold Behavior + * ------------------------------------------------------------------------ + * 0 0 blocks until 1 byte is available timeout > 0, threshold = 0, blocks + * until timeout occurs, returns -1 on timeout >0 >0 blocks until timeout, + * returns - 1 on timeout, magnitude of threshold doesn't play a role. 0 >0 + * Blocks until 1 byte, magnitude of threshold doesn't play a role + */ + public synchronized int read() throws IOException { + if (fd == 0) + throw new IOException(); + if (monThreadisInterrupted) { + log.debug("read(): monThreadisInterrupted"); } IOLockedMutex.readLock().lock(); try { waitForTheNativeCodeSilly(); int result = readByte(); - return( result ); - } - finally - { + return (result); + } finally { IOLockedMutex.readLock().unlock(); } } - /** - * @param b[] - * @return int number of bytes read - * IOException -* -*timeout threshold Behavior -*------------------------------------------------------------------------ -*0 0 blocks until 1 byte is available -*>0 0 blocks until timeout occurs, returns 0 on timeout -*>0 >0 blocks until timeout or reads threshold bytes, - returns 0 on timeout -*0 >0 blocks until reads threshold bytes - */ - public synchronized int read( byte b[] ) throws IOException - { + /** + * @param b[] + * @return int number of bytes read IOException + * + * timeout threshold Behavior + * ------------------------------------------------------------------------ + * 0 0 blocks until 1 byte is available >0 0 blocks until timeout + * occurs, returns 0 on timeout >0 >0 blocks until timeout or reads + * threshold bytes, returns 0 on timeout 0 >0 blocks until reads + * threshold bytes + */ + public synchronized int read(byte b[]) throws IOException { int result; - if ( monThreadisInterrupted == true ) - { - return(0); + if (monThreadisInterrupted == true) { + return (0); } IOLockedMutex.readLock().lock(); - try - { + try { waitForTheNativeCodeSilly(); - result = read( b, 0, b.length); - return( result ); - } - finally - { + result = read(b, 0, b.length); + return (result); + } finally { IOLockedMutex.readLock().unlock(); } } -/* -read(byte b[], int, int) -Documentation is at http://java.sun.com/products/jdk/1.2/docs/api/java/io/InputStream.html#read(byte[], int, int) -*/ - /** - * @param b[] - * @param off - * @param len - * @return int number of bytes read - * IOException -* -*timeout threshold Behavior -*------------------------------------------------------------------------ -*0 0 blocks until 1 byte is available -*>0 0 blocks until timeout occurs, returns 0 on timeout -*>0 >0 blocks until timeout or reads threshold bytes, - returns 0 on timeout -*0 >0 blocks until either threshold # of bytes or len bytes, - whichever was lower. - */ - public synchronized int read( byte b[], int off, int len ) - throws IOException - { + /* + * read(byte b[], int, int) Documentation is at + * http://java.sun.com/products/jdk/1.2/docs/api/java/io/InputStream.html#read( + * byte[], int, int) + */ + /** + * @param b[] + * @param off + * @param len + * @return int number of bytes read IOException + * + * timeout threshold Behavior + * ------------------------------------------------------------------------ + * 0 0 blocks until 1 byte is available >0 0 blocks until timeout + * occurs, returns 0 on timeout >0 >0 blocks until timeout or reads + * threshold bytes, returns 0 on timeout 0 >0 blocks until either + * threshold # of bytes or len bytes, whichever was lower. + */ + public synchronized int read(byte b[], int off, int len) throws IOException { int result; /* * Some sanity checks */ - if ( fd == 0 ) - { + if (fd == 0) { throw new IOException(); } - if( b==null ) - { + if (b == null) { throw new NullPointerException("Input byte array is null"); } - if( (off < 0) || (len < 0) || (off+len > b.length)) - { + if ((off < 0) || (len < 0) || (off + len > b.length)) { throw new IndexOutOfBoundsException("Offset: " + off + " Length: " + len + " Data length: " + b.length); } /* * Return immediately if len==0 */ - if( len==0 ) - { + if (len == 0) { return 0; } /* @@ -1289,93 +1170,76 @@ public synchronized int read( byte b[], int off, int len ) */ int Minimum = len; - if( threshold==0 ) - { - /* - * If threshold is disabled, read should return as soon - * as data are available (up to the amount of available - * bytes in order to avoid blocking) - * Read may return earlier depending of the receive time - * out. - */ + if (threshold == 0) { + /* + * If threshold is disabled, read should return as soon as data are available + * (up to the amount of available bytes in order to avoid blocking) Read may + * return earlier depending of the receive time out. + */ int a = nativeavailable(); - if( a == 0 ) + if (a == 0) Minimum = 1; else - Minimum = Math.min( Minimum, a ); - } - else - { - /* - * Threshold is enabled. Read should return when - * 'threshold' bytes have been received (or when the - * receive timeout expired) - */ + Minimum = Math.min(Minimum, a); + } else { + /* + * Threshold is enabled. Read should return when 'threshold' bytes have been + * received (or when the receive timeout expired) + */ Minimum = Math.min(Minimum, threshold); } - if ( monThreadisInterrupted == true ) - { - log.debug( "RXTXPort:SerialInputStream:read() Interrupted"); - return(0); + if (monThreadisInterrupted == true) { + log.debug("RXTXPort:SerialInputStream:read() Interrupted"); + return (0); } IOLockedMutex.readLock().lock(); - try - { + try { waitForTheNativeCodeSilly(); - result = readArray( b, off, Minimum); - return( result ); - } - finally - { + result = readArray(b, off, Minimum); + return (result); + } finally { IOLockedMutex.readLock().unlock(); } } - /** - * @param b[] - * @param off - * @param len - * @param t[] - * @return int number of bytes read - * IOException - - We are trying to catch the terminator in the native code - Right now it is assumed that t[] is an array of 2 bytes. - - if the read encounters the two bytes, it will return and the - array will contain the terminator. Otherwise read behavior should - be the same as read( b[], off, len ). Timeouts have not been well - tested. - */ - - public synchronized int read( byte b[], int off, int len, byte t[] ) - throws IOException - { - log.trace( "RXTXPort:SerialInputStream:read(" + b.length + " " + off + " " + len + ") called" /*+ new String(b) */ ); + /** + * @param b[] + * @param off + * @param len + * @param t[] + * @return int number of bytes read IOException + * + * We are trying to catch the terminator in the native code Right now it + * is assumed that t[] is an array of 2 bytes. + * + * if the read encounters the two bytes, it will return and the array + * will contain the terminator. Otherwise read behavior should be the + * same as read( b[], off, len ). Timeouts have not been well tested. + */ + + public synchronized int read(byte b[], int off, int len, byte t[]) throws IOException { + log.trace("RXTXPort:SerialInputStream:read(" + b.length + " " + off + " " + len + + ") called" /* + new String(b) */ ); int result; /* * Some sanity checks */ - if ( fd == 0 ) - { + if (fd == 0) { throw new IOException(); } - if( b==null ) - { + if (b == null) { throw new NullPointerException("Input byte array is null"); } - if( (off < 0) || (len < 0) || (off+len > b.length)) - { + if ((off < 0) || (len < 0) || (off + len > b.length)) { throw new IndexOutOfBoundsException("Offset: " + off + " Length: " + len + " Data length: " + b.length); } /* * Return immediately if len==0 */ - if( len==0 ) - { + if (len == 0) { return 0; } /* @@ -1383,630 +1247,500 @@ public synchronized int read( byte b[], int off, int len, byte t[] ) */ int Minimum = len; - if( threshold==0 ) - { - /* - * If threshold is disabled, read should return as soon - * as data are available (up to the amount of available - * bytes in order to avoid blocking) - * Read may return earlier depending of the receive time - * out. - */ + if (threshold == 0) { + /* + * If threshold is disabled, read should return as soon as data are available + * (up to the amount of available bytes in order to avoid blocking) Read may + * return earlier depending of the receive time out. + */ int a = nativeavailable(); - if( a == 0 ) + if (a == 0) Minimum = 1; else - Minimum = Math.min( Minimum, a ); - } - else - { - /* - * Threshold is enabled. Read should return when - * 'threshold' bytes have been received (or when the - * receive timeout expired) - */ + Minimum = Math.min(Minimum, a); + } else { + /* + * Threshold is enabled. Read should return when 'threshold' bytes have been + * received (or when the receive timeout expired) + */ Minimum = Math.min(Minimum, threshold); } - if ( monThreadisInterrupted == true ) - { - log.debug( "RXTXPort:SerialInputStream:read() Interrupted"); - return(0); + if (monThreadisInterrupted == true) { + log.debug("RXTXPort:SerialInputStream:read() Interrupted"); + return (0); } IOLockedMutex.readLock().lock(); - try - { + try { waitForTheNativeCodeSilly(); - result = readTerminatedArray( b, off, Minimum, t ); - return( result ); - } - finally - { + result = readTerminatedArray(b, off, Minimum, t); + return (result); + } finally { IOLockedMutex.readLock().unlock(); } } - /** - * @return int bytes available - * IOException - */ - public synchronized int available() throws IOException - { - if ( monThreadisInterrupted == true ) - { - return(0); + /** + * @return int bytes available IOException + */ + public synchronized int available() throws IOException { + if (monThreadisInterrupted == true) { + return (0); } IOLockedMutex.readLock().lock(); - try - { + try { int r = nativeavailable(); return r; - } - finally - { + } finally { IOLockedMutex.readLock().unlock(); } } } /** - * A dummy method added so RXTX compiles on Kaffee - * @deprecated deprecated but used in Kaffe - */ - public void setRcvFifoTrigger(int trigger){}; - -/*------------------------ END OF CommAPI -----------------------------*/ - - private native static void nativeStaticSetSerialPortParams( String f, - int b, int d, int s, int p ) - throws UnsupportedCommOperationException; - private native static boolean nativeStaticSetDSR( String port, - boolean flag ) - throws UnsupportedCommOperationException; - private native static boolean nativeStaticSetDTR( String port, - boolean flag ) - throws UnsupportedCommOperationException; - private native static boolean nativeStaticSetRTS( String port, - boolean flag ) - throws UnsupportedCommOperationException; - - private native static boolean nativeStaticIsDSR( String port ) - throws UnsupportedCommOperationException; - private native static boolean nativeStaticIsDTR( String port ) - throws UnsupportedCommOperationException; - private native static boolean nativeStaticIsRTS( String port ) - throws UnsupportedCommOperationException; - private native static boolean nativeStaticIsCTS( String port ) - throws UnsupportedCommOperationException; - private native static boolean nativeStaticIsCD( String port ) - throws UnsupportedCommOperationException; - private native static boolean nativeStaticIsRI( String port ) - throws UnsupportedCommOperationException; - - private native static int nativeStaticGetBaudRate( String port ) - throws UnsupportedCommOperationException; - private native static int nativeStaticGetDataBits( String port ) - throws UnsupportedCommOperationException; - private native static int nativeStaticGetParity( String port ) - throws UnsupportedCommOperationException; - private native static int nativeStaticGetStopBits( String port ) - throws UnsupportedCommOperationException; - - - private native byte nativeGetParityErrorChar( ) - throws UnsupportedCommOperationException; - private native boolean nativeSetParityErrorChar( byte b ) - throws UnsupportedCommOperationException; - private native byte nativeGetEndOfInputChar( ) - throws UnsupportedCommOperationException; - private native boolean nativeSetEndOfInputChar( byte b ) - throws UnsupportedCommOperationException; - private native boolean nativeSetUartType(String type, boolean test) - throws UnsupportedCommOperationException; - native String nativeGetUartType() - throws UnsupportedCommOperationException; - private native boolean nativeSetBaudBase(int BaudBase) - throws UnsupportedCommOperationException; - private native int nativeGetBaudBase() - throws UnsupportedCommOperationException; - private native boolean nativeSetDivisor(int Divisor) - throws UnsupportedCommOperationException; - private native int nativeGetDivisor() - throws UnsupportedCommOperationException; - private native boolean nativeSetLowLatency() - throws UnsupportedCommOperationException; - private native boolean nativeGetLowLatency() - throws UnsupportedCommOperationException; - private native boolean nativeSetCallOutHangup(boolean NoHup) - throws UnsupportedCommOperationException; - private native boolean nativeGetCallOutHangup() - throws UnsupportedCommOperationException; - private native boolean nativeClearCommInput() - throws UnsupportedCommOperationException; - - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * This is only accurate up to 38600 baud currently. - * - * @param port the name of the port thats been preopened - * @return BaudRate on success - * UnsupportedCommOperationException; - * This will not behave as expected with custom speeds - * - */ - public static int staticGetBaudRate( String port ) - throws UnsupportedCommOperationException - { - return(nativeStaticGetBaudRate( port )); - } - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * @param port the name of the port thats been preopened - * @return DataBits on success - * UnsupportedCommOperationException; - * - */ - public static int staticGetDataBits( String port ) - throws UnsupportedCommOperationException - { - return(nativeStaticGetDataBits( port ) ); + * A dummy method added so RXTX compiles on Kaffee + * + * @deprecated deprecated but used in Kaffe + */ + public void setRcvFifoTrigger(int trigger) { + }; + + /*------------------------ END OF CommAPI -----------------------------*/ + + private native static void nativeStaticSetSerialPortParams(String f, int b, int d, int s, int p) + throws UnsupportedCommOperationException; + private native static boolean nativeStaticSetDSR(String port, boolean flag) + throws UnsupportedCommOperationException; + private native static boolean nativeStaticSetDTR(String port, boolean flag) + throws UnsupportedCommOperationException; + private native static boolean nativeStaticSetRTS(String port, boolean flag) + throws UnsupportedCommOperationException; + + private native static boolean nativeStaticIsDSR(String port) throws UnsupportedCommOperationException; + private native static boolean nativeStaticIsDTR(String port) throws UnsupportedCommOperationException; + private native static boolean nativeStaticIsRTS(String port) throws UnsupportedCommOperationException; + private native static boolean nativeStaticIsCTS(String port) throws UnsupportedCommOperationException; + private native static boolean nativeStaticIsCD(String port) throws UnsupportedCommOperationException; + private native static boolean nativeStaticIsRI(String port) throws UnsupportedCommOperationException; + + private native static int nativeStaticGetBaudRate(String port) throws UnsupportedCommOperationException; + private native static int nativeStaticGetDataBits(String port) throws UnsupportedCommOperationException; + private native static int nativeStaticGetParity(String port) throws UnsupportedCommOperationException; + private native static int nativeStaticGetStopBits(String port) throws UnsupportedCommOperationException; + + private native byte nativeGetParityErrorChar() throws UnsupportedCommOperationException; + private native boolean nativeSetParityErrorChar(byte b) throws UnsupportedCommOperationException; + private native byte nativeGetEndOfInputChar() throws UnsupportedCommOperationException; + private native boolean nativeSetEndOfInputChar(byte b) throws UnsupportedCommOperationException; + private native boolean nativeSetUartType(String type, boolean test) throws UnsupportedCommOperationException; + native String nativeGetUartType() throws UnsupportedCommOperationException; + private native boolean nativeSetBaudBase(int BaudBase) throws UnsupportedCommOperationException; + private native int nativeGetBaudBase() throws UnsupportedCommOperationException; + private native boolean nativeSetDivisor(int Divisor) throws UnsupportedCommOperationException; + private native int nativeGetDivisor() throws UnsupportedCommOperationException; + private native boolean nativeSetLowLatency() throws UnsupportedCommOperationException; + private native boolean nativeGetLowLatency() throws UnsupportedCommOperationException; + private native boolean nativeSetCallOutHangup(boolean NoHup) throws UnsupportedCommOperationException; + private native boolean nativeGetCallOutHangup() throws UnsupportedCommOperationException; + private native boolean nativeClearCommInput() throws UnsupportedCommOperationException; + + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * This is only accurate up to 38600 baud currently. + * + * @param port + * the name of the port thats been preopened + * @return BaudRate on success UnsupportedCommOperationException; This will not + * behave as expected with custom speeds + * + */ + public static int staticGetBaudRate(String port) throws UnsupportedCommOperationException { + return (nativeStaticGetBaudRate(port)); + } + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @param port + * the name of the port thats been preopened + * @return DataBits on success UnsupportedCommOperationException; + * + */ + public static int staticGetDataBits(String port) throws UnsupportedCommOperationException { + return (nativeStaticGetDataBits(port)); } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * @param port the name of the port thats been preopened - * @return Parity on success - * UnsupportedCommOperationException; - * - */ - public static int staticGetParity( String port ) - throws UnsupportedCommOperationException - { - return( nativeStaticGetParity( port ) ); + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @param port + * the name of the port thats been preopened + * @return Parity on success UnsupportedCommOperationException; + * + */ + public static int staticGetParity(String port) throws UnsupportedCommOperationException { + return (nativeStaticGetParity(port)); } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * @param port the name of the port thats been preopened - * @return StopBits on success - * UnsupportedCommOperationException; - * - */ - public static int staticGetStopBits( String port ) - throws UnsupportedCommOperationException - { - return(nativeStaticGetStopBits( port ) ); + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @param port + * the name of the port thats been preopened + * @return StopBits on success UnsupportedCommOperationException; + * + */ + public static int staticGetStopBits(String port) throws UnsupportedCommOperationException { + return (nativeStaticGetStopBits(port)); } - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * Set the SerialPort parameters - * 1.5 stop bits requires 5 databits - * @param f filename - * @param b baudrate - * @param d databits - * @param s stopbits - * @param p parity - * - * UnsupportedCommOperationException - * @see gnu.io.UnsupportedCommOperationException - */ + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * Set the SerialPort parameters 1.5 stop bits requires 5 databits + * + * @param f + * filename + * @param b + * baudrate + * @param d + * databits + * @param s + * stopbits + * @param p + * parity + * + * UnsupportedCommOperationException + * @see gnu.io.UnsupportedCommOperationException + */ - public static void staticSetSerialPortParams( String f, int b, int d, - int s, int p ) - throws UnsupportedCommOperationException - { - log.trace("RXTXPort:staticSetSerialPortParams( " + - f + " " + b + " " + d + " " + s + " " + p ); - nativeStaticSetSerialPortParams( f, b, d, s, p ); - } - - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * Open the port and set DSR. remove lockfile and do not close - * This is so some software can appear to set the DSR before 'opening' - * the port a second time later on. - * - * @return true on success - * UnsupportedCommOperationException; - * - */ + public static void staticSetSerialPortParams(String f, int b, int d, int s, int p) + throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticSetSerialPortParams( " + f + " " + b + " " + d + " " + s + " " + p); + nativeStaticSetSerialPortParams(f, b, d, s, p); + } - public static boolean staticSetDSR( String port, boolean flag ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticSetDSR( " + port + " " + flag ); - return( nativeStaticSetDSR( port, flag ) ); - } - - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * Open the port and set DTR. remove lockfile and do not close - * This is so some software can appear to set the DTR before 'opening' - * the port a second time later on. - * - * @return true on success - * UnsupportedCommOperationException; - * - */ + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * Open the port and set DSR. remove lockfile and do not close This is so some + * software can appear to set the DSR before 'opening' the port a second time + * later on. + * + * @return true on success UnsupportedCommOperationException; + * + */ - public static boolean staticSetDTR( String port, boolean flag ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticSetDTR( " + port + " " + flag ); - return( nativeStaticSetDTR( port, flag ) ); - } - - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * Open the port and set RTS. remove lockfile and do not close - * This is so some software can appear to set the RTS before 'opening' - * the port a second time later on. - * - * @return none - * UnsupportedCommOperationException; - * - */ + public static boolean staticSetDSR(String port, boolean flag) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticSetDSR( " + port + " " + flag); + return (nativeStaticSetDSR(port, flag)); + } + + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * Open the port and set DTR. remove lockfile and do not close This is so some + * software can appear to set the DTR before 'opening' the port a second time + * later on. + * + * @return true on success UnsupportedCommOperationException; + * + */ - public static boolean staticSetRTS( String port, boolean flag ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticSetRTS( " + port + " " + flag ); - return( nativeStaticSetRTS( port, flag ) ); + public static boolean staticSetDTR(String port, boolean flag) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticSetDTR( " + port + " " + flag); + return (nativeStaticSetDTR(port, flag)); } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * find the fd and return RTS without using a Java open() call - * - * @param port - * @return true if asserted - * UnsupportedCommOperationException; - * - */ + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * Open the port and set RTS. remove lockfile and do not close This is so some + * software can appear to set the RTS before 'opening' the port a second time + * later on. + * + * @return none UnsupportedCommOperationException; + * + */ - public static boolean staticIsRTS( String port ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticIsRTS( " + port + " )" ); - return( nativeStaticIsRTS( port ) ); - } - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * find the fd and return CD without using a Java open() call - * - * @param port - * @return true if asserted - * UnsupportedCommOperationException; - * - */ + public static boolean staticSetRTS(String port, boolean flag) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticSetRTS( " + port + " " + flag); + return (nativeStaticSetRTS(port, flag)); + } - public static boolean staticIsCD( String port ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticIsCD( " + port + " )" ); - return( nativeStaticIsCD( port ) ); - } - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * find the fd and return CTS without using a Java open() call - * - * @param port - * @return true if asserted - * UnsupportedCommOperationException; - * - */ + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * find the fd and return RTS without using a Java open() call + * + * @param port + * @return true if asserted UnsupportedCommOperationException; + * + */ - public static boolean staticIsCTS( String port ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticIsCTS( " + port + " )" ); - return( nativeStaticIsCTS( port ) ); - } - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * find the fd and return DSR without using a Java open() call - * - * @param port - * @return true if asserted - * UnsupportedCommOperationException; - * - */ + public static boolean staticIsRTS(String port) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticIsRTS( " + port + " )"); + return (nativeStaticIsRTS(port)); + } + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * find the fd and return CD without using a Java open() call + * + * @param port + * @return true if asserted UnsupportedCommOperationException; + * + */ - public static boolean staticIsDSR( String port ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticIsDSR( " + port + " )" ); - return( nativeStaticIsDSR( port ) ); - } - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * find the fd and return DTR without using a Java open() call - * - * @param port - * @return true if asserted - * UnsupportedCommOperationException; - * - */ + public static boolean staticIsCD(String port) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticIsCD( " + port + " )"); + return (nativeStaticIsCD(port)); + } + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * find the fd and return CTS without using a Java open() call + * + * @param port + * @return true if asserted UnsupportedCommOperationException; + * + */ - public static boolean staticIsDTR( String port ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticIsDTR( " + port + " )" ); - return( nativeStaticIsDTR( port ) ); - } - /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * - * find the fd and return RI without using a Java open() call - * - * @param port - * @return true if asserted - * UnsupportedCommOperationException; - * - */ + public static boolean staticIsCTS(String port) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticIsCTS( " + port + " )"); + return (nativeStaticIsCTS(port)); + } + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * find the fd and return DSR without using a Java open() call + * + * @param port + * @return true if asserted UnsupportedCommOperationException; + * + */ - public static boolean staticIsRI( String port ) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:staticIsRI( " + port + " )" ); - return( nativeStaticIsRI( port ) ); + public static boolean staticIsDSR(String port) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticIsDSR( " + port + " )"); + return (nativeStaticIsDSR(port)); } + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * find the fd and return DTR without using a Java open() call + * + * @param port + * @return true if asserted UnsupportedCommOperationException; + * + */ + public static boolean staticIsDTR(String port) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticIsDTR( " + port + " )"); + return (nativeStaticIsDTR(port)); + } + /** + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * find the fd and return RI without using a Java open() call + * + * @param port + * @return true if asserted UnsupportedCommOperationException; + * + */ + + public static boolean staticIsRI(String port) throws UnsupportedCommOperationException { + log.trace("RXTXPort:staticIsRI( " + port + " )"); + return (nativeStaticIsRI(port)); + } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * @return int the Parity Error Character - * UnsupportedCommOperationException; - * - * Anyone know how to do this in Unix? - */ + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @return int the Parity Error Character UnsupportedCommOperationException; + * + * Anyone know how to do this in Unix? + */ - public byte getParityErrorChar( ) - throws UnsupportedCommOperationException - { + public byte getParityErrorChar() throws UnsupportedCommOperationException { byte ret; ret = nativeGetParityErrorChar(); - return( ret ); + return (ret); } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * @param b Parity Error Character - * @return boolean true on success - * UnsupportedCommOperationException; - * - * Anyone know how to do this in Unix? - */ + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @param b + * Parity Error Character + * @return boolean true on success UnsupportedCommOperationException; + * + * Anyone know how to do this in Unix? + */ - public boolean setParityErrorChar( byte b ) - throws UnsupportedCommOperationException - { - log.trace( "setParityErrorChar(" + b + ")" ); - return( nativeSetParityErrorChar( b ) ); + public boolean setParityErrorChar(byte b) throws UnsupportedCommOperationException { + log.trace("setParityErrorChar(" + b + ")"); + return (nativeSetParityErrorChar(b)); } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * @return int the End of Input Character - * UnsupportedCommOperationException; - * - * Anyone know how to do this in Unix? - */ + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @return int the End of Input Character UnsupportedCommOperationException; + * + * Anyone know how to do this in Unix? + */ - public byte getEndOfInputChar( ) - throws UnsupportedCommOperationException - { + public byte getEndOfInputChar() throws UnsupportedCommOperationException { byte ret; ret = nativeGetEndOfInputChar(); - return( ret ); + return (ret); } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * @param b End Of Input Character - * @return boolean true on success - * UnsupportedCommOperationException; - */ + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @param b + * End Of Input Character + * @return boolean true on success UnsupportedCommOperationException; + */ - public boolean setEndOfInputChar( byte b ) - throws UnsupportedCommOperationException - { - log.trace( "setEndOfInputChar(" + b + ")" ); - return( nativeSetEndOfInputChar( b ) ); + public boolean setEndOfInputChar(byte b) throws UnsupportedCommOperationException { + log.trace("setEndOfInputChar(" + b + ")"); + return (nativeSetEndOfInputChar(b)); } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * @param type String representation of the UART type which mayb - * be "none", "8250", "16450", "16550", "16550A", "16650", "16550V2" - * or "16750". - * @param test boolean flag to determin if the UART should be tested. - * @return boolean true on success - * UnsupportedCommOperationException; - */ - public boolean setUARTType(String type, boolean test) - throws UnsupportedCommOperationException - { - log.trace( "RXTXPort:setUARTType()"); + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @param type + * String representation of the UART type which mayb be "none", + * "8250", "16450", "16550", "16550A", "16650", "16550V2" or "16750". + * @param test + * boolean flag to determin if the UART should be tested. + * @return boolean true on success UnsupportedCommOperationException; + */ + public boolean setUARTType(String type, boolean test) throws UnsupportedCommOperationException { + log.trace("RXTXPort:setUARTType()"); return nativeSetUartType(type, test); } /** - * Extension to CommAPI - * This is an extension to CommAPI. It may not be supported on - * all operating systems. - * @return type String representation of the UART type which mayb - * be "none", "8250", "16450", "16550", "16550A", "16650", "16550V2" - * or "16750". - * UnsupportedCommOperationException; - */ - public String getUARTType() throws UnsupportedCommOperationException - { + * Extension to CommAPI This is an extension to CommAPI. It may not be supported + * on all operating systems. + * + * @return type String representation of the UART type which mayb be "none", + * "8250", "16450", "16550", "16550A", "16650", "16550V2" or "16750". + * UnsupportedCommOperationException; + */ + public String getUARTType() throws UnsupportedCommOperationException { return nativeGetUartType(); } /** - * Extension to CommAPI. Set Baud Base to 38600 on Linux and W32 - * before using. - * @param BaudBase The clock frequency divided by 16. Default - * BaudBase is 115200. - * @return true on success - * UnsupportedCommOperationException, IOException - */ + * Extension to CommAPI. Set Baud Base to 38600 on Linux and W32 before using. + * + * @param BaudBase + * The clock frequency divided by 16. Default BaudBase is 115200. + * @return true on success UnsupportedCommOperationException, IOException + */ - public boolean setBaudBase(int BaudBase) - throws UnsupportedCommOperationException, - IOException - { - log.trace( "RXTXPort:setBaudBase()"); + public boolean setBaudBase(int BaudBase) throws UnsupportedCommOperationException, IOException { + log.trace("RXTXPort:setBaudBase()"); return nativeSetBaudBase(BaudBase); } /** - * Extension to CommAPI - * @return BaudBase - * UnsupportedCommOperationException, IOException - */ + * Extension to CommAPI + * + * @return BaudBase UnsupportedCommOperationException, IOException + */ - public int getBaudBase() throws UnsupportedCommOperationException, - IOException - { + public int getBaudBase() throws UnsupportedCommOperationException, IOException { return nativeGetBaudBase(); } /** - * Extension to CommAPI. Set Baud Base to 38600 on Linux and W32 - * before using. - * @param Divisor - * UnsupportedCommOperationException, IOException - */ + * Extension to CommAPI. Set Baud Base to 38600 on Linux and W32 before using. + * + * @param Divisor + * UnsupportedCommOperationException, IOException + */ - public boolean setDivisor(int Divisor) - throws UnsupportedCommOperationException, IOException - { + public boolean setDivisor(int Divisor) throws UnsupportedCommOperationException, IOException { return nativeSetDivisor(Divisor); } /** - * Extension to CommAPI - * @return Divisor; - * UnsupportedCommOperationException, IOException - */ + * Extension to CommAPI + * + * @return Divisor; UnsupportedCommOperationException, IOException + */ - public int getDivisor() throws UnsupportedCommOperationException, - IOException - { + public int getDivisor() throws UnsupportedCommOperationException, IOException { return nativeGetDivisor(); } /** - * Extension to CommAPI - * returns boolean true on success - * UnsupportedCommOperationException - */ + * Extension to CommAPI returns boolean true on success + * UnsupportedCommOperationException + */ - public boolean setLowLatency() throws UnsupportedCommOperationException - { + public boolean setLowLatency() throws UnsupportedCommOperationException { return nativeSetLowLatency(); } /** - * Extension to CommAPI - * returns boolean true on success - * UnsupportedCommOperationException - */ + * Extension to CommAPI returns boolean true on success + * UnsupportedCommOperationException + */ - public boolean getLowLatency() throws UnsupportedCommOperationException - { + public boolean getLowLatency() throws UnsupportedCommOperationException { return nativeGetLowLatency(); } /** - * Extension to CommAPI - * returns boolean true on success - * UnsupportedCommOperationException - */ + * Extension to CommAPI returns boolean true on success + * UnsupportedCommOperationException + */ - public boolean setCallOutHangup(boolean NoHup) - throws UnsupportedCommOperationException - { + public boolean setCallOutHangup(boolean NoHup) throws UnsupportedCommOperationException { return nativeSetCallOutHangup(NoHup); } /** - * Extension to CommAPI - * returns boolean true on success - * UnsupportedCommOperationException - */ + * Extension to CommAPI returns boolean true on success + * UnsupportedCommOperationException + */ - public boolean getCallOutHangup() - throws UnsupportedCommOperationException - { + public boolean getCallOutHangup() throws UnsupportedCommOperationException { return nativeGetCallOutHangup(); } /** - * Extension to CommAPI - * returns boolean true on success - * UnsupportedCommOperationException - */ + * Extension to CommAPI returns boolean true on success + * UnsupportedCommOperationException + */ - public boolean clearCommInput() - throws UnsupportedCommOperationException - { + public boolean clearCommInput() throws UnsupportedCommOperationException { return nativeClearCommInput(); } - public int enableRs485(boolean busEnableActiveLow, int delayBusEnableBeforeSendMs, int delayBusEnableAfterSendMs) { return controlRs485(fd, true, busEnableActiveLow, delayBusEnableBeforeSendMs, delayBusEnableAfterSendMs); } @@ -2015,7 +1749,8 @@ public int disableRs485() { return controlRs485(fd, false, false, 0, 0); } - private native synchronized int controlRs485(int fd, boolean enable, boolean busEnableActiveLow, int delayBusEnableBeforeSendMs, int delayBusEnableAfterSendMs); + private native synchronized int controlRs485(int fd, boolean enable, boolean busEnableActiveLow, + int delayBusEnableBeforeSendMs, int delayBusEnableAfterSendMs); -/*------------------------ END OF CommAPI Extensions -----------------------*/ + /*------------------------ END OF CommAPI Extensions -----------------------*/ } diff --git a/src/main/java/gnu/io/Zystem.java b/src/main/java/gnu/io/Zystem.java index 351982dd..a1efff25 100755 --- a/src/main/java/gnu/io/Zystem.java +++ b/src/main/java/gnu/io/Zystem.java @@ -58,288 +58,203 @@ package gnu.io; import java.io.RandomAccessFile; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class Zystem -{ +public class Zystem { private static final Logger log = LoggerFactory.getLogger(Zystem.class); - public static final int SILENT_MODE = 0; - public static final int FILE_MODE = 1; - public static final int NET_MODE = 2; - public static final int MEX_MODE = 3; - public static final int PRINT_MODE = 4; - public static final int J2EE_MSG_MODE = 5; - public static final int J2SE_LOG_MODE = 6; + public static final int SILENT_MODE = 0; + public static final int FILE_MODE = 1; + public static final int NET_MODE = 2; + public static final int MEX_MODE = 3; + public static final int PRINT_MODE = 4; + public static final int J2EE_MSG_MODE = 5; + public static final int J2SE_LOG_MODE = 6; static int mode; - static - { - /* - The rxtxZystem library uses Python code and is not - included with RXTX. A seperate library will be released - to avoid potential license conflicts. - - Trent Jarvi taj@www.linux.org.uk - */ + static { + /* + * The rxtxZystem library uses Python code and is not included with RXTX. A + * seperate library will be released to avoid potential license conflicts. + * + * Trent Jarvi taj@www.linux.org.uk + */ - //System.loadLibrary( "rxtxZystem" ); + // System.loadLibrary( "rxtxZystem" ); mode = SILENT_MODE; } private static String target; - public Zystem( int m ) throws UnSupportedLoggerException - { + public Zystem(int m) throws UnSupportedLoggerException { mode = m; - startLogger( "asdf" ); + startLogger("asdf"); + } + /** + * Constructor. Mode is taken from the java system property "gnu.io.log.mode". + * The available values are : + *
    + *
  • SILENT_MODE No logging + *
  • FILE_MODE log to file + *
  • NET_MODE + *
  • MEX_MODE + *
  • PRINT_MODE + *
  • J2EE_MSG_MODE + *
  • J2SE_LOG_MODE log to java.util.logging + *
+ */ + public Zystem() throws UnSupportedLoggerException { + String s = System.getProperty("gnu.io.log.mode"); + if (s != null) { + if ("SILENT_MODE".equals(s)) { + mode = SILENT_MODE; + } else if ("FILE_MODE".equals(s)) { + mode = FILE_MODE; + } else if ("NET_MODE".equals(s)) { + mode = NET_MODE; + } else if ("MEX_MODE".equals(s)) { + mode = MEX_MODE; + } else if ("PRINT_MODE".equals(s)) { + mode = PRINT_MODE; + } else if ("J2EE_MSG_MODE".equals(s)) { + mode = J2EE_MSG_MODE; + } else if ("J2SE_LOG_MODE".equals(s)) { + mode = J2SE_LOG_MODE; + } else { + try { + mode = Integer.parseInt(s); + } catch (NumberFormatException e) { + mode = SILENT_MODE; + } + } + } else { + mode = SILENT_MODE; + } + startLogger("asdf"); } - /** - * Constructor. - * Mode is taken from the java system property "gnu.io.log.mode". The available values are :
    - *
  • SILENT_MODE No logging - *
  • FILE_MODE log to file - *
  • NET_MODE - *
  • MEX_MODE - *
  • PRINT_MODE - *
  • J2EE_MSG_MODE - *
  • J2SE_LOG_MODE log to java.util.logging - *
- */ - public Zystem () throws UnSupportedLoggerException - { - String s = System.getProperty ("gnu.io.log.mode"); - if (s != null) - { - if ("SILENT_MODE".equals (s)) - { - mode = SILENT_MODE; - } - else if ("FILE_MODE".equals (s)) - { - mode = FILE_MODE; - } - else if ("NET_MODE".equals (s)) - { - mode = NET_MODE; - } - else if ("MEX_MODE".equals (s)) - { - mode = MEX_MODE; - } - else if ("PRINT_MODE".equals (s)) - { - mode = PRINT_MODE; - } - else if ("J2EE_MSG_MODE".equals (s)) - { - mode = J2EE_MSG_MODE; - } - else if ("J2SE_LOG_MODE".equals (s)) - { - mode = J2SE_LOG_MODE; - } - else - { - try - { - mode = Integer.parseInt (s); - } - catch (NumberFormatException e) - { - mode = SILENT_MODE; - } - } - } - else - { - mode = SILENT_MODE; - } - startLogger ("asdf"); - } - - public void startLogger( ) throws UnSupportedLoggerException - { - if ( mode == SILENT_MODE || mode == PRINT_MODE ) - { - //nativeNetInit( ); + public void startLogger() throws UnSupportedLoggerException { + if (mode == SILENT_MODE || mode == PRINT_MODE) { + // nativeNetInit( ); return; } - throw new UnSupportedLoggerException( "Target Not Allowed" ); + throw new UnSupportedLoggerException("Target Not Allowed"); } - /* accept the host or file to log to. */ + /* accept the host or file to log to. */ - public void startLogger( String t ) throws UnSupportedLoggerException - { + public void startLogger(String t) throws UnSupportedLoggerException { target = t; - /* - if ( mode == NET_MODE ) - { - nativeNetInit( ); - } - if ( nativeInit( ) ) - { - throw new UnSupportedLoggerException( - "Port initializion failed" ); - } - */ + /* + * if ( mode == NET_MODE ) { nativeNetInit( ); } if ( nativeInit( ) ) { throw + * new UnSupportedLoggerException( "Port initializion failed" ); } + */ return; } - public void finalize() - { - /* - if ( mode == NET_MODE ) - { - nativeNetFinalize( ); - } - nativeFinalize(); - */ + public void finalize() { + /* + * if ( mode == NET_MODE ) { nativeNetFinalize( ); } nativeFinalize(); + */ mode = SILENT_MODE; target = null; } - public void filewrite( String s ) - { + public void filewrite(String s) { try { - RandomAccessFile w = - new RandomAccessFile( target, "rw" ); - w.seek( w.length() ); - w.writeBytes( s ); + RandomAccessFile w = new RandomAccessFile(target, "rw"); + w.seek(w.length()); + w.writeBytes(s); w.close(); - } catch ( Exception e ) { + } catch (Exception e) { log.error("Debug output file write failed", e); } } - public boolean report( String s) - { - if ( mode == NET_MODE ) - { - // return( nativeNetReportln( s ) ); - } - else if ( mode == PRINT_MODE ) - { - log.debug( s ); - return( true ); - } - else if ( mode == MEX_MODE ) - { - // return( nativeMexReport( s ) ); - } - else if ( mode == SILENT_MODE ) - { - return( true ); - } - else if ( mode == FILE_MODE ) - { - filewrite( s ); - } - else if ( mode == J2EE_MSG_MODE ) - { - return( false ); - } - else if (mode == J2SE_LOG_MODE) - { - java.util.logging.Logger.getLogger ("gnu.io").fine (s); + public boolean report(String s) { + if (mode == NET_MODE) { + // return( nativeNetReportln( s ) ); + } else if (mode == PRINT_MODE) { + log.debug(s); + return (true); + } else if (mode == MEX_MODE) { + // return( nativeMexReport( s ) ); + } else if (mode == SILENT_MODE) { + return (true); + } else if (mode == FILE_MODE) { + filewrite(s); + } else if (mode == J2EE_MSG_MODE) { + return (false); + } else if (mode == J2SE_LOG_MODE) { + java.util.logging.Logger.getLogger("gnu.io").fine(s); return (true); } - return( false ); + return (false); } - public boolean reportln( ) - { - if ( mode == NET_MODE ) - { - // b= nativeNetReportln( "\n" ); - // return(b); - } - else if ( mode == PRINT_MODE ) - { - log.debug( "" ); - return( true ); - } - else if ( mode == MEX_MODE ) - { - // b = nativeMexReportln( "\n" ); - // return(b); - } - else if ( mode == SILENT_MODE ) - { - return( true ); - } - else if ( mode == FILE_MODE ) - { - filewrite( "\n" ); - } - else if ( mode == J2EE_MSG_MODE ) - { - return( false ); + public boolean reportln() { + if (mode == NET_MODE) { + // b= nativeNetReportln( "\n" ); + // return(b); + } else if (mode == PRINT_MODE) { + log.debug(""); + return (true); + } else if (mode == MEX_MODE) { + // b = nativeMexReportln( "\n" ); + // return(b); + } else if (mode == SILENT_MODE) { + return (true); + } else if (mode == FILE_MODE) { + filewrite("\n"); + } else if (mode == J2EE_MSG_MODE) { + return (false); } - return( false ); + return (false); } - public boolean reportln( String s) - { - if ( mode == NET_MODE ) - { - // b= nativeNetReportln( s + "\n" ); - // return(b); - } - else if ( mode == PRINT_MODE ) - { - log.debug( s ); - return( true ); - } - else if ( mode == MEX_MODE ) - { - // b = nativeMexReportln( s + "\n" ); - // return(b); - } - else if ( mode == SILENT_MODE ) - { - return( true ); - } - else if ( mode == FILE_MODE ) - { - filewrite( s + "\n" ); - } - else if ( mode == J2EE_MSG_MODE ) - { - return( false ); - } - else if (mode == J2SE_LOG_MODE) - { + public boolean reportln(String s) { + if (mode == NET_MODE) { + // b= nativeNetReportln( s + "\n" ); + // return(b); + } else if (mode == PRINT_MODE) { + log.debug(s); + return (true); + } else if (mode == MEX_MODE) { + // b = nativeMexReportln( s + "\n" ); + // return(b); + } else if (mode == SILENT_MODE) { + return (true); + } else if (mode == FILE_MODE) { + filewrite(s + "\n"); + } else if (mode == J2EE_MSG_MODE) { + return (false); + } else if (mode == J2SE_LOG_MODE) { return (true); } - return( false ); + return (false); } -/* - private native boolean nativeInit( ); - private native void nativeFinalize(); -*/ + /* + * private native boolean nativeInit( ); private native void nativeFinalize(); + */ /* open and close the socket */ -/* - private native boolean nativeNetInit( ); - private native void nativeNetFinalize(); -*/ + /* + * private native boolean nativeNetInit( ); private native void + * nativeNetFinalize(); + */ /* dumping to a remote machine */ -/* - public native boolean nativeNetReport( String s ); - public native boolean nativeNetReportln( String s ); -*/ + /* + * public native boolean nativeNetReport( String s ); public native boolean + * nativeNetReportln( String s ); + */ - /* specific to Matlab */ -/* - public native boolean nativeMexReport( String s ); - public native boolean nativeMexReportln( String s ); -*/ + /* specific to Matlab */ + /* + * public native boolean nativeMexReport( String s ); public native boolean + * nativeMexReportln( String s ); + */ } diff --git a/src/main/java/gnu/io/factory/SerialPortRegistry.java b/src/main/java/gnu/io/factory/SerialPortRegistry.java index 70968f96..832f0a1d 100644 --- a/src/main/java/gnu/io/factory/SerialPortRegistry.java +++ b/src/main/java/gnu/io/factory/SerialPortRegistry.java @@ -1,11 +1,9 @@ package gnu.io.factory; +import gnu.io.SerialPort; import java.util.Collection; import java.util.Comparator; import java.util.TreeSet; - -import gnu.io.SerialPort; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -13,26 +11,29 @@ public class SerialPortRegistry { private static final Logger log = LoggerFactory.getLogger(SerialPortRegistry.class); 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>() { + // 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()); + } + }); - @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}. */ @@ -40,28 +41,35 @@ 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. + * 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) { + public SerialPortCreator getPortCreatorForPortName(String portName, + Class expectedClass) { + for (@SuppressWarnings("rawtypes") + SerialPortCreator creator : this.portCreators) { try { - if(creator.isApplicable(portName, expectedClass)) + if (creator.isApplicable(portName, expectedClass)) return (SerialPortCreator) creator; - } catch(Exception e) { - log.error("Error for SerialPortCreator#isApplicable: " + creator.getClass()+"; " + creator.getProtocol() + " ->", e); + } catch (Exception e) { + log.error("Error for SerialPortCreator#isApplicable: " + creator.getClass() + "; " + + creator.getProtocol() + " ->", e); } } return null; diff --git a/src/main/java/gnu/io/rfc2217/ComPortOptionHandler.java b/src/main/java/gnu/io/rfc2217/ComPortOptionHandler.java index 5a0af46e..c60801fd 100644 --- a/src/main/java/gnu/io/rfc2217/ComPortOptionHandler.java +++ b/src/main/java/gnu/io/rfc2217/ComPortOptionHandler.java @@ -56,7 +56,6 @@ package gnu.io.rfc2217; import org.apache.commons.net.telnet.TelnetOptionHandler; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,50 +65,49 @@ * @see RFC 2217 */ public class ComPortOptionHandler extends TelnetOptionHandler { - private static final Logger log = LoggerFactory.getLogger(ComPortOptionHandler.class); + private static final Logger log = LoggerFactory.getLogger(ComPortOptionHandler.class); - private final TelnetSerialPort port; + private final TelnetSerialPort port; - protected ComPortOptionHandler(TelnetSerialPort telnetSerialPort) { - super(RFC2217.COM_PORT_OPTION, true, false, true, false); - if (telnetSerialPort == null) - throw new IllegalArgumentException("null telnetSerialPort"); - this.port = telnetSerialPort; - } + protected ComPortOptionHandler(TelnetSerialPort telnetSerialPort) { + super(RFC2217.COM_PORT_OPTION, true, false, true, false); + if (telnetSerialPort == null) + throw new IllegalArgumentException("null telnetSerialPort"); + this.port = telnetSerialPort; + } - @Override - public int[] answerSubnegotiation(int[] data, int length) { + @Override + public int[] answerSubnegotiation(int[] data, int length) { - // Copy data into buffer of the correct size - if (data.length != length) { - int[] data2 = new int[length]; - System.arraycopy(data, 0, data2, 0, length); - data = data2; - } + // Copy data into buffer of the correct size + if (data.length != length) { + int[] data2 = new int[length]; + System.arraycopy(data, 0, data2, 0, length); + data = data2; + } - // Decode option - ComPortCommand command; - try { - command = RFC2217.decodeComPortCommand(data); - } catch (IllegalArgumentException e) { - log.error(this.port.getName() + ": rec'd invalid COM-PORT-OPTION command:", e); - return null; - } + // Decode option + ComPortCommand command; + try { + command = RFC2217.decodeComPortCommand(data); + } catch (IllegalArgumentException e) { + log.error(this.port.getName() + ": rec'd invalid COM-PORT-OPTION command:", e); + return null; + } - // Notify port - this.port.handleCommand(command); - return null; - } + // Notify port + this.port.handleCommand(command); + return null; + } - @Override - public int[] startSubnegotiationLocal() { - this.port.startSubnegotiation(); - return null; - } + @Override + public int[] startSubnegotiationLocal() { + this.port.startSubnegotiation(); + return null; + } - @Override - public int[] startSubnegotiationRemote() { - return null; - } + @Override + public int[] startSubnegotiationRemote() { + return null; + } } - diff --git a/src/main/java/gnu/io/rfc2217/TelnetSerialPort.java b/src/main/java/gnu/io/rfc2217/TelnetSerialPort.java index 010d7524..897dee15 100644 --- a/src/main/java/gnu/io/rfc2217/TelnetSerialPort.java +++ b/src/main/java/gnu/io/rfc2217/TelnetSerialPort.java @@ -55,27 +55,6 @@ --------------------------------------------------------------------------*/ package gnu.io.rfc2217; -import gnu.io.SerialPort; -import gnu.io.SerialPortEvent; -import gnu.io.SerialPortEventListener; -import gnu.io.UnsupportedCommOperationException; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.TooManyListenersException; - -import org.apache.commons.net.telnet.EchoOptionHandler; -import org.apache.commons.net.telnet.InvalidTelnetOptionException; -import org.apache.commons.net.telnet.SuppressGAOptionHandler; -import org.apache.commons.net.telnet.TelnetClient; -import org.apache.commons.net.telnet.TelnetInputListener; -import org.apache.commons.net.telnet.TerminalTypeOptionHandler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import static gnu.io.rfc2217.RFC2217.CONTROL_BREAK_OFF; import static gnu.io.rfc2217.RFC2217.CONTROL_BREAK_ON; import static gnu.io.rfc2217.RFC2217.CONTROL_DTR_OFF; @@ -106,31 +85,50 @@ import static gnu.io.rfc2217.RFC2217.STOPSIZE_1_5; import static gnu.io.rfc2217.RFC2217.STOPSIZE_2; +import gnu.io.SerialPort; +import gnu.io.SerialPortEvent; +import gnu.io.SerialPortEventListener; +import gnu.io.UnsupportedCommOperationException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.TooManyListenersException; +import org.apache.commons.net.telnet.EchoOptionHandler; +import org.apache.commons.net.telnet.InvalidTelnetOptionException; +import org.apache.commons.net.telnet.SuppressGAOptionHandler; +import org.apache.commons.net.telnet.TelnetClient; +import org.apache.commons.net.telnet.TelnetInputListener; +import org.apache.commons.net.telnet.TerminalTypeOptionHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** - * Implements the client side of the RFC 2217 - * serial-over-Telnet protocol as as {@link SerialPort}. + * Implements the client side of the + * RFC 2217 serial-over-Telnet + * protocol as as {@link SerialPort}. * - * - * This class extends the {@link SerialPort} class and functions in the same way, however, there are - * a couple of differences to be aware of: + * + * This class extends the {@link SerialPort} class and functions in the same + * way, however, there are a couple of differences to be aware of: *
    - *
  • - * To "open" a serial port, create an instance of this class, configure it as required, - * and then get the {@link TelnetClient} via {@link #getTelnetClient} and invoke - * {@link TelnetClient#connect(java.net.InetAddress, int) TelnetClient.connect()} (or one of its variants). - * This will create the telnet connection to the access server. - *
  • + *
  • To "open" a serial port, create an instance of this class, configure it + * as required, and then get the {@link TelnetClient} via + * {@link #getTelnetClient} and invoke + * {@link TelnetClient#connect(java.net.InetAddress, int) + * TelnetClient.connect()} (or one of its variants). This will create the telnet + * connection to the access server.
  • * - *
  • - * Once connected, if the underlying telnet connection is broken, an {@link IOException} will be - * thrown when attempting to access the serial port input or output streams. In addition, a - * {@link SerialPortEvent#DATA_AVAILABLE DATA_AVAILABLE} event will be immediately generated. - *
  • + *
  • Once connected, if the underlying telnet connection is broken, an + * {@link IOException} will be thrown when attempting to access the serial port + * input or output streams. In addition, a {@link SerialPortEvent#DATA_AVAILABLE + * DATA_AVAILABLE} event will be immediately generated.
  • *
- * + * * - * - * The following optional functionality is not implemented and/or inappropriate for a networked connection: + * + * The following optional functionality is not implemented and/or inappropriate + * for a networked connection: *
    *
  • Receive threshold
  • *
  • Receive timeout
  • @@ -138,1003 +136,1024 @@ *
  • Input buffer size
  • *
  • Output buffer size
  • *
- * + * * - * - * In addition, access servers typically don't support {@link #notifyOnOutputEmpty}. - * + * + * In addition, access servers typically don't support + * {@link #notifyOnOutputEmpty}. + * * - * - * Finally, {@link #sendBreak} is supported but the {@code millis} argument is ignored, as timing cannot be - * assured over a TCP connection. Access servers typically enforce a fixed break time. - * + * + * Finally, {@link #sendBreak} is supported but the {@code millis} argument is + * ignored, as timing cannot be assured over a TCP connection. Access servers + * typically enforce a fixed break time. + * * * @see SerialPort * @see RFC 2217 */ public class TelnetSerialPort extends SerialPort { - private static final Logger log = LoggerFactory.getLogger(TelnetSerialPort.class); - - private static final int DEFAULT_BAUD_RATE = 9600; - - private static final String DEFAULT_TERMINAL_TYPE = "VT100"; - - // Modem state bits we always want the server to report to us regardless of what listener wants. - // This is so we can always stay up-to-date with their values in case isCD(), etc. is invoked. - private static final int MODEMSTATE_ALWAYS_MONITOR - = MODEMSTATE_CARRIER_DETECT | MODEMSTATE_RING_INDICATOR | MODEMSTATE_DSR | MODEMSTATE_CTS; - - // Line state bits we never want the server to report to us regardless of what listener wants; internally, - // we use the LINESTATE_DATA_READY bit only to indicate the listener wants DATA_AVAILABLE notifications. - private static final int LINESTATE_NEVER_MONITOR = LINESTATE_DATA_READY; - - // States - private enum State { - INITIAL(false, false), - ESTABLISHED(true, false), - CLOSED(false, true); - - private final boolean established; - private final boolean closed; - - private State(boolean established, boolean closed) { - this.established = established; - this.closed = closed; - } - - public void checkNotClosed() { - if (this.closed) - throw new IllegalStateException("port is closed"); - } - - public boolean isEstablished() { - return this.established; - } - } - - private final TelnetClient telnetClient; - - private String name; - private String signature; - private State state; - private SerialPortEventListener listener; - - private int baudRate = DEFAULT_BAUD_RATE; - private int dataSize = DATASIZE_8; - private int flowControlInbound = CONTROL_INBOUND_FLOW_NONE; - private int flowControlOutbound = CONTROL_OUTBOUND_FLOW_NONE; - private int parity = RFC2217.PARITY_NONE; - private int stopSize = STOPSIZE_1; - - private boolean cd; - private boolean cts; - private boolean dsr; - private boolean dtr; - private boolean ri; - private boolean rts; - - private int lineStateNotify; // which line state changes we notify listener about - private int lineStateMask; // which line state changes access server notifies us about - private int lineStateLast; // most recent line state rec'd from access server - private int modemStateNotify; // which modem state changes we notify listener about - private int modemStateMask = MODEMSTATE_ALWAYS_MONITOR; // which modem state changes access server notifies us about - private int modemStateLast; // most recent modem state rec'd from access server - - /** - * Constructor. - */ - public TelnetSerialPort() { - this.state = State.INITIAL; - this.name = getClass().getSimpleName(); - this.signature = "jvser v" + Version.JVSER_VERSION; - this.telnetClient = this.createTelnetClient(); - this.telnetClient.registerInputListener(new TelnetInputListener() { - - @Override - public void telnetInputAvailable() { - boolean notify; - synchronized (TelnetSerialPort.this) { - notify = (TelnetSerialPort.this.lineStateNotify & LINESTATE_DATA_READY) != 0; - } - if (notify) - TelnetSerialPort.this.sendEvent(SerialPortEvent.DATA_AVAILABLE); - } - }); - } - - /** - * Get the descriptive name of this client (used for logging purposes). - */ - @Override + private static final Logger log = LoggerFactory.getLogger(TelnetSerialPort.class); + + private static final int DEFAULT_BAUD_RATE = 9600; + + private static final String DEFAULT_TERMINAL_TYPE = "VT100"; + + // Modem state bits we always want the server to report to us regardless of what + // listener wants. + // This is so we can always stay up-to-date with their values in case isCD(), + // etc. is invoked. + private static final int MODEMSTATE_ALWAYS_MONITOR = MODEMSTATE_CARRIER_DETECT | MODEMSTATE_RING_INDICATOR + | MODEMSTATE_DSR | MODEMSTATE_CTS; + + // Line state bits we never want the server to report to us regardless of what + // listener wants; internally, + // we use the LINESTATE_DATA_READY bit only to indicate the listener wants + // DATA_AVAILABLE notifications. + private static final int LINESTATE_NEVER_MONITOR = LINESTATE_DATA_READY; + + // States + private enum State { + INITIAL(false, false), ESTABLISHED(true, false), CLOSED(false, true); + + private final boolean established; + private final boolean closed; + + private State(boolean established, boolean closed) { + this.established = established; + this.closed = closed; + } + + public void checkNotClosed() { + if (this.closed) + throw new IllegalStateException("port is closed"); + } + + public boolean isEstablished() { + return this.established; + } + } + + private final TelnetClient telnetClient; + + private String name; + private String signature; + private State state; + private SerialPortEventListener listener; + + private int baudRate = DEFAULT_BAUD_RATE; + private int dataSize = DATASIZE_8; + private int flowControlInbound = CONTROL_INBOUND_FLOW_NONE; + private int flowControlOutbound = CONTROL_OUTBOUND_FLOW_NONE; + private int parity = RFC2217.PARITY_NONE; + private int stopSize = STOPSIZE_1; + + private boolean cd; + private boolean cts; + private boolean dsr; + private boolean dtr; + private boolean ri; + private boolean rts; + + private int lineStateNotify; // which line state changes we notify listener about + private int lineStateMask; // which line state changes access server notifies us about + private int lineStateLast; // most recent line state rec'd from access server + private int modemStateNotify; // which modem state changes we notify listener about + private int modemStateMask = MODEMSTATE_ALWAYS_MONITOR; // which modem state changes access server notifies us about + private int modemStateLast; // most recent modem state rec'd from access server + + /** + * Constructor. + */ + public TelnetSerialPort() { + this.state = State.INITIAL; + this.name = getClass().getSimpleName(); + this.signature = "jvser v" + Version.JVSER_VERSION; + this.telnetClient = this.createTelnetClient(); + this.telnetClient.registerInputListener(new TelnetInputListener() { + + @Override + public void telnetInputAvailable() { + boolean notify; + synchronized (TelnetSerialPort.this) { + notify = (TelnetSerialPort.this.lineStateNotify & LINESTATE_DATA_READY) != 0; + } + if (notify) + TelnetSerialPort.this.sendEvent(SerialPortEvent.DATA_AVAILABLE); + } + }); + } + + /** + * Get the descriptive name of this client (used for logging purposes). + */ + @Override public String getName() { - return this.name; - } - - /** - * Set the descriptive name of this client (used for logging purposes). - */ - public void setName(String name) { - this.name = name; - } - - /** - * Get the signature sent to the remote server at connection time. - * By default, the signature is the name of this class. - */ - public String getSignature() { - return this.signature; - } - - /** - * Set the signature sent to the remote server at connection time. - * - * @param signature signature string, or {@code null} (or empty string) to not send a signature - */ - public void setSignature(String signature) { - this.signature = signature; - } - - /** - * Get the {@link TelnetClient} associated with this instance. - */ - public TelnetClient getTelnetClient() { - return this.telnetClient; - } - - /** - * Construct and configure the {@link TelnetClient} to be used for this instance. - */ - protected TelnetClient createTelnetClient() { - TelnetClient tc = new TelnetClient(DEFAULT_TERMINAL_TYPE); - tc.setReaderThread(true); // allows immediate option negotiation - try { - tc.addOptionHandler(new TerminalTypeOptionHandler(DEFAULT_TERMINAL_TYPE, false, false, true, false)); - tc.addOptionHandler(new EchoOptionHandler(false, false, false, false)); - tc.addOptionHandler(new SuppressGAOptionHandler(true, true, true, true)); - tc.addOptionHandler(new TransmitBinaryOptionHandler(true, true, true, true)); - tc.addOptionHandler(new ComPortOptionHandler(this)); - } catch (IOException e) { - throw new RuntimeException("unexpected exception", e); - } catch (InvalidTelnetOptionException e) { - throw new RuntimeException("unexpected exception", e); - } - return tc; - } - - // We wrap the telnet port's InputStream in a NotifyInputStream so we can detect when there - // is new data available to be read. It would be nice if the TelnetClient provided a way to - // notify us directly, but it doesn't, so we have to use this hack. - @Override - public synchronized InputStream getInputStream() throws IOException { - this.state.checkNotClosed(); - return this.telnetClient.getInputStream(); - } - - @Override - public synchronized OutputStream getOutputStream() throws IOException { - this.state.checkNotClosed(); - return this.telnetClient.getOutputStream(); - } - - @Override - public synchronized void close() { - if (this.state == State.CLOSED) - return; - this.state = State.CLOSED; - try { - this.telnetClient.disconnect(); - } catch (IOException e) { - // - } - } - - @Override - public synchronized int getBaudRate() { - this.state.checkNotClosed(); - return this.baudRate; - } - - @Override - public synchronized int getDataBits() { - this.state.checkNotClosed(); - switch (this.dataSize) { - case DATASIZE_5: - return DATABITS_5; - case DATASIZE_6: - return DATABITS_6; - case DATASIZE_7: - return DATABITS_7; - case DATASIZE_8: - return DATABITS_8; - default: - throw new RuntimeException("impossible case"); - } - } - - @Override - public synchronized int getStopBits() { - this.state.checkNotClosed(); - switch (this.stopSize) { - case STOPSIZE_1: - return STOPBITS_1; - case STOPSIZE_2: - return STOPBITS_2; - case STOPSIZE_1_5: - return STOPBITS_1_5; - default: - throw new RuntimeException("impossible case"); - } - } - - @Override - public synchronized int getParity() { - this.state.checkNotClosed(); - switch (this.parity) { - case RFC2217.PARITY_NONE: - return SerialPort.PARITY_NONE; - case RFC2217.PARITY_ODD: - return SerialPort.PARITY_ODD; - case RFC2217.PARITY_EVEN: - return SerialPort.PARITY_EVEN; - case RFC2217.PARITY_MARK: - return SerialPort.PARITY_MARK; - case RFC2217.PARITY_SPACE: - return SerialPort.PARITY_SPACE; - default: - throw new RuntimeException("impossible case"); - } - } - - @Override - public void sendBreak(int millis) { - CommandList commandList = new CommandList(2); - synchronized (this) { - this.state.checkNotClosed(); - if (this.state != State.ESTABLISHED) - return; - commandList.add(new ControlCommand(true, CONTROL_BREAK_ON)); - commandList.add(new ControlCommand(true, CONTROL_BREAK_OFF)); - } - commandList.send(); - } - - @Override - public void setFlowControlMode(int flowControl) throws UnsupportedCommOperationException { - - // Validate bit combination - if ((flowControl & (FLOWCONTROL_RTSCTS_OUT | FLOWCONTROL_XONXOFF_OUT)) == (FLOWCONTROL_RTSCTS_OUT | FLOWCONTROL_XONXOFF_OUT) - || (flowControl & (FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_XONXOFF_IN)) == (FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_XONXOFF_IN)) - throw new UnsupportedCommOperationException("invalid flow control value " + flowControl); - - // Apply changes - CommandList commandList = new CommandList(2); - synchronized (this) { - this.state.checkNotClosed(); - - // Convert to RFC 2217 values - int previousFlowControlOutbound = this.flowControlOutbound; - int previousFlowControlInbound = this.flowControlInbound; - this.flowControlOutbound = (flowControl & FLOWCONTROL_RTSCTS_OUT) != 0 ? CONTROL_OUTBOUND_FLOW_HARDWARE : - (flowControl & FLOWCONTROL_XONXOFF_OUT) != 0 ? CONTROL_OUTBOUND_FLOW_XON_XOFF : CONTROL_OUTBOUND_FLOW_NONE; - this.flowControlInbound = (flowControl & FLOWCONTROL_RTSCTS_IN) != 0 ? CONTROL_INBOUND_FLOW_HARDWARE : - (flowControl & FLOWCONTROL_XONXOFF_IN) != 0 ? CONTROL_INBOUND_FLOW_XON_XOFF : CONTROL_INBOUND_FLOW_NONE; - - // Update server (outbound first per RFC 2217) - if (this.flowControlOutbound != previousFlowControlOutbound && this.state.isEstablished()) - commandList.add(new ControlCommand(true, this.flowControlOutbound)); - if (this.flowControlInbound != previousFlowControlInbound && this.state.isEstablished()) - commandList.add(new ControlCommand(true, this.flowControlInbound)); - } - commandList.send(); - } - - @Override - public synchronized int getFlowControlMode() { - this.state.checkNotClosed(); - int value = FLOWCONTROL_NONE; - switch (this.flowControlOutbound) { - case CONTROL_OUTBOUND_FLOW_HARDWARE: - value |= FLOWCONTROL_RTSCTS_OUT; - break; - case CONTROL_OUTBOUND_FLOW_XON_XOFF: - value |= FLOWCONTROL_XONXOFF_OUT; - break; - default: - break; - } - switch (this.flowControlInbound) { - case CONTROL_INBOUND_FLOW_HARDWARE: - value |= FLOWCONTROL_RTSCTS_IN; - break; - case CONTROL_INBOUND_FLOW_XON_XOFF: - value |= FLOWCONTROL_XONXOFF_IN; - break; - default: - break; - } - return value; - } - - @Override - public void setSerialPortParams(int baudRate, int dataBits, int stopBits, int parity) - throws UnsupportedCommOperationException { - CommandList commandList = new CommandList(4); - synchronized (this) { - this.state.checkNotClosed(); - - // Validate parameters and convert to RFC 2217 values - if (baudRate <= 0) - throw new UnsupportedCommOperationException("invalid baud rate " + baudRate); - switch (dataBits) { - case DATABITS_5: - dataBits = DATASIZE_5; - break; - case DATABITS_6: - dataBits = DATASIZE_6; - break; - case DATABITS_7: - dataBits = DATASIZE_7; - break; - case DATABITS_8: - dataBits = DATASIZE_8; - break; - default: - throw new UnsupportedCommOperationException("invalid data bits " + dataBits); - } - switch (stopBits) { - case STOPBITS_1: - stopBits = STOPSIZE_1; - break; - case STOPBITS_2: - stopBits = STOPSIZE_2; - break; - case STOPBITS_1_5: - stopBits = STOPSIZE_1_5; - break; - default: - throw new UnsupportedCommOperationException("invalid stop bits " + stopBits); - } - switch (parity) { - case SerialPort.PARITY_NONE: - parity = RFC2217.PARITY_NONE; - break; - case SerialPort.PARITY_ODD: - parity = RFC2217.PARITY_ODD; - break; - case SerialPort.PARITY_EVEN: - parity = RFC2217.PARITY_EVEN; - break; - case SerialPort.PARITY_MARK: - parity = RFC2217.PARITY_MARK; - break; - case SerialPort.PARITY_SPACE: - parity = RFC2217.PARITY_SPACE; - break; - default: - throw new UnsupportedCommOperationException("invalid parity " + parity); - } - - // Update my state - boolean changed = false; - if (this.baudRate != baudRate) { - this.baudRate = baudRate; - changed = true; - } - if (this.dataSize != dataBits) { - this.dataSize = dataBits; - changed = true; - } - if (this.stopSize != stopBits) { - this.stopSize = stopBits; - changed = true; - } - if (this.parity != parity) { - this.parity = parity; - changed = true; - } - - // Update access server if there was a change - if (changed && this.state.isEstablished()) - this.addSerialPortGeometry(commandList); - } - commandList.send(); - } - - @Override - public void setDTR(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (this.dtr != value) { - this.dtr = value; - if (this.state.isEstablished()) - commandList.add(new ControlCommand(true, this.dtr ? CONTROL_DTR_ON : CONTROL_DTR_OFF)); - } - } - commandList.send(); - } - - @Override - public synchronized boolean isDTR() { - this.state.checkNotClosed(); - return this.dtr; - } - - @Override - public void setRTS(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (this.rts != value) { - this.rts = value; - if (this.state.isEstablished()) - commandList.add(new ControlCommand(true, this.rts ? CONTROL_RTS_ON : CONTROL_RTS_OFF)); - } - } - commandList.send(); - } - - @Override - public synchronized boolean isRTS() { - this.state.checkNotClosed(); - return this.rts; - } - - @Override - public synchronized boolean isCTS() { - this.state.checkNotClosed(); - return this.cts; - } - - @Override - public synchronized boolean isDSR() { - this.state.checkNotClosed(); - return this.dsr; - } - - @Override - public synchronized boolean isRI() { - this.state.checkNotClosed(); - return this.ri; - } - - @Override - public synchronized boolean isCD() { - this.state.checkNotClosed(); - return this.cd; - } - - // This is invoked by the ComPortOptionHandler once the server has agreed to accept COM-PORT-OPTION subnegotiation commands - - void startSubnegotiation() { - CommandList commandList = new CommandList(12); - synchronized (this) { - - // Update state - this.state.checkNotClosed(); - this.state = State.ESTABLISHED; - - // Request signature from peer - commandList.add(new SignatureCommand(true)); - - // Send signature if desired - if (this.signature != null && this.signature.length() > 0) - commandList.add(new SignatureCommand(true, this.signature)); - - // Send all configuration information - this.addSerialPortGeometry(commandList); - commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); - commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); - commandList.add(new ControlCommand(true, this.flowControlInbound)); - commandList.add(new ControlCommand(true, this.flowControlOutbound)); - commandList.add(new ControlCommand(true, this.dtr ? CONTROL_DTR_ON : CONTROL_DTR_OFF)); - commandList.add(new ControlCommand(true, this.rts ? CONTROL_RTS_ON : CONTROL_RTS_OFF)); - } - commandList.send(); - } - - // Method to send serial port "geometry" in the order recommended by RFC 2217 (section 2) - - private void addSerialPortGeometry(CommandList commandList) { - commandList.add(new BaudRateCommand(true, this.baudRate)); - commandList.add(new DataSizeCommand(true, this.dataSize)); - commandList.add(new ParityCommand(true, this.parity)); - commandList.add(new StopSizeCommand(true, this.stopSize)); - } - - // This is invoked by the ComPortOptionHandler when we receive a command from the server - - void handleCommand(ComPortCommand command) { - - // Incoming commands should be server versions - if (!command.isServerCommand()) { - return; - } - - // Handle command - command.visit(new AbstractComPortCommandSwitch() { - - @Override - public void caseBaudRate(BaudRateCommand command) { - synchronized (TelnetSerialPort.this) { - TelnetSerialPort.this.baudRate = command.getBaudRate(); - } - } - - @Override - public void caseDataSize(DataSizeCommand command) { - synchronized (TelnetSerialPort.this) { - TelnetSerialPort.this.dataSize = command.getDataSize(); - } - } - - @Override - public void caseParity(ParityCommand command) { - synchronized (TelnetSerialPort.this) { - TelnetSerialPort.this.parity = command.getParity(); - } - } - - @Override - public void caseStopSize(StopSizeCommand command) { - synchronized (TelnetSerialPort.this) { - TelnetSerialPort.this.stopSize = command.getStopSize(); - } - } - - @Override - public void caseControl(ControlCommand command) { - synchronized (TelnetSerialPort.this) { - switch (command.getControl()) { - case CONTROL_OUTBOUND_FLOW_NONE: - case CONTROL_OUTBOUND_FLOW_XON_XOFF: - case CONTROL_OUTBOUND_FLOW_HARDWARE: - TelnetSerialPort.this.flowControlOutbound = command.getControl(); - break; - case CONTROL_INBOUND_FLOW_NONE: - case CONTROL_INBOUND_FLOW_XON_XOFF: - case CONTROL_INBOUND_FLOW_HARDWARE: - TelnetSerialPort.this.flowControlInbound = command.getControl(); - break; - case CONTROL_DTR_ON: - TelnetSerialPort.this.dtr = true; - break; - case CONTROL_DTR_OFF: - TelnetSerialPort.this.dtr = false; - break; - case CONTROL_RTS_ON: - TelnetSerialPort.this.rts = true; - break; - case CONTROL_RTS_OFF: - TelnetSerialPort.this.rts = false; - break; - default: - break; - } - } - } - - @Override - public void caseNotifyLineState(NotifyLineStateCommand command) { - int lineState = command.getLineState(); - int notify; - synchronized (TelnetSerialPort.this) { - notify = TelnetSerialPort.this.lineStateNotify; - TelnetSerialPort.this.lineStateLast = lineState; - } - notify &= lineState; // notify only if bit is equal to 1 - if ((notify & LINESTATE_TRANSFER_SHIFT_REGISTER_EMPTY) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.OUTPUT_BUFFER_EMPTY); - if ((notify & LINESTATE_BREAK_DETECT) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.BI); - if ((notify & LINESTATE_FRAMING_ERROR) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.FE); - if ((notify & LINESTATE_PARITY_ERROR) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.PE); - if ((notify & LINESTATE_OVERRUN_ERROR) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.OE); - } - - @Override - public void caseNotifyModemState(NotifyModemStateCommand command) { - int modemState = command.getModemState(); - int notify; - synchronized (TelnetSerialPort.this) { - notify = TelnetSerialPort.this.modemStateNotify; - TelnetSerialPort.this.modemStateLast = modemState; - } - notify &= modemState ^ modemStateLast; // notify only if bit has changed - if ((notify & MODEMSTATE_CARRIER_DETECT) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.CD, (modemState & MODEMSTATE_CARRIER_DETECT) != 0); - if ((notify & MODEMSTATE_RING_INDICATOR) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.RI, (modemState & MODEMSTATE_RING_INDICATOR) != 0); - if ((notify & MODEMSTATE_DSR) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.DSR, (modemState & MODEMSTATE_DSR) != 0); - if ((notify & MODEMSTATE_CTS) != 0) - TelnetSerialPort.this.sendEvent(SerialPortEvent.CTS, (modemState & MODEMSTATE_CTS) != 0); - } - - @Override - protected void caseDefault(ComPortCommand command) { - // - } - }); - } - - // Listener management - - @Override - public synchronized void addEventListener(SerialPortEventListener listener) throws TooManyListenersException { - this.state.checkNotClosed(); - if (this.listener != null) - throw new TooManyListenersException("only one listener allowed"); - this.listener = listener; - } - - @Override - public synchronized void removeEventListener() { - this.listener = null; - } - - // Notification configuration - - @Override - public synchronized void notifyOnDataAvailable(boolean value) { - this.state.checkNotClosed(); - updateLineStateMask(LINESTATE_DATA_READY, value); - } - - @Override - public void notifyOnOutputEmpty(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (this.updateLineStateMask(LINESTATE_TRANSFER_SHIFT_REGISTER_EMPTY, value) && this.state.isEstablished()) - commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); - } - commandList.send(); - } - - @Override - public void notifyOnCTS(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (updateModemStateMask(MODEMSTATE_CTS, value) && this.state.isEstablished()) - commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); - } - commandList.send(); - } - - @Override - public void notifyOnDSR(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (updateModemStateMask(MODEMSTATE_DSR, value) && this.state.isEstablished()) - commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); - } - commandList.send(); - } - - @Override - public void notifyOnRingIndicator(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (updateModemStateMask(MODEMSTATE_RING_INDICATOR, value) && this.state.isEstablished()) - commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); - } - commandList.send(); - } - - @Override - public void notifyOnCarrierDetect(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (updateModemStateMask(MODEMSTATE_CARRIER_DETECT, value) && this.state.isEstablished()) - commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); - } - commandList.send(); - } - - @Override - public void notifyOnOverrunError(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (this.updateLineStateMask(LINESTATE_OVERRUN_ERROR, value) && this.state.isEstablished()) - commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); - } - commandList.send(); - } - - @Override - public void notifyOnParityError(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (this.updateLineStateMask(LINESTATE_PARITY_ERROR, value) && this.state.isEstablished()) - commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); - } - commandList.send(); - } - - @Override - public void notifyOnFramingError(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (this.updateLineStateMask(LINESTATE_FRAMING_ERROR, value) && this.state.isEstablished()) - commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); - } - commandList.send(); - } - - @Override - public void notifyOnBreakInterrupt(boolean value) { - CommandList commandList = new CommandList(1); - synchronized (this) { - this.state.checkNotClosed(); - if (this.updateLineStateMask(LINESTATE_BREAK_DETECT, value) && this.state.isEstablished()) - commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); - } - commandList.send(); - } - - // Methods for sending event notifications - - private void sendEvent(int type) { - this.sendEvent(type, true); - } - - private void sendEvent(int type, boolean newValue) { - SerialPortEventListener currentListener; - synchronized (this) { - currentListener = this.listener; - } - if (currentListener == null) - return; - SerialPortEvent event = new SerialPortEvent(this, type, !newValue, newValue); - try { - currentListener.serialEvent(event); - } catch (Exception e) { - log.error(this.name + ": exception from listener " + listener + ":", e); - } - } - - // Internal utility methods - - // Send a subnegotiation to the peer - private void sendSubnegotiation(ComPortCommand command) { - assert !Thread.holdsLock(TelnetSerialPort.this); // otherwise we can deadlock - try { - this.telnetClient.sendSubnegotiation(command.getBytes()); - } catch (IOException e) { - log.error(this.name + ": exception sending subcommand:", e); - } - } - - // Update line state notifications; return true if we need to send new mask to access server - private synchronized boolean updateLineStateMask(int bit, boolean value) { - int previous = this.lineStateMask; - if (value) { - this.lineStateNotify |= bit; - this.lineStateMask |= bit; - } else { - this.lineStateNotify &= ~bit; - this.lineStateMask &= ~bit; - } - this.lineStateMask &= ~LINESTATE_NEVER_MONITOR; - return this.lineStateMask != previous; - } - - // Update modem state notifications; return true if we need to send new mask to access server - private synchronized boolean updateModemStateMask(int bit, boolean value) { - int previous = this.modemStateMask; - if (value) { - this.modemStateNotify |= bit; - this.modemStateMask |= bit; - } else { - this.modemStateNotify &= ~bit; - this.modemStateMask &= ~bit; - } - this.modemStateMask |= MODEMSTATE_ALWAYS_MONITOR; - return this.modemStateMask != previous; - } - - // Unimplemented methods - - @Override - public synchronized void enableReceiveThreshold(int threshold) throws UnsupportedCommOperationException { - this.state.checkNotClosed(); - throw new UnsupportedCommOperationException(); - } - - @Override - public synchronized void disableReceiveThreshold() { - this.state.checkNotClosed(); - } - - @Override - public synchronized boolean isReceiveThresholdEnabled() { - this.state.checkNotClosed(); - return false; - } - - @Override - public synchronized int getReceiveThreshold() { - this.state.checkNotClosed(); - return 0; - } - - @Override - public synchronized void enableReceiveTimeout(int timeout) throws UnsupportedCommOperationException { - this.state.checkNotClosed(); - throw new UnsupportedCommOperationException(); - } - - @Override - public synchronized void disableReceiveTimeout() { - this.state.checkNotClosed(); - } - - @Override - public synchronized boolean isReceiveTimeoutEnabled() { - this.state.checkNotClosed(); - return false; - } - - @Override - public synchronized int getReceiveTimeout() { - this.state.checkNotClosed(); - return 0; - } - - @Override - public synchronized void enableReceiveFraming(int framingByte) throws UnsupportedCommOperationException { - this.state.checkNotClosed(); - throw new UnsupportedCommOperationException(); - } - - @Override - public synchronized void disableReceiveFraming() { - this.state.checkNotClosed(); - } - - @Override - public synchronized boolean isReceiveFramingEnabled() { - this.state.checkNotClosed(); - return false; - } - - @Override - public synchronized int getReceiveFramingByte() { - this.state.checkNotClosed(); - return 0; - } - - @Override - public synchronized void setInputBufferSize(int size) { - this.state.checkNotClosed(); - } - - @Override - public synchronized int getInputBufferSize() { - this.state.checkNotClosed(); - return 0; - } - - @Override - public synchronized void setOutputBufferSize(int size) { - this.state.checkNotClosed(); - } - - @Override - public synchronized int getOutputBufferSize() { - this.state.checkNotClosed(); - return 0; - } - - // Utility class - - @SuppressWarnings("serial") - private class CommandList extends ArrayList { - - public CommandList(int size) { - super(size); - } - - public void send() { - for (ComPortCommand command : this) - TelnetSerialPort.this.sendSubnegotiation(command); - this.clear(); - } - } + return this.name; + } + + /** + * Set the descriptive name of this client (used for logging purposes). + */ + public void setName(String name) { + this.name = name; + } + + /** + * Get the signature sent to the remote server at connection time. By default, + * the signature is the name of this class. + */ + public String getSignature() { + return this.signature; + } + + /** + * Set the signature sent to the remote server at connection time. + * + * @param signature + * signature string, or {@code null} (or empty string) to not send a + * signature + */ + public void setSignature(String signature) { + this.signature = signature; + } + + /** + * Get the {@link TelnetClient} associated with this instance. + */ + public TelnetClient getTelnetClient() { + return this.telnetClient; + } + + /** + * Construct and configure the {@link TelnetClient} to be used for this + * instance. + */ + protected TelnetClient createTelnetClient() { + TelnetClient tc = new TelnetClient(DEFAULT_TERMINAL_TYPE); + tc.setReaderThread(true); // allows immediate option negotiation + try { + tc.addOptionHandler(new TerminalTypeOptionHandler(DEFAULT_TERMINAL_TYPE, false, false, true, false)); + tc.addOptionHandler(new EchoOptionHandler(false, false, false, false)); + tc.addOptionHandler(new SuppressGAOptionHandler(true, true, true, true)); + tc.addOptionHandler(new TransmitBinaryOptionHandler(true, true, true, true)); + tc.addOptionHandler(new ComPortOptionHandler(this)); + } catch (IOException e) { + throw new RuntimeException("unexpected exception", e); + } catch (InvalidTelnetOptionException e) { + throw new RuntimeException("unexpected exception", e); + } + return tc; + } + + // We wrap the telnet port's InputStream in a NotifyInputStream so we can detect + // when there + // is new data available to be read. It would be nice if the TelnetClient + // provided a way to + // notify us directly, but it doesn't, so we have to use this hack. + @Override + public synchronized InputStream getInputStream() throws IOException { + this.state.checkNotClosed(); + return this.telnetClient.getInputStream(); + } + + @Override + public synchronized OutputStream getOutputStream() throws IOException { + this.state.checkNotClosed(); + return this.telnetClient.getOutputStream(); + } + + @Override + public synchronized void close() { + if (this.state == State.CLOSED) + return; + this.state = State.CLOSED; + try { + this.telnetClient.disconnect(); + } catch (IOException e) { + // + } + } + + @Override + public synchronized int getBaudRate() { + this.state.checkNotClosed(); + return this.baudRate; + } + + @Override + public synchronized int getDataBits() { + this.state.checkNotClosed(); + switch (this.dataSize) { + case DATASIZE_5 : + return DATABITS_5; + case DATASIZE_6 : + return DATABITS_6; + case DATASIZE_7 : + return DATABITS_7; + case DATASIZE_8 : + return DATABITS_8; + default : + throw new RuntimeException("impossible case"); + } + } + + @Override + public synchronized int getStopBits() { + this.state.checkNotClosed(); + switch (this.stopSize) { + case STOPSIZE_1 : + return STOPBITS_1; + case STOPSIZE_2 : + return STOPBITS_2; + case STOPSIZE_1_5 : + return STOPBITS_1_5; + default : + throw new RuntimeException("impossible case"); + } + } + + @Override + public synchronized int getParity() { + this.state.checkNotClosed(); + switch (this.parity) { + case RFC2217.PARITY_NONE : + return SerialPort.PARITY_NONE; + case RFC2217.PARITY_ODD : + return SerialPort.PARITY_ODD; + case RFC2217.PARITY_EVEN : + return SerialPort.PARITY_EVEN; + case RFC2217.PARITY_MARK : + return SerialPort.PARITY_MARK; + case RFC2217.PARITY_SPACE : + return SerialPort.PARITY_SPACE; + default : + throw new RuntimeException("impossible case"); + } + } + + @Override + public void sendBreak(int millis) { + CommandList commandList = new CommandList(2); + synchronized (this) { + this.state.checkNotClosed(); + if (this.state != State.ESTABLISHED) + return; + commandList.add(new ControlCommand(true, CONTROL_BREAK_ON)); + commandList.add(new ControlCommand(true, CONTROL_BREAK_OFF)); + } + commandList.send(); + } + + @Override + public void setFlowControlMode(int flowControl) throws UnsupportedCommOperationException { + + // Validate bit combination + if ((flowControl & (FLOWCONTROL_RTSCTS_OUT | FLOWCONTROL_XONXOFF_OUT)) == (FLOWCONTROL_RTSCTS_OUT + | FLOWCONTROL_XONXOFF_OUT) + || (flowControl & (FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_XONXOFF_IN)) == (FLOWCONTROL_RTSCTS_IN + | FLOWCONTROL_XONXOFF_IN)) + throw new UnsupportedCommOperationException("invalid flow control value " + flowControl); + + // Apply changes + CommandList commandList = new CommandList(2); + synchronized (this) { + this.state.checkNotClosed(); + + // Convert to RFC 2217 values + int previousFlowControlOutbound = this.flowControlOutbound; + int previousFlowControlInbound = this.flowControlInbound; + this.flowControlOutbound = (flowControl & FLOWCONTROL_RTSCTS_OUT) != 0 + ? CONTROL_OUTBOUND_FLOW_HARDWARE + : (flowControl & FLOWCONTROL_XONXOFF_OUT) != 0 + ? CONTROL_OUTBOUND_FLOW_XON_XOFF + : CONTROL_OUTBOUND_FLOW_NONE; + this.flowControlInbound = (flowControl & FLOWCONTROL_RTSCTS_IN) != 0 + ? CONTROL_INBOUND_FLOW_HARDWARE + : (flowControl & FLOWCONTROL_XONXOFF_IN) != 0 + ? CONTROL_INBOUND_FLOW_XON_XOFF + : CONTROL_INBOUND_FLOW_NONE; + + // Update server (outbound first per RFC 2217) + if (this.flowControlOutbound != previousFlowControlOutbound && this.state.isEstablished()) + commandList.add(new ControlCommand(true, this.flowControlOutbound)); + if (this.flowControlInbound != previousFlowControlInbound && this.state.isEstablished()) + commandList.add(new ControlCommand(true, this.flowControlInbound)); + } + commandList.send(); + } + + @Override + public synchronized int getFlowControlMode() { + this.state.checkNotClosed(); + int value = FLOWCONTROL_NONE; + switch (this.flowControlOutbound) { + case CONTROL_OUTBOUND_FLOW_HARDWARE : + value |= FLOWCONTROL_RTSCTS_OUT; + break; + case CONTROL_OUTBOUND_FLOW_XON_XOFF : + value |= FLOWCONTROL_XONXOFF_OUT; + break; + default : + break; + } + switch (this.flowControlInbound) { + case CONTROL_INBOUND_FLOW_HARDWARE : + value |= FLOWCONTROL_RTSCTS_IN; + break; + case CONTROL_INBOUND_FLOW_XON_XOFF : + value |= FLOWCONTROL_XONXOFF_IN; + break; + default : + break; + } + return value; + } + + @Override + public void setSerialPortParams(int baudRate, int dataBits, int stopBits, int parity) + throws UnsupportedCommOperationException { + CommandList commandList = new CommandList(4); + synchronized (this) { + this.state.checkNotClosed(); + + // Validate parameters and convert to RFC 2217 values + if (baudRate <= 0) + throw new UnsupportedCommOperationException("invalid baud rate " + baudRate); + switch (dataBits) { + case DATABITS_5 : + dataBits = DATASIZE_5; + break; + case DATABITS_6 : + dataBits = DATASIZE_6; + break; + case DATABITS_7 : + dataBits = DATASIZE_7; + break; + case DATABITS_8 : + dataBits = DATASIZE_8; + break; + default : + throw new UnsupportedCommOperationException("invalid data bits " + dataBits); + } + switch (stopBits) { + case STOPBITS_1 : + stopBits = STOPSIZE_1; + break; + case STOPBITS_2 : + stopBits = STOPSIZE_2; + break; + case STOPBITS_1_5 : + stopBits = STOPSIZE_1_5; + break; + default : + throw new UnsupportedCommOperationException("invalid stop bits " + stopBits); + } + switch (parity) { + case SerialPort.PARITY_NONE : + parity = RFC2217.PARITY_NONE; + break; + case SerialPort.PARITY_ODD : + parity = RFC2217.PARITY_ODD; + break; + case SerialPort.PARITY_EVEN : + parity = RFC2217.PARITY_EVEN; + break; + case SerialPort.PARITY_MARK : + parity = RFC2217.PARITY_MARK; + break; + case SerialPort.PARITY_SPACE : + parity = RFC2217.PARITY_SPACE; + break; + default : + throw new UnsupportedCommOperationException("invalid parity " + parity); + } + + // Update my state + boolean changed = false; + if (this.baudRate != baudRate) { + this.baudRate = baudRate; + changed = true; + } + if (this.dataSize != dataBits) { + this.dataSize = dataBits; + changed = true; + } + if (this.stopSize != stopBits) { + this.stopSize = stopBits; + changed = true; + } + if (this.parity != parity) { + this.parity = parity; + changed = true; + } + + // Update access server if there was a change + if (changed && this.state.isEstablished()) + this.addSerialPortGeometry(commandList); + } + commandList.send(); + } + + @Override + public void setDTR(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (this.dtr != value) { + this.dtr = value; + if (this.state.isEstablished()) + commandList.add(new ControlCommand(true, this.dtr ? CONTROL_DTR_ON : CONTROL_DTR_OFF)); + } + } + commandList.send(); + } + + @Override + public synchronized boolean isDTR() { + this.state.checkNotClosed(); + return this.dtr; + } + + @Override + public void setRTS(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (this.rts != value) { + this.rts = value; + if (this.state.isEstablished()) + commandList.add(new ControlCommand(true, this.rts ? CONTROL_RTS_ON : CONTROL_RTS_OFF)); + } + } + commandList.send(); + } + + @Override + public synchronized boolean isRTS() { + this.state.checkNotClosed(); + return this.rts; + } + + @Override + public synchronized boolean isCTS() { + this.state.checkNotClosed(); + return this.cts; + } + + @Override + public synchronized boolean isDSR() { + this.state.checkNotClosed(); + return this.dsr; + } + + @Override + public synchronized boolean isRI() { + this.state.checkNotClosed(); + return this.ri; + } + + @Override + public synchronized boolean isCD() { + this.state.checkNotClosed(); + return this.cd; + } + + // This is invoked by the ComPortOptionHandler once the server has agreed to + // accept COM-PORT-OPTION subnegotiation commands + + void startSubnegotiation() { + CommandList commandList = new CommandList(12); + synchronized (this) { + + // Update state + this.state.checkNotClosed(); + this.state = State.ESTABLISHED; + + // Request signature from peer + commandList.add(new SignatureCommand(true)); + + // Send signature if desired + if (this.signature != null && this.signature.length() > 0) + commandList.add(new SignatureCommand(true, this.signature)); + + // Send all configuration information + this.addSerialPortGeometry(commandList); + commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); + commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); + commandList.add(new ControlCommand(true, this.flowControlInbound)); + commandList.add(new ControlCommand(true, this.flowControlOutbound)); + commandList.add(new ControlCommand(true, this.dtr ? CONTROL_DTR_ON : CONTROL_DTR_OFF)); + commandList.add(new ControlCommand(true, this.rts ? CONTROL_RTS_ON : CONTROL_RTS_OFF)); + } + commandList.send(); + } + + // Method to send serial port "geometry" in the order recommended by RFC 2217 + // (section 2) + + private void addSerialPortGeometry(CommandList commandList) { + commandList.add(new BaudRateCommand(true, this.baudRate)); + commandList.add(new DataSizeCommand(true, this.dataSize)); + commandList.add(new ParityCommand(true, this.parity)); + commandList.add(new StopSizeCommand(true, this.stopSize)); + } + + // This is invoked by the ComPortOptionHandler when we receive a command from + // the server + + void handleCommand(ComPortCommand command) { + + // Incoming commands should be server versions + if (!command.isServerCommand()) { + return; + } + + // Handle command + command.visit(new AbstractComPortCommandSwitch() { + + @Override + public void caseBaudRate(BaudRateCommand command) { + synchronized (TelnetSerialPort.this) { + TelnetSerialPort.this.baudRate = command.getBaudRate(); + } + } + + @Override + public void caseDataSize(DataSizeCommand command) { + synchronized (TelnetSerialPort.this) { + TelnetSerialPort.this.dataSize = command.getDataSize(); + } + } + + @Override + public void caseParity(ParityCommand command) { + synchronized (TelnetSerialPort.this) { + TelnetSerialPort.this.parity = command.getParity(); + } + } + + @Override + public void caseStopSize(StopSizeCommand command) { + synchronized (TelnetSerialPort.this) { + TelnetSerialPort.this.stopSize = command.getStopSize(); + } + } + + @Override + public void caseControl(ControlCommand command) { + synchronized (TelnetSerialPort.this) { + switch (command.getControl()) { + case CONTROL_OUTBOUND_FLOW_NONE : + case CONTROL_OUTBOUND_FLOW_XON_XOFF : + case CONTROL_OUTBOUND_FLOW_HARDWARE : + TelnetSerialPort.this.flowControlOutbound = command.getControl(); + break; + case CONTROL_INBOUND_FLOW_NONE : + case CONTROL_INBOUND_FLOW_XON_XOFF : + case CONTROL_INBOUND_FLOW_HARDWARE : + TelnetSerialPort.this.flowControlInbound = command.getControl(); + break; + case CONTROL_DTR_ON : + TelnetSerialPort.this.dtr = true; + break; + case CONTROL_DTR_OFF : + TelnetSerialPort.this.dtr = false; + break; + case CONTROL_RTS_ON : + TelnetSerialPort.this.rts = true; + break; + case CONTROL_RTS_OFF : + TelnetSerialPort.this.rts = false; + break; + default : + break; + } + } + } + + @Override + public void caseNotifyLineState(NotifyLineStateCommand command) { + int lineState = command.getLineState(); + int notify; + synchronized (TelnetSerialPort.this) { + notify = TelnetSerialPort.this.lineStateNotify; + TelnetSerialPort.this.lineStateLast = lineState; + } + notify &= lineState; // notify only if bit is equal to 1 + if ((notify & LINESTATE_TRANSFER_SHIFT_REGISTER_EMPTY) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.OUTPUT_BUFFER_EMPTY); + if ((notify & LINESTATE_BREAK_DETECT) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.BI); + if ((notify & LINESTATE_FRAMING_ERROR) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.FE); + if ((notify & LINESTATE_PARITY_ERROR) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.PE); + if ((notify & LINESTATE_OVERRUN_ERROR) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.OE); + } + + @Override + public void caseNotifyModemState(NotifyModemStateCommand command) { + int modemState = command.getModemState(); + int notify; + synchronized (TelnetSerialPort.this) { + notify = TelnetSerialPort.this.modemStateNotify; + TelnetSerialPort.this.modemStateLast = modemState; + } + notify &= modemState ^ modemStateLast; // notify only if bit has changed + if ((notify & MODEMSTATE_CARRIER_DETECT) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.CD, (modemState & MODEMSTATE_CARRIER_DETECT) != 0); + if ((notify & MODEMSTATE_RING_INDICATOR) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.RI, (modemState & MODEMSTATE_RING_INDICATOR) != 0); + if ((notify & MODEMSTATE_DSR) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.DSR, (modemState & MODEMSTATE_DSR) != 0); + if ((notify & MODEMSTATE_CTS) != 0) + TelnetSerialPort.this.sendEvent(SerialPortEvent.CTS, (modemState & MODEMSTATE_CTS) != 0); + } + + @Override + protected void caseDefault(ComPortCommand command) { + // + } + }); + } + + // Listener management + + @Override + public synchronized void addEventListener(SerialPortEventListener listener) throws TooManyListenersException { + this.state.checkNotClosed(); + if (this.listener != null) + throw new TooManyListenersException("only one listener allowed"); + this.listener = listener; + } + + @Override + public synchronized void removeEventListener() { + this.listener = null; + } + + // Notification configuration + + @Override + public synchronized void notifyOnDataAvailable(boolean value) { + this.state.checkNotClosed(); + updateLineStateMask(LINESTATE_DATA_READY, value); + } + + @Override + public void notifyOnOutputEmpty(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (this.updateLineStateMask(LINESTATE_TRANSFER_SHIFT_REGISTER_EMPTY, value) && this.state.isEstablished()) + commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); + } + commandList.send(); + } + + @Override + public void notifyOnCTS(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (updateModemStateMask(MODEMSTATE_CTS, value) && this.state.isEstablished()) + commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); + } + commandList.send(); + } + + @Override + public void notifyOnDSR(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (updateModemStateMask(MODEMSTATE_DSR, value) && this.state.isEstablished()) + commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); + } + commandList.send(); + } + + @Override + public void notifyOnRingIndicator(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (updateModemStateMask(MODEMSTATE_RING_INDICATOR, value) && this.state.isEstablished()) + commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); + } + commandList.send(); + } + + @Override + public void notifyOnCarrierDetect(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (updateModemStateMask(MODEMSTATE_CARRIER_DETECT, value) && this.state.isEstablished()) + commandList.add(new ModemStateMaskCommand(true, this.modemStateMask)); + } + commandList.send(); + } + + @Override + public void notifyOnOverrunError(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (this.updateLineStateMask(LINESTATE_OVERRUN_ERROR, value) && this.state.isEstablished()) + commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); + } + commandList.send(); + } + + @Override + public void notifyOnParityError(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (this.updateLineStateMask(LINESTATE_PARITY_ERROR, value) && this.state.isEstablished()) + commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); + } + commandList.send(); + } + + @Override + public void notifyOnFramingError(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (this.updateLineStateMask(LINESTATE_FRAMING_ERROR, value) && this.state.isEstablished()) + commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); + } + commandList.send(); + } + + @Override + public void notifyOnBreakInterrupt(boolean value) { + CommandList commandList = new CommandList(1); + synchronized (this) { + this.state.checkNotClosed(); + if (this.updateLineStateMask(LINESTATE_BREAK_DETECT, value) && this.state.isEstablished()) + commandList.add(new LineStateMaskCommand(true, this.lineStateMask)); + } + commandList.send(); + } + + // Methods for sending event notifications + + private void sendEvent(int type) { + this.sendEvent(type, true); + } + + private void sendEvent(int type, boolean newValue) { + SerialPortEventListener currentListener; + synchronized (this) { + currentListener = this.listener; + } + if (currentListener == null) + return; + SerialPortEvent event = new SerialPortEvent(this, type, !newValue, newValue); + try { + currentListener.serialEvent(event); + } catch (Exception e) { + log.error(this.name + ": exception from listener " + listener + ":", e); + } + } + + // Internal utility methods + + // Send a subnegotiation to the peer + private void sendSubnegotiation(ComPortCommand command) { + assert !Thread.holdsLock(TelnetSerialPort.this); // otherwise we can deadlock + try { + this.telnetClient.sendSubnegotiation(command.getBytes()); + } catch (IOException e) { + log.error(this.name + ": exception sending subcommand:", e); + } + } + + // Update line state notifications; return true if we need to send new mask to + // access server + private synchronized boolean updateLineStateMask(int bit, boolean value) { + int previous = this.lineStateMask; + if (value) { + this.lineStateNotify |= bit; + this.lineStateMask |= bit; + } else { + this.lineStateNotify &= ~bit; + this.lineStateMask &= ~bit; + } + this.lineStateMask &= ~LINESTATE_NEVER_MONITOR; + return this.lineStateMask != previous; + } + + // Update modem state notifications; return true if we need to send new mask to + // access server + private synchronized boolean updateModemStateMask(int bit, boolean value) { + int previous = this.modemStateMask; + if (value) { + this.modemStateNotify |= bit; + this.modemStateMask |= bit; + } else { + this.modemStateNotify &= ~bit; + this.modemStateMask &= ~bit; + } + this.modemStateMask |= MODEMSTATE_ALWAYS_MONITOR; + return this.modemStateMask != previous; + } + + // Unimplemented methods + + @Override + public synchronized void enableReceiveThreshold(int threshold) throws UnsupportedCommOperationException { + this.state.checkNotClosed(); + throw new UnsupportedCommOperationException(); + } + + @Override + public synchronized void disableReceiveThreshold() { + this.state.checkNotClosed(); + } + + @Override + public synchronized boolean isReceiveThresholdEnabled() { + this.state.checkNotClosed(); + return false; + } + + @Override + public synchronized int getReceiveThreshold() { + this.state.checkNotClosed(); + return 0; + } + + @Override + public synchronized void enableReceiveTimeout(int timeout) throws UnsupportedCommOperationException { + this.state.checkNotClosed(); + throw new UnsupportedCommOperationException(); + } + + @Override + public synchronized void disableReceiveTimeout() { + this.state.checkNotClosed(); + } + + @Override + public synchronized boolean isReceiveTimeoutEnabled() { + this.state.checkNotClosed(); + return false; + } + + @Override + public synchronized int getReceiveTimeout() { + this.state.checkNotClosed(); + return 0; + } + + @Override + public synchronized void enableReceiveFraming(int framingByte) throws UnsupportedCommOperationException { + this.state.checkNotClosed(); + throw new UnsupportedCommOperationException(); + } + + @Override + public synchronized void disableReceiveFraming() { + this.state.checkNotClosed(); + } + + @Override + public synchronized boolean isReceiveFramingEnabled() { + this.state.checkNotClosed(); + return false; + } + + @Override + public synchronized int getReceiveFramingByte() { + this.state.checkNotClosed(); + return 0; + } + + @Override + public synchronized void setInputBufferSize(int size) { + this.state.checkNotClosed(); + } + + @Override + public synchronized int getInputBufferSize() { + this.state.checkNotClosed(); + return 0; + } + + @Override + public synchronized void setOutputBufferSize(int size) { + this.state.checkNotClosed(); + } + + @Override + public synchronized int getOutputBufferSize() { + this.state.checkNotClosed(); + return 0; + } + + // Utility class + + @SuppressWarnings("serial") + private class CommandList extends ArrayList { + + public CommandList(int size) { + super(size); + } + + public void send() { + for (ComPortCommand command : this) + TelnetSerialPort.this.sendSubnegotiation(command); + this.clear(); + } + } @Override public int getBaudBase() throws UnsupportedCommOperationException, IOException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); return baudRate; } @Override public boolean getCallOutHangup() throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); throw new UnsupportedCommOperationException(); } @Override public int getDivisor() throws UnsupportedCommOperationException, IOException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); return 1; } @Override public byte getEndOfInputChar() throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); return 0x04; } @Override public boolean getLowLatency() throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); throw new UnsupportedCommOperationException(); } @Override public byte getParityErrorChar() throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); throw new UnsupportedCommOperationException(); } @Override public String getUARTType() throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); throw new UnsupportedCommOperationException(); } @Override public boolean setBaudBase(int arg0) throws UnsupportedCommOperationException, IOException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); return true; } @Override public boolean setCallOutHangup(boolean arg0) throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); throw new UnsupportedCommOperationException(); } @Override public boolean setDivisor(int arg0) throws UnsupportedCommOperationException, IOException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); return true; } @Override public boolean setEndOfInputChar(byte arg0) throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); return true; } @Override public boolean setLowLatency() throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); throw new UnsupportedCommOperationException(); } @Override public boolean setParityErrorChar(byte arg0) throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); throw new UnsupportedCommOperationException(); } @Override public boolean setUARTType(String arg0, boolean arg1) throws UnsupportedCommOperationException { - this.state.checkNotClosed(); + this.state.checkNotClosed(); throw new UnsupportedCommOperationException(); } } - diff --git a/test/src/test/NRJavaSerialTest.java b/test/src/test/NRJavaSerialTest.java index 26a5f214..2cb6de72 100644 --- a/test/src/test/NRJavaSerialTest.java +++ b/test/src/test/NRJavaSerialTest.java @@ -1,100 +1,99 @@ -/*------------------------------------------------------------------------- -| RXTX License v 2.1 - LGPL v 2.1 + Linking Over Controlled Interface. -| RXTX is a native interface to serial ports in java. -| Copyright 1997-2007 by Trent Jarvi tjarvi@qbang.org and others who -| actually wrote it. See individual source files for more information. -| -| A copy of the LGPL v 2.1 may be found at -| http://www.gnu.org/licenses/lgpl.txt on March 4th 2007. A copy is -| here for your convenience. -| -| This library is free software; you can redistribute it and/or -| modify it under the terms of the GNU Lesser General Public -| License as published by the Free Software Foundation; either -| version 2.1 of the License, or (at your option) any later version. -| -| This library is distributed in the hope that it will be useful, -| but WITHOUT ANY WARRANTY; without even the implied warranty of -| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -| Lesser General Public License for more details. -| -| An executable that contains no derivative of any portion of RXTX, but -| is designed to work with RXTX by being dynamically linked with it, -| is considered a "work that uses the Library" subject to the terms and -| conditions of the GNU Lesser General Public License. -| -| The following has been added to the RXTX License to remove -| any confusion about linking to RXTX. We want to allow in part what -| section 5, paragraph 2 of the LGPL does not permit in the special -| case of linking over a controlled interface. The intent is to add a -| Java Specification Request or standards body defined interface in the -| future as another exception but one is not currently available. -| -| http://www.fsf.org/licenses/gpl-faq.html#LinkingOverControlledInterface -| -| As a special exception, the copyright holders of RXTX give you -| permission to link RXTX with independent modules that communicate with -| RXTX solely through the Sun Microsytems CommAPI interface version 2, -| regardless of the license terms of these independent modules, and to copy -| and distribute the resulting combined work under terms of your choice, -| provided that every copy of the combined work is accompanied by a complete -| copy of the source code of RXTX (the version of RXTX used to produce the -| combined work), being distributed under the terms of the GNU Lesser General -| Public License plus this exception. An independent module is a -| module which is not derived from or based on RXTX. -| -| Note that people who make modified versions of RXTX are not obligated -| to grant this special exception for their modified versions; it is -| their choice whether to do so. The GNU Lesser General Public License -| gives permission to release a modified version without this exception; this -| exception also makes it possible to release a modified version which -| carries forward this exception. -| -| You should have received a copy of the GNU Lesser General Public -| License along with this library; if not, write to the Free -| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -| All trademarks belong to their respective owners. ---------------------------------------------------------------------------*/ -package test; -import java.util.Enumeration; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import gnu.io.CommPortIdentifier; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NRJavaSerialTest { - private static final Logger log = LoggerFactory.getLogger(NRJavaSerialTest.class); - - private static final Lock LOCK = new ReentrantLock(); - private static final String PORT = "/dev/ttyUSB0"; - - public static void main(String[] args) throws Exception { - Thread thread = new Thread(NRJavaSerialTest::printPortIdentifiers); - thread.start(); - Thread.sleep(2000L); - CommPortIdentifier id = CommPortIdentifier.getPortIdentifier(PORT); - id.open(NRJavaSerialTest.class.getSimpleName(), 5000); - log.info("Opened: " + PORT); - LOCK.lock(); - } - - @SuppressWarnings("unchecked") - private static void printPortIdentifiers() { - try { - for (int i=0;i<5&&!Thread.currentThread().isInterrupted();i++) { - Enumeration ids = CommPortIdentifier.getPortIdentifiers(); - log.info("--- Port Identifiers ---"); - while (ids.hasMoreElements()) { - log.info("name: " + ids.nextElement().getName()); - } - Thread.sleep(5000L); - } - } catch (InterruptedException e) { - log.error("Thread interrupted"); - } - System.exit(0); - } -} \ No newline at end of file +/*------------------------------------------------------------------------- +| RXTX License v 2.1 - LGPL v 2.1 + Linking Over Controlled Interface. +| RXTX is a native interface to serial ports in java. +| Copyright 1997-2007 by Trent Jarvi tjarvi@qbang.org and others who +| actually wrote it. See individual source files for more information. +| +| A copy of the LGPL v 2.1 may be found at +| http://www.gnu.org/licenses/lgpl.txt on March 4th 2007. A copy is +| here for your convenience. +| +| This library is free software; you can redistribute it and/or +| modify it under the terms of the GNU Lesser General Public +| License as published by the Free Software Foundation; either +| version 2.1 of the License, or (at your option) any later version. +| +| This library is distributed in the hope that it will be useful, +| but WITHOUT ANY WARRANTY; without even the implied warranty of +| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +| Lesser General Public License for more details. +| +| An executable that contains no derivative of any portion of RXTX, but +| is designed to work with RXTX by being dynamically linked with it, +| is considered a "work that uses the Library" subject to the terms and +| conditions of the GNU Lesser General Public License. +| +| The following has been added to the RXTX License to remove +| any confusion about linking to RXTX. We want to allow in part what +| section 5, paragraph 2 of the LGPL does not permit in the special +| case of linking over a controlled interface. The intent is to add a +| Java Specification Request or standards body defined interface in the +| future as another exception but one is not currently available. +| +| http://www.fsf.org/licenses/gpl-faq.html#LinkingOverControlledInterface +| +| As a special exception, the copyright holders of RXTX give you +| permission to link RXTX with independent modules that communicate with +| RXTX solely through the Sun Microsytems CommAPI interface version 2, +| regardless of the license terms of these independent modules, and to copy +| and distribute the resulting combined work under terms of your choice, +| provided that every copy of the combined work is accompanied by a complete +| copy of the source code of RXTX (the version of RXTX used to produce the +| combined work), being distributed under the terms of the GNU Lesser General +| Public License plus this exception. An independent module is a +| module which is not derived from or based on RXTX. +| +| Note that people who make modified versions of RXTX are not obligated +| to grant this special exception for their modified versions; it is +| their choice whether to do so. The GNU Lesser General Public License +| gives permission to release a modified version without this exception; this +| exception also makes it possible to release a modified version which +| carries forward this exception. +| +| You should have received a copy of the GNU Lesser General Public +| License along with this library; if not, write to the Free +| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +| All trademarks belong to their respective owners. +--------------------------------------------------------------------------*/ +package test; + +import gnu.io.CommPortIdentifier; +import java.util.Enumeration; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NRJavaSerialTest { + private static final Logger log = LoggerFactory.getLogger(NRJavaSerialTest.class); + + private static final Lock LOCK = new ReentrantLock(); + private static final String PORT = "/dev/ttyUSB0"; + + public static void main(String[] args) throws Exception { + Thread thread = new Thread(NRJavaSerialTest::printPortIdentifiers); + thread.start(); + Thread.sleep(2000L); + CommPortIdentifier id = CommPortIdentifier.getPortIdentifier(PORT); + id.open(NRJavaSerialTest.class.getSimpleName(), 5000); + log.info("Opened: " + PORT); + LOCK.lock(); + } + + @SuppressWarnings("unchecked") + private static void printPortIdentifiers() { + try { + for (int i = 0; i < 5 && !Thread.currentThread().isInterrupted(); i++) { + Enumeration ids = CommPortIdentifier.getPortIdentifiers(); + log.info("--- Port Identifiers ---"); + while (ids.hasMoreElements()) { + log.info("name: " + ids.nextElement().getName()); + } + Thread.sleep(5000L); + } + } catch (InterruptedException e) { + log.error("Thread interrupted"); + } + System.exit(0); + } +} diff --git a/test/src/test/ReadTest.java b/test/src/test/ReadTest.java index 11d33785..6ebbe43a 100644 --- a/test/src/test/ReadTest.java +++ b/test/src/test/ReadTest.java @@ -1,25 +1,22 @@ package test; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.TooManyListenersException; import gnu.io.NRSerialPort; import gnu.io.SerialPortEvent; -import gnu.io.Zystem; - +import java.io.DataInputStream; +import java.io.IOException; +import java.util.TooManyListenersException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReadTest { private static final Logger log = LoggerFactory.getLogger(ReadTest.class); - public static void main(String [] args) { + public static void main(String[] args) { String port = ""; - for(String s:NRSerialPort.getAvailableSerialPorts()){ - log.info("Availible port: "+s); - port=s; + for (String s : NRSerialPort.getAvailableSerialPorts()) { + log.info("Availible port: " + s); + port = s; } int baudRate = 115200; @@ -27,22 +24,23 @@ public static void main(String [] args) { serial.connect(); DataInputStream ins = new DataInputStream(serial.getInputStream()); try { - serial.addEventListener(ev->{ - if(ev.getEventType()==SerialPortEvent.DATA_AVAILABLE) { - //while(ins.available()==0 && !Thread.interrupted());// wait for a byte + serial.addEventListener(ev -> { + if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE) { + // while(ins.available()==0 && !Thread.interrupted());// wait for a byte try { - while(ins.available()>0) {// read all bytes - - char b = (char) ins.read(); - //outs.write((byte)b); - System.out.print(b); - + while (ins.available() > 0) {// read all bytes + + char b = (char) ins.read(); + // outs.write((byte)b); + System.out.print(b); + } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - }if(ev.getEventType()==SerialPortEvent.HARDWARE_ERROR) { + } + if (ev.getEventType() == SerialPortEvent.HARDWARE_ERROR) { log.info("Clean exit of hardware"); serial.disconnect(); } @@ -51,24 +49,24 @@ public static void main(String [] args) { // TODO Auto-generated catch block e.printStackTrace(); } - -// DataOutputStream outs = new DataOutputStream(serial.getOutputStream()); -// try{ -// byte bytes[] = new byte[10]; -// //while(ins.available()==0 && !Thread.interrupted());// wait for a byte -// while(!Thread.interrupted()) {// read all bytes -// //if(ins.available()>0) { -// //char b = (char) ins.read(); -// int back = ins.read(bytes); -// //outs.write((byte)b); -// for(int i=0;i0) { + // //char b = (char) ins.read(); + // int back = ins.read(bytes); + // //outs.write((byte)b); + // for(int i=0;i Date: Sun, 24 Jan 2021 16:51:23 +0000 Subject: [PATCH 2/2] Remove extraneous trace statements. --- src/main/c/include/SerialImp.h | 62 ----- src/main/c/include/slf4j.h | 5 - src/main/c/include/windows/win32termios.h | 7 - src/main/c/src/SerialImp.c | 227 +------------------ src/main/c/src/windows/termios.c | 102 --------- src/main/java/gnu/io/CommPort.java | 6 +- src/main/java/gnu/io/CommPortIdentifier.java | 5 - src/main/java/gnu/io/RXTXCommDriver.java | 6 - src/main/java/gnu/io/RXTXPort.java | 65 +----- 9 files changed, 5 insertions(+), 480 deletions(-) diff --git a/src/main/c/include/SerialImp.h b/src/main/c/include/SerialImp.h index 81732db2..1c0b9010 100644 --- a/src/main/c/include/SerialImp.h +++ b/src/main/c/include/SerialImp.h @@ -294,68 +294,6 @@ Trent # define SELECT select #endif /* WIN32 */ -#if defined(DEBUG_TIMING) && ! defined(WIN32) /* WIN32 does not have gettimeofday() */ -struct timeval snow, enow, seloop, eeloop; -#ifdef __APPLE__ -#define report_time_eventLoop( ) { \ - if ( seloop.tv_sec == eeloop.tv_sec && seloop.tv_usec == eeloop.tv_usec ) \ - { \ - gettimeofday(&eeloop, NULL); \ - seloop.tv_sec = eeloop.tv_sec; \ - seloop.tv_usec = eeloop.tv_usec; \ - printf("%8li sec : %8i usec\n", eeloop.tv_sec - seloop.tv_sec, eeloop.tv_usec - seloop.tv_usec); \ - } \ -} -#define report_time( ) \ -{ \ - struct timeval now; \ - gettimeofday(&now, NULL); \ - printf("%8s : %5i : %8li sec : %8i usec\n", __TIME__, __LINE__, now.tv_sec, now.tv_usec); \ -} -#define report_time_start( ) \ -{ \ - gettimeofday(&snow, NULL); \ - printf("%8s : %5i : %8li sec : %8i usec", __TIME__, __LINE__, snow.tv_sec, snow.tv_usec); \ -} -#define report_time_end( ) \ -{ \ - gettimeofday(&enow, NULL); \ - printf("%8li sec : %8i usec\n", enow.tv_sec - snow.tv_sec, enow.tv_sec - snow.tv_sec?snow.tv_usec-enow.tv_usec:enow.tv_usec - snow.tv_usec); \ -} -#else /* ! __APPLE__ */ -#define report_time_eventLoop( ) { \ -if ( seloop.tv_sec == eeloop.tv_sec && seloop.tv_usec == eeloop.tv_usec ) \ -{ \ -gettimeofday(&eeloop, NULL); \ -seloop.tv_sec = eeloop.tv_sec; \ -seloop.tv_usec = eeloop.tv_usec; \ -printf("%8li sec : %8li usec\n", eeloop.tv_sec - seloop.tv_sec, eeloop.tv_usec - seloop.tv_usec); \ -} \ -} -#define report_time( ) \ -{ \ -struct timeval now; \ -gettimeofday(&now, NULL); \ -printf("%8s : %5i : %8li sec : %8li usec\n", __TIME__, __LINE__, now.tv_sec, now.tv_usec); \ -} -#define report_time_start( ) \ -{ \ -gettimeofday(&snow, NULL); \ -printf("%8s : %5i : %8li sec : %8li usec", __TIME__, __LINE__, snow.tv_sec, snow.tv_usec); \ -} -#define report_time_end( ) \ -{ \ -gettimeofday(&enow, NULL); \ -printf("%8li sec : %8li usec\n", enow.tv_sec - snow.tv_sec, enow.tv_sec - snow.tv_sec?snow.tv_usec-enow.tv_usec:enow.tv_usec - snow.tv_usec); \ -} -#endif /* __APPLE__ */ -#else /* ! DEBUG_TIMING || WIN32 */ -#define report_time_eventLoop( ){}; -#define report_time( ) {} -#define report_time_start( ) {} -#define report_time_end( ) {} -#endif /* DEBUG_TIMING && ! WIN32 */ - /* allow people to override the directories */ /* #define USER_LOCK_DIRECTORY "/home/tjarvi/1.5/build" */ #ifdef USER_LOCK_DIRECTORY diff --git a/src/main/c/include/slf4j.h b/src/main/c/include/slf4j.h index 2b1aaa5f..0734c639 100644 --- a/src/main/c/include/slf4j.h +++ b/src/main/c/include/slf4j.h @@ -91,11 +91,6 @@ typedef enum LogLevel LOG_LEVELS } LogLevel; -/** \brief Trace-level log to denote entering a function. */ -#define ENTER(x) slf4j_log(LOG_TRACE, "entering " x) -/** \brief Trace-level log to denote leaving a function. */ -#define LEAVE(x) slf4j_log(LOG_TRACE, "leaving " x) - /** * \brief Log a ERROR-level message through SLF4J. * diff --git a/src/main/c/include/windows/win32termios.h b/src/main/c/include/windows/win32termios.h index b4d6a96a..2cb1e914 100644 --- a/src/main/c/include/windows/win32termios.h +++ b/src/main/c/include/windows/win32termios.h @@ -60,13 +60,6 @@ #include #include #include -#ifdef TRACE -#define ENTER(x) report("entering "x" \n"); -#define LEAVE(x) report("leaving "x" \n"); -#else -#define ENTER(x) -#define LEAVE(x) -#endif /* TRACE */ #if defined(_MSC_VER) # define snprintf _snprintf #endif diff --git a/src/main/c/src/SerialImp.c b/src/main/c/src/SerialImp.c index 9e82cb91..3ea37dff 100644 --- a/src/main/c/src/SerialImp.c +++ b/src/main/c/src/SerialImp.c @@ -181,13 +181,11 @@ cfmakeraw int cfmakeraw ( struct termios *term ) { - ENTER( "cfmakeraw" ); term->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON); term->c_oflag &= ~OPOST; term->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN); term->c_cflag &= ~(CSIZE|PARENB); term->c_cflag |= CS8; - LEAVE( "cfmakeraw" ); return( 0 ); } #endif /* __sun__ || __hpux__ */ @@ -290,21 +288,15 @@ JNIEXPORT void JNICALL RXTXPort(Initialize)( sigaction(SIGIO, &new_action, NULL); } #endif /* !WIN32 */ - ENTER( "RXTXPort:Initialize" ); #ifdef PRERELEASE /* this is just for avoiding confusion while testing new libraries */ printf("RXTX Prerelease for testing Thu Feb 21 19:31:38\n"); #endif /* PRERELEASE */ -#if defined(DEBUG_TIMING) && ! defined(WIN32) - /* WIN32 does not have gettimeofday() */ - gettimeofday(&seloop, NULL); -#endif /* DEBUG_TIMING && ! WIN32 */ #if defined(DEBUG) && defined(__linux__) && defined(UTS_RELEASE) /* Lets let people who upgraded kernels know they may have problems */ if (uname (&name) == -1) { report( "RXTX WARNING: cannot get system name\n" ); - LEAVE( "RXTXPort:Initialize" ); return; } if(strcmp(name.release,UTS_RELEASE)!=0) @@ -314,7 +306,6 @@ JNIEXPORT void JNICALL RXTXPort(Initialize)( report( message ); getchar(); } - LEAVE( "RXTXPort:Initialize" ); #endif /* DEBUG && __linux__ && UTS_RELEASE */ } @@ -677,7 +668,6 @@ JNIEXPORT jint JNICALL RXTXPort(open)( const char *filename; jclass jclazz = (*env)->GetObjectClass( env, jobj ); jfieldID jfid = (*env)->GetFieldID( env, jclazz, "pid", "I" ); - report_time_start( ); if( !jfid ) { (*env)->ExceptionDescribe( env ); @@ -703,7 +693,6 @@ JNIEXPORT jint JNICALL RXTXPort(open)( system_does_not_lock Win32 */ - ENTER( "RXTXPort:open" ); //report_warning("\nopen() Attempting to lock: "); if ( LOCK( filename, pid ) ) { @@ -769,13 +758,10 @@ JNIEXPORT jint JNICALL RXTXPort(open)( (*env)->ReleaseStringUTFChars( env, jstr, filename ); sprintf( message, "open: fd returned is %i\n", fd ); report_verbose( message ); - LEAVE( "RXTXPort:open" ); - report_time_end( ); return (jint)fd; fail: (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:open" ); throw_java_exception( env, PORT_IN_USE_EXCEPTION, "open", strerror( errno ) ); return -1; @@ -799,7 +785,6 @@ JNIEXPORT void JNICALL RXTXPort(nativeClose)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 ); jclass jclazz = (*env)->GetObjectClass( env, jobj ); - report_time_start( ); pid = get_java_var( env, jobj,"pid","I" ); //report_warning("nativeClose() Attempting Close pid\n"); @@ -824,7 +809,6 @@ JNIEXPORT void JNICALL RXTXPort(nativeClose)( JNIEnv *env, system_does_not_unlock Win32 */ - ENTER( "RXTXPort:nativeClose" ); if (fd > 0) { report_verbose("nativeClose: discarding remaining data (tcflush)\n"); @@ -855,8 +839,6 @@ JNIEXPORT void JNICALL RXTXPort(nativeClose)( JNIEnv *env, (*env)->DeleteLocalRef( env, jclazz ); report_verbose("nativeClose: release filename\n"); (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeClose" ); - report_time_end( ); return; } @@ -990,9 +972,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeSetSerialPortParams)( int fd = get_java_var( env, jobj,"fd","I" ); int cspeed = translate_speed( env, speed ); - ENTER( "RXTXPort:nativeSetSerialPortParams" ); - report_time_start( ); - if (cspeed < 0 ) { report(" invalid cspeed\n"); @@ -1009,7 +988,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeSetSerialPortParams)( if( set_port_params( env, fd, cspeed, dataBits, stopBits, parity ) ) { report("set_port_params failed\n"); - LEAVE( "RXTXPort:nativeSetSerialPortParams" ); /* For some reason the native exceptions are not being caught. Moving this to the Java side fixed the issue. taj. @@ -1019,8 +997,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeSetSerialPortParams)( return(1); } - LEAVE( "RXTXPort:nativeSetSerialPortParams" ); - report_time_end( ); return(0); } @@ -1037,7 +1013,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeSetSerialPortParams)( ----------------------------------------------------------*/ int translate_speed( JNIEnv *env, jint speed ) { - LEAVE( "RXTXPort:translate_speed" ); switch( speed ) { case 0: return B0; case 50: return B50; @@ -1117,7 +1092,6 @@ int translate_speed( JNIEnv *env, jint speed ) if( speed >= 0 ) return speed; else { - LEAVE( "RXTXPort:translate_speed: Error condition" ); return -1; } } @@ -1134,7 +1108,6 @@ int translate_data_bits( JNIEnv *env, tcflag_t *cflag, jint dataBits ) { int temp = (*cflag) & ~CSIZE; - ENTER( "translate_date_bits" ); switch( dataBits ) { case JDATABITS_5: (*cflag) = temp | CS5; @@ -1150,7 +1123,6 @@ int translate_data_bits( JNIEnv *env, tcflag_t *cflag, jint dataBits ) return 0; } - LEAVE( "RXTXPort:translate_date_bits" ); /* For some reason the native exceptions are not being caught. Moving this to the Java side fixed the issue. taj. @@ -1172,11 +1144,9 @@ int translate_data_bits( JNIEnv *env, tcflag_t *cflag, jint dataBits ) ----------------------------------------------------------*/ int translate_stop_bits( JNIEnv *env, tcflag_t *cflag, jint stopBits ) { - ENTER( "translate_stop_bits" ); switch( stopBits ) { case STOPBITS_1: (*cflag) &= ~CSTOPB; - LEAVE( "RXTXPort:translate_stop_bits" ); return 0; /* ok.. lets try putting it in and see if anyone notices */ case STOPBITS_1_5: @@ -1186,11 +1156,9 @@ int translate_stop_bits( JNIEnv *env, tcflag_t *cflag, jint stopBits ) return 0; case STOPBITS_2: (*cflag) |= CSTOPB; - LEAVE( "RXTXPort:translate_stop_bits" ); return 0; } - LEAVE( "RXTXPort:translate_stop_bits" ); /* For some reason the native exceptions are not being caught. Moving this to the Java side fixed the issue. taj. @@ -1273,37 +1241,30 @@ JNIEXPORT jint JNICALL RXTXPort(nativeGetParity)(JNIEnv *env, jobject jobj, jint ----------------------------------------------------------*/ int translate_parity( JNIEnv *env, tcflag_t *cflag, jint parity ) { - ENTER( "translate_parity" ); #ifdef CMSPAR (*cflag) &= ~(PARENB | PARODD | CMSPAR ); #endif /* CMSPAR */ switch( parity ) { case JPARITY_NONE: - LEAVE( "translate_parity" ); return 0; case JPARITY_EVEN: (*cflag) |= PARENB; - LEAVE( "translate_parity" ); return 0; case JPARITY_ODD: (*cflag) |= PARENB | PARODD; - LEAVE( "translate_parity" ); return 0; #ifdef CMSPAR case JPARITY_MARK: (*cflag) |= PARENB | PARODD | CMSPAR; - LEAVE( "translate_parity" ); return 0; case JPARITY_SPACE: (*cflag) |= PARENB | CMSPAR; - LEAVE( "translate_parity" ); return 0; #endif /* CMSPAR */ default: printf("Parity missed %i\n", (int) parity ); } - LEAVE( "translate_parity" ); /* For some reason the native exceptions are not being caught. Moving this to the Java side fixed the issue. taj. @@ -1414,10 +1375,8 @@ void finalize_threads( struct event_info_struct *eis ) /* used to shut down any remaining write threads */ eis->output_buffer_empty_flag = 0; - ENTER("finalize_threads\n"); /* need to clean up again after working events */ - LEAVE("---------------- finalize_threads ---------------"); #endif /* TIOCSERGETLSR & !WIN32 */ } @@ -1452,7 +1411,6 @@ int init_threads( struct event_info_struct *eis ) struct sigaction newaction, oldaction; pthread_t tid; - report_time_start( ); report("init_threads: start\n"); /* ignore child thread status changes */ sigemptyset(&newmask); @@ -1498,7 +1456,6 @@ int init_threads( struct event_info_struct *eis ) report_verbose("init_threads: set eis\n"); (*eis->env)->SetLongField(eis->env, *eis->jobj, jeis, ( size_t ) eis ); report_verbose("init_threads: stop\n"); - report_time_end( ); return( 1 ); } @@ -1536,8 +1493,6 @@ JNIEXPORT void JNICALL RXTXPort(writeByte)( JNIEnv *env, int count; #endif /* __sun__ */ - report_time_start(); - ENTER( "RXTXPort:writeByte" ); do { sprintf( msg, "writeByte %c>>\n", byte ); report( msg ); @@ -1571,10 +1526,8 @@ JNIEXPORT void JNICALL RXTXPort(writeByte)( JNIEnv *env, #endif sprintf( msg, "RXTXPort:writeByte %i\n", result ); report( msg ); - LEAVE( "RXTXPort:writeByte" ); if(result >= 0) { - report_time_end(); return; } fail: @@ -1623,8 +1576,6 @@ JNIEXPORT void JNICALL RXTXPort(writeArray)( JNIEnv *env, (*env)->ReleaseByteArrayElements( env, jbarray, body, 0 ); */ /* return; OH CRAP */ - report_time_start(); - ENTER( "writeArray" ); /* warning Roy Rogers */ /* sprintf( message, "::::RXTXPort:writeArray(%s);\n", (char *) body ); @@ -1676,8 +1627,6 @@ JNIEXPORT void JNICALL RXTXPort(writeArray)( JNIEnv *env, Things just start spinning out of control after that. */ - LEAVE( "RXTXPort:writeArray" ); - report_time_end(); fail: if( result < 0 ) throw_java_exception( env, IO_EXCEPTION, "writeArray", strerror( errno ) ); @@ -1707,8 +1656,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeDrain)( JNIEnv *env, char message[80]; - ENTER( "SerialImp.c:drain()" ); - report_time_start( ); do { report_verbose( "nativeDrain: trying tcdrain\n" ); result=tcdrain(fd); @@ -1721,7 +1668,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeDrain)( JNIEnv *env, /* FIXME: No time to test on all OS's for production */ return( JNI_TRUE ); #endif /* __sun__ */ - LEAVE( "RXTXPort:drain()" ); if( result ) throw_java_exception( env, IO_EXCEPTION, "nativeDrain", strerror( errno ) ); if( interrupted ) return( JNI_FALSE ); @@ -1738,7 +1684,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeDrain)( JNIEnv *env, build_threadsafe_eis( env, &jobj, eis ); send_event( &myeis, SPE_OUTPUT_BUFFER_EMPTY, 1 ); } - report_time_end( ); return( JNI_FALSE ); } @@ -1756,11 +1701,7 @@ JNIEXPORT void JNICALL RXTXPort(sendBreak)( JNIEnv *env, slf4j_setup_instance(env, jobj); int fd = get_java_var( env, jobj,"fd","I" ); - report_time_start( ); - ENTER( "RXTXPort:sendBreak()" ); tcsendbreak( fd, (int)( duration / 250 ) ); - report_time_end( ); - LEAVE( "RXTXPort:sendBreak()" ); } /*---------------------------------------------------------- @@ -1781,12 +1722,9 @@ JNIEXPORT jint JNICALL RXTXPort(NativegetReceiveTimeout)( int fd = get_java_var( env, jobj,"fd","I" ); struct termios ttyset; - ENTER( "RXTXPort:nativegetRecieveTimeout()" ); if( tcgetattr( fd, &ttyset ) < 0 ) goto fail; - LEAVE( "RXTXPort:nativegetRecieveTimeout()" ); return(ttyset.c_cc[ VTIME ] * 100); fail: - LEAVE( "RXTXPort:nativegetRecieveTimeout()" ); throw_java_exception( env, IO_EXCEPTION, "getReceiveTimeout", strerror( errno ) ); return -1; @@ -1809,12 +1747,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(NativeisReceiveTimeoutEnabled)( int fd = get_java_var( env, jobj,"fd","I" ); struct termios ttyset; - ENTER( "RXTXPort:NativeisRecieveTimeoutEnabled()" ); if( tcgetattr( fd, &ttyset ) < 0 ) goto fail; - LEAVE( "RXTXPort:NativeisRecieveTimeoutEnabled()" ); return(ttyset.c_cc[ VTIME ] > 0 ? JNI_TRUE:JNI_FALSE); fail: - LEAVE( "RXTXPort:NativeisRecieveTimeoutEnabled()" ); throw_java_exception( env, IO_EXCEPTION, "isReceiveTimeoutEnabled", strerror( errno ) ); return JNI_FALSE; @@ -1839,11 +1774,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(isDSR)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:isDSR" ); ioctl( fd, TIOCMGET, &result ); sprintf( message, "RXTXPort:isDSR returns %i\n", result & TIOCM_DSR ); report( message ); - LEAVE( "RXTXPort:isDSR" ); if( result & TIOCM_DSR ) return JNI_TRUE; else return JNI_FALSE; } @@ -1871,10 +1804,8 @@ JNIEXPORT jboolean JNICALL RXTXPort(isCD)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:isCD" ); ioctl( fd, TIOCMGET, &result ); sprintf( message, "RXTXPort:isCD returns %i\n", result & TIOCM_CD ); - LEAVE( "RXTXPort:isCD" ); if( result & TIOCM_CD ) return JNI_TRUE; else return JNI_FALSE; } @@ -1898,11 +1829,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(isCTS)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:isCTS" ); ioctl( fd, TIOCMGET, &result ); sprintf( message, "RXTXPort:isCTS returns %i\n", result & TIOCM_CTS ); report( message ); - LEAVE( "RXTXPort:isCTS" ); if( result & TIOCM_CTS ) return JNI_TRUE; else return JNI_FALSE; } @@ -1926,11 +1855,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(isRI)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:isRI" ); ioctl( fd, TIOCMGET, &result ); sprintf( message, "RXTXPort:isRI returns %i\n", result & TIOCM_RI ); report( message ); - LEAVE( "RXTXPort:isRI" ); if( result & TIOCM_RI ) return JNI_TRUE; else return JNI_FALSE; } @@ -1954,11 +1881,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(isRTS)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:isRTS" ); ioctl( fd, TIOCMGET, &result ); sprintf( message, "RXTXPort:isRTS returns %i\n", result & TIOCM_RTS ); report( message ); - LEAVE( "RXTXPort:isRTS" ); if( result & TIOCM_RTS ) return JNI_TRUE; else return JNI_FALSE; } @@ -1983,14 +1908,12 @@ JNIEXPORT void JNICALL RXTXPort(setRTS)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:setRTS" ); ioctl( fd, TIOCMGET, &result ); if( state == JNI_TRUE ) result |= TIOCM_RTS; else result &= ~TIOCM_RTS; ioctl( fd, TIOCMSET, &result ); sprintf( message, "setRTS( %i )\n", state ); report( message ); - LEAVE( "RXTXPort:setRTS" ); return; } @@ -2014,7 +1937,6 @@ JNIEXPORT void JNICALL RXTXPort(setDSR)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:setDSR()" ); ioctl( fd, TIOCMGET, &result ); sprintf( message, "setDSR( %i )\n", state ); @@ -2023,7 +1945,6 @@ JNIEXPORT void JNICALL RXTXPort(setDSR)( JNIEnv *env, ioctl( fd, TIOCMSET, &result ); sprintf( message, "setDSR( %i )\n", state ); report_verbose( message ); - LEAVE( "RXTXPort:setDSR()" ); return; } @@ -2046,11 +1967,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(isDTR)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:isDTR" ); ioctl( fd, TIOCMGET, &result ); sprintf( message, "isDTR( ) returns %i\n", result& TIOCM_DTR ); report( message ); - LEAVE( "RXTXPort:isDTR" ); if( result & TIOCM_DTR ) return JNI_TRUE; else return JNI_FALSE; } @@ -2074,14 +1993,12 @@ JNIEXPORT void JNICALL RXTXPort(setDTR)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); char message[80]; - ENTER( "RXTXPort:setDTR" ); ioctl( fd, TIOCMGET, &result ); if( state == JNI_TRUE ) result |= TIOCM_DTR; else result &= ~TIOCM_DTR; ioctl( fd, TIOCMSET, &result ); sprintf( message, "setDTR( %i )\n", state ); report_verbose( message ); - LEAVE( "RXTXPort:setDTR" ); return; } /*---------------------------------------------------------- @@ -2340,7 +2257,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetDSR) (JNIEnv *env, int result; const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 ); - ENTER( "RXTXPort:nativeStaticSetDSR" ); #ifndef WIN32 pid = getpid(); #endif /* WIN32 */ @@ -2374,11 +2290,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetDSR) (JNIEnv *env, /* dont close the port. Its not clear if the DSR would remain high */ (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetDSR" ); return( JNI_TRUE ); fail: (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetDSR" ); return( JNI_FALSE ); } @@ -2408,7 +2322,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetRTS) (JNIEnv *env, int result; const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 ); - ENTER( "RXTXPort:nativeStaticSetRTS" ); #ifndef WIN32 pid = getpid(); #endif /* WIN32 */ @@ -2442,11 +2355,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetRTS) (JNIEnv *env, /* dont close the port. Its not clear if the RTS would remain high */ (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetRTS" ); return( JNI_TRUE ); fail: (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetRTS" ); return( JNI_FALSE ); } @@ -2476,8 +2387,6 @@ JNIEXPORT void JNICALL RXTXPort(nativeStaticSetSerialPortParams) (JNIEnv *env, const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 ); int cspeed = translate_speed( env, baudrate ); - - ENTER( "RXTXPort:nativeStaticSetSerialPortParams" ); #ifndef WIN32 pid = getpid(); #endif /* WIN32 */ @@ -2497,7 +2406,6 @@ JNIEXPORT void JNICALL RXTXPort(nativeStaticSetSerialPortParams) (JNIEnv *env, if ( fd < 0 ) { (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetSerialPortParams" ); throw_java_exception( env, UNSUPPORTED_COMM_OPERATION, "nativeStaticSetSerialPortParams", strerror( errno ) ); return; @@ -2514,7 +2422,6 @@ JNIEXPORT void JNICALL RXTXPort(nativeStaticSetSerialPortParams) (JNIEnv *env, if( set_port_params( env, fd, cspeed, dataBits, stopBits, parity ) ) { (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStatic SetSerialPortParams" ); throw_java_exception( env, UNSUPPORTED_COMM_OPERATION, "nativeStaticSetSerialPortParams", strerror( errno ) ); return; @@ -2528,11 +2435,9 @@ JNIEXPORT void JNICALL RXTXPort(nativeStaticSetSerialPortParams) (JNIEnv *env, /* dont close the port. */ (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetSerialPortParams" ); return; fail: (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetSerialPortParams" ); return; } @@ -2562,7 +2467,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetDTR) (JNIEnv *env, const char *filename = (*env)->GetStringUTFChars( env, jstr, 0 ); int result; - ENTER( "RXTXPort:nativeStaticSetDTR" ); #ifndef WIN32 pid = getpid(); #endif /* WIN32 */ @@ -2596,11 +2500,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticSetDTR) (JNIEnv *env, /* dont close the port. Its not clear if the DTR would remain high */ (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetDTR" ); return( JNI_TRUE ); fail: (*env)->ReleaseStringUTFChars( env, jstr, filename ); - LEAVE( "RXTXPort:nativeStaticSetDTR" ); return( JNI_FALSE ); } @@ -2625,7 +2527,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsRTS)( JNIEnv *env, int fd = find_preopened_ports( filename ); char message[80]; - ENTER( "RXTXPort:nativeStaticIsRTS" ); if( !fd ) { /* Exception? FIXME */ @@ -2634,7 +2535,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsRTS)( JNIEnv *env, ioctl( fd, TIOCMGET, &result ); sprintf( message, "nativeStaticIsRTS( ) returns %i\n", result& TIOCM_RTS ); report( message ); - LEAVE( "RXTXPort:nativeStaticIsRTS" ); if( result & TIOCM_RTS ) return JNI_TRUE; else return JNI_FALSE; } @@ -2659,7 +2559,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsDSR)( JNIEnv *env, int fd = find_preopened_ports( filename ); char message[80]; - ENTER( "RXTXPort:nativeStaticIsDSR" ); if( !fd ) { /* Exception? FIXME */ @@ -2668,7 +2567,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsDSR)( JNIEnv *env, ioctl( fd, TIOCMGET, &result ); sprintf( message, "nativeStaticIsDSR( ) returns %i\n", result& TIOCM_DSR ); report( message ); - LEAVE( "RXTXPort:nativeStaticIsDSR" ); if( result & TIOCM_DSR ) return JNI_TRUE; else return JNI_FALSE; } @@ -2693,7 +2591,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsDTR)( JNIEnv *env, int fd = find_preopened_ports( filename ); char message[80]; - ENTER( "RXTXPort:nativeStaticIsDTR" ); if( !fd ) { /* Exception? FIXME */ @@ -2702,7 +2599,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsDTR)( JNIEnv *env, ioctl( fd, TIOCMGET, &result ); sprintf( message, "nativeStaticIsDTR( ) returns %i\n", result& TIOCM_DTR ); report( message ); - LEAVE( "RXTXPort:nativeStaticIsDTR" ); if( result & TIOCM_DTR ) return JNI_TRUE; else return JNI_FALSE; } @@ -2727,7 +2623,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsCD)( JNIEnv *env, int fd = find_preopened_ports( filename ); char message[80]; - ENTER( "RXTXPort:nativeStaticIsCD" ); if( !fd ) { /* Exception? FIXME */ @@ -2736,7 +2631,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsCD)( JNIEnv *env, ioctl( fd, TIOCMGET, &result ); sprintf( message, "nativeStaticIsCD( ) returns %i\n", result& TIOCM_CD ); report( message ); - LEAVE( "RXTXPort:nativeStaticIsCD" ); if( result & TIOCM_CD ) return JNI_TRUE; else return JNI_FALSE; } @@ -2761,7 +2655,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsCTS)( JNIEnv *env, int fd = find_preopened_ports( filename ); char message[80]; - ENTER( "RXTXPort:nativeStaticIsCTS" ); if( !fd ) { /* Exception? FIXME */ @@ -2770,7 +2663,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsCTS)( JNIEnv *env, ioctl( fd, TIOCMGET, &result ); sprintf( message, "nativeStaticIsCTS( ) returns %i\n", result& TIOCM_CTS ); report( message ); - LEAVE( "RXTXPort:nativeStaticIsCTS" ); if( result & TIOCM_CTS ) return JNI_TRUE; else return JNI_FALSE; } @@ -2795,7 +2687,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsRI)( JNIEnv *env, int fd = find_preopened_ports( filename ); char message[80]; - ENTER( "RXTXPort:nativeStaticIsRI" ); if( !fd ) { /* Exception? FIXME */ @@ -2804,7 +2695,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeStaticIsRI)( JNIEnv *env, ioctl( fd, TIOCMGET, &result ); sprintf( message, "nativeStaticRI( ) returns %i\n", result& TIOCM_RI ); report( message ); - LEAVE( "RXTXPort:nativeStaticIsRI" ); if( result & TIOCM_RI ) return JNI_TRUE; else return JNI_FALSE; } @@ -2828,7 +2718,6 @@ JNIEXPORT jint JNICALL RXTXPort(nativeStaticGetBaudRate)( JNIEnv *env, jobject j int baudrate; (*env)->ReleaseStringUTFChars( env, jstr, filename ); - ENTER( "RXTXPort:nativeStaticGetBaudRate" ); if( !fd ) { /* Exception? FIXME */ @@ -2881,7 +2770,6 @@ JNIEXPORT jint JNICALL RXTXPort(nativeStaticGetDataBits)( JNIEnv *env, jobject j struct termios ttyset; (*env)->ReleaseStringUTFChars( env, jstr, filename ); - ENTER( "RXTXPort:nativeStaticGetDataBits" ); if( !fd ) { /* Exception? FIXME */ @@ -2918,7 +2806,6 @@ JNIEXPORT jint JNICALL RXTXPort(nativeStaticGetParity)( JNIEnv *env, jobject job struct termios ttyset; (*env)->ReleaseStringUTFChars( env, jstr, filename ); - ENTER( "RXTXPort:nativeStaticGetParity" ); if( !fd ) { /* Exception? FIXME */ @@ -2962,7 +2849,6 @@ JNIEXPORT jint JNICALL RXTXPort(nativeStaticGetStopBits)( JNIEnv *env, jobject j struct termios ttyset; (*env)->ReleaseStringUTFChars( env, jstr, filename ); - ENTER( "RXTXPort:nativeStaticGetStopBits" ); if( !fd ) { /* Exception? FIXME */ @@ -3009,7 +2895,6 @@ JNIEXPORT jbyte JNICALL RXTXPort(nativeGetParityErrorChar)( JNIEnv *env, unsigned int result = 0; - ENTER( "nativeGetParityErrorChar" ); #ifdef WIN32 result = ( jbyte ) termiosGetParityErrorChar( get_java_var(env, jobj, "fd", "I" ) ); @@ -3021,7 +2906,6 @@ JNIEXPORT jbyte JNICALL RXTXPort(nativeGetParityErrorChar)( JNIEnv *env, result = ( jint ) '\0'; #endif /* WIN32 */ - LEAVE( "nativeGetParityErrorChar" ); return( ( jbyte ) result ); } @@ -3042,12 +2926,9 @@ JNIEXPORT jbyte JNICALL RXTXPort(nativeGetEndOfInputChar)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); struct termios ttyset; - ENTER( "nativeGetEndOfInputChar" ); if( tcgetattr( fd, &ttyset ) < 0 ) goto fail; - LEAVE( "nativeGetEndOfInputChar" ); return( (jbyte) ttyset.c_cc[VEOF] ); fail: - LEAVE( "nativeGetEndOfInputChar" ); report( "nativeGetEndOfInputChar failed\n" ); return( ( jbyte ) -1 ); } @@ -3073,12 +2954,9 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeSetParityErrorChar)( JNIEnv *env, #ifdef WIN32 int fd = get_java_var( env, jobj,"fd","I" ); - ENTER( "nativeSetParityErrorChar" ); termiosSetParityError( fd, ( char ) value ); - LEAVE( "nativeSetParityErrorChar" ); return( JNI_TRUE ); #else - ENTER( "nativeSetParityErrorChar" ); /* arg! I cant find a way to change it from \0 in Linux. I think the frame and parity error characters are hardcoded. @@ -3087,7 +2965,6 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeSetParityErrorChar)( JNIEnv *env, throw_java_exception( env, UNSUPPORTED_COMM_OPERATION, "Not implemented... yet", strerror( errno ) ); - LEAVE( "nativeSetParityErrorChar" ); return( JNI_FALSE ); #endif /* WIN32 */ } @@ -3115,17 +2992,14 @@ JNIEXPORT jboolean JNICALL RXTXPort(nativeSetEndOfInputChar)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); struct termios ttyset; - ENTER( "nativeSetEndOfInputChar" ); if( tcgetattr( fd, &ttyset ) < 0 ) goto fail; ttyset.c_cc[VEOF] = ( char ) value; if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 ) goto fail; - LEAVE( "nativeSetEndOfInputChar" ); return( JNI_TRUE ); fail: throw_java_exception( env, IO_EXCEPTION, "nativeSetEndOfInputChar", strerror( errno ) ); report( "nativeSetEndOfInputChar failed\n" ); - LEAVE( "nativeSetEndOfInputChar" ); return( JNI_FALSE ); } @@ -3184,11 +3058,9 @@ int read_byte_array( JNIEnv *env, struct event_info_struct *eis = ( struct event_info_struct * ) get_java_var_long( env, *jobj,"eis","J" ); - report_time_start(); flag = eis->eventflags[SPE_DATA_AVAILABLE]; eis->eventflags[SPE_DATA_AVAILABLE] = 0; /* - ENTER( "read_byte_array" ); sprintf(msg, "read_byte_array requests %i\n", length); report( msg ); */ @@ -3234,7 +3106,6 @@ int read_byte_array( JNIEnv *env, #endif /* WIN32 */ if (ret == -1){ report( "read_byte_array: select returned -1\n" ); - LEAVE( "read_byte_array" ); eis->eventflags[SPE_DATA_AVAILABLE] = flag; return -1; } @@ -3243,7 +3114,6 @@ int read_byte_array( JNIEnv *env, if ((ret = READ( fd, buffer + bytes, left )) < 0 ){ if (errno != EINTR && errno != EAGAIN){ report( "read_byte_array: read returned -1\n" ); - LEAVE( "read_byte_array" ); eis->eventflags[SPE_DATA_AVAILABLE] = flag; return -1; } @@ -3280,8 +3150,6 @@ int read_byte_array( JNIEnv *env, sprintf(msg, "read_byte_array returns %i\n", bytes); report( msg ); - LEAVE( "read_byte_array" ); - report_time_end(); */ eis->eventflags[SPE_DATA_AVAILABLE] = flag; return bytes; @@ -3299,8 +3167,6 @@ int read_byte_array( JNIEnv *env, long now, start = 0; char msg[80]; - report_time_start(); - ENTER( "read_byte_array" ); sprintf(msg, "read_byte_array requests %i\n", length); report( msg ); left = length; @@ -3318,7 +3184,6 @@ RETRY: if ((ret = READ( fd, buffer + bytes, left )) < 0 ) if (errno == EINTR) goto RETRY; report( "read_byte_array: read returned -1\n" ); - LEAVE( "read_byte_array" ); return -1; } bytes += ret; @@ -3326,8 +3191,6 @@ RETRY: if ((ret = READ( fd, buffer + bytes, left )) < 0 ) } sprintf(msg, "read_byte_array returns %i\n", bytes); report( msg ); - LEAVE( "read_byte_array" ); - report_time_end(); return bytes; } @@ -3349,7 +3212,6 @@ int read_byte_array( JNIEnv *env, struct timeval *psleep=&sleep; #endif /* WIN32 */ - ENTER( "read_byte_array" ); left = length; FD_ZERO( &rfds ); FD_SET( fd, &rfds ); @@ -3381,32 +3243,27 @@ int read_byte_array( JNIEnv *env, if( ret == 0 ) { report( "read_byte_array: select returned 0\n" ); - LEAVE( "read_byte_array" ); break; } if( ret < 0 ) { report( "read_byte_array: select returned -1\n" ); - LEAVE( "read_byte_array" ); return -1; } ret = READ( fd, buffer + bytes, left ); if( ret == 0 ) { report( "read_byte_array: read returned 0 bytes\n" ); - LEAVE( "read_byte_array" ); break; } else if( ret < 0 ) { report( "read_byte_array: read returned -1\n" ); - LEAVE( "read_byte_array" ); return -1; } bytes += ret; left -= ret; } - LEAVE( "read_byte_array" ); return bytes; } #endif /* asdf */ @@ -3439,16 +3296,13 @@ JNIEXPORT void JNICALL RXTXPort(NativeEnableReceiveTimeoutThreshold)( timeout = vtime; } - ENTER( "RXTXPort:NativeEnableRecieveTimeoutThreshold" ); if( tcgetattr( fd, &ttyset ) < 0 ) goto fail; ttyset.c_cc[ VMIN ] = threshold; ttyset.c_cc[ VTIME ] = timeout/100; if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 ) goto fail; - LEAVE( "RXTXPort:NativeEnableRecieveTimeoutThreshold" ); return; fail: - LEAVE( "RXTXPort:NativeEnableRecieveTimeoutThreshold" ); throw_java_exception( env, IO_EXCEPTION, "TimeoutThreshold", strerror( errno ) ); return; @@ -3599,22 +3453,15 @@ JNIEXPORT jint JNICALL RXTXPort(readByte)( JNIEnv *env, int timeout = get_java_var( env, jobj, "timeout", "I" ); /* char msg[80]; */ -/* - ENTER( "RXTXPort:readByte" ); - report_time_start( ); -*/ bytes = read_byte_array( env, &jobj, fd, buffer, 1, timeout ); if( bytes < 0 ) { - LEAVE( "RXTXPort:readByte" ); throw_java_exception( env, IO_EXCEPTION, "readByte", strerror( errno ) ); return -1; } /* - LEAVE( "RXTXPort:readByte" ); sprintf( msg, "readByte return(%i)\n", bytes ? buffer[ 0 ] : -1 ); report( msg ); - report_time_end( ); */ return (bytes ? (jint)buffer[ 0 ] : -1); } @@ -3642,17 +3489,12 @@ JNIEXPORT jint JNICALL RXTXPort(readArray)( JNIEnv *env, int fd = get_java_var( env, jobj, "fd", "I" ); int timeout = get_java_var( env, jobj, "timeout", "I" ); -/* - ENTER( "readArray" ); - report_time_start( ); -*/ #ifdef __LCC__ if( (size_t) length > SSIZE_MAX ) { #else if( (size_t) length > SSIZE_MAX || (size_t) length < 0 ) { #endif /* __LCC__ */ report( "RXTXPort:readArray length > SSIZE_MAX" ); - LEAVE( "RXTXPort:readArray" ); throw_java_exception( env, ARRAY_INDEX_OUT_OF_BOUNDS, "readArray", "Invalid length" ); return -1; @@ -3662,7 +3504,6 @@ JNIEXPORT jint JNICALL RXTXPort(readArray)( JNIEnv *env, (*env)->ReleaseByteArrayElements( env, jbarray, body, 0 ); if( bytes < 0 ) { report( "RXTXPort:readArray bytes < 0" ); - LEAVE( "RXTXPort:readArray" ); throw_java_exception( env, IO_EXCEPTION, "readArray", strerror( errno ) ); return -1; @@ -3670,8 +3511,6 @@ JNIEXPORT jint JNICALL RXTXPort(readArray)( JNIEnv *env, /* sprintf( msg, "RXTXPort:readArray: %i %i\n", (int) length, bytes); report( msg ); - report_time_end( ); - LEAVE( "RXTXPort:readArray" ); */ return (bytes); } @@ -3723,17 +3562,12 @@ JNIEXPORT jint JNICALL RXTXPort(readTerminatedArray)( JNIEnv *env, int fd = get_java_var( env, jobj, "fd", "I" ); int timeout = get_java_var( env, jobj, "timeout", "I" ); -/* - ENTER( "readArray" ); - report_time_start( ); -*/ #ifdef __LCC__ if( (size_t) length > SSIZE_MAX ) { #else if( (size_t) length > SSIZE_MAX || (size_t) length < 0 ) { #endif /* __LCC__ */ report( "RXTXPort:readArray length > SSIZE_MAX" ); - LEAVE( "RXTXPort:readArray" ); throw_java_exception( env, ARRAY_INDEX_OUT_OF_BOUNDS, "readArray", "Invalid length" ); return -1; @@ -3746,7 +3580,6 @@ JNIEXPORT jint JNICALL RXTXPort(readTerminatedArray)( JNIEnv *env, total += bytes; if( bytes < 0 ) { report( "RXTXPort:readArray bytes < 0" ); - LEAVE( "RXTXPort:readArray" ); throw_java_exception( env, IO_EXCEPTION, "readArray", strerror( errno ) ); return -1; @@ -3764,8 +3597,6 @@ JNIEXPORT jint JNICALL RXTXPort(readTerminatedArray)( JNIEnv *env, /* sprintf( msg, "RXTXPort:readArray: %i %i\n", (int) length, bytes); report( msg ); - report_time_end( ); - LEAVE( "RXTXPort:readArray" ); */ return (bytes); } @@ -3787,11 +3618,6 @@ JNIEXPORT jint JNICALL RXTXPort(nativeavailable)( JNIEnv *env, int fd = get_java_var( env, jobj,"fd","I" ); int result=-1; /* - char message[80]; - - - ENTER( "RXTXPort:nativeavailable" ); - On SCO OpenServer FIONREAD always fails for serial devices, so try ioctl FIORDCHK instead; will only tell us whether bytes are available, not how many, but better than nothing. @@ -3809,24 +3635,9 @@ JNIEXPORT jint JNICALL RXTXPort(nativeavailable)( JNIEnv *env, if (result == -1) { goto fail; } -/* - sprintf(message, " nativeavailable: FIORDCHK result %d, \ - errno %d\n", result , result == -1 ? errno : 0); - report_verbose( message ); - if( result ) - { - sprintf(message, " nativeavailable: FIORDCHK result %d, \ - errno %d\n", result , result == -1 ? errno : 0); - report( message ); - } - LEAVE( "RXTXPort:nativeavailable" ); -*/ return (jint)result; fail: report("RXTXPort:nativeavailable: ioctl() failed\n"); -/* - LEAVE( "RXTXPort:nativeavailable" ); -*/ throw_java_exception( env, IO_EXCEPTION, "nativeavailable", strerror( errno ) ); return (jint)result; @@ -3855,7 +3666,6 @@ JNIEXPORT void JNICALL RXTXPort(setflowcontrol)( JNIEnv *env, struct termios ttyset; int fd = get_java_var( env, jobj,"fd","I" ); - ENTER( "RXTXPort:setflowcontrol" ); if( tcgetattr( fd, &ttyset ) ) goto fail; if ( flowmode & ( FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_RTSCTS_OUT ) ) @@ -3880,10 +3690,8 @@ JNIEXPORT void JNICALL RXTXPort(setflowcontrol)( JNIEnv *env, else ttyset.c_iflag &= ~IXON; /* TRENT */ if( tcsetattr( fd, TCSANOW, &ttyset ) ) goto fail; - LEAVE( "RXTXPort:setflowcontrol" ); return; fail: - LEAVE( "RXTXPort:setflowcontrol" ); throw_java_exception( env, UNSUPPORTED_COMM_OPERATION, "", "flow control type not supported" ); return; @@ -4087,11 +3895,8 @@ void check_tiocmget_changes( struct event_info_struct * eis ) if( !eis ) return; change = eis->change; - report_verbose("entering check_tiocmget_changes\n"); if( ioctl( eis->fd, TIOCMGET, &mflags ) ) { - report( "=======================================\n"); - report( "check_tiocmget_changes: ioctl(TIOCMGET)\n" ); return; } @@ -4101,7 +3906,6 @@ void check_tiocmget_changes( struct event_info_struct * eis ) change = (mflags&TIOCM_DSR) - (eis->omflags&TIOCM_DSR); if( eis && change ) { - report( "sending DSR ===========================\n"); send_event( eis, SPE_DSR, change ); } @@ -4113,7 +3917,6 @@ void check_tiocmget_changes( struct event_info_struct * eis ) if( eis ) eis->omflags = mflags; - report_verbose("leaving check_tiocmget_changes\n"); } /*---------------------------------------------------------- @@ -4362,18 +4165,15 @@ JNIEXPORT void JNICALL RXTXPort(eventLoop)( JNIEnv *env, jobject jobj ) eis.jobj = &jobj; eis.initialised = 0; - ENTER( "eventLoop\n" ); if ( !initialise_event_info_struct( &eis ) ) goto end; if ( !init_threads( &eis ) ) goto end; unlock_monitor_thread( &eis ); do{ - report_time_eventLoop( ); do { if(RXTXPort(nativeavailable)( env, jobj )<0){ report("eventLoop: Hardware Missing\n"); finalize_threads( &eis ); finalize_event_info_struct( &eis ); - LEAVE("eventLoop:error"); return; } /* nothing goes between this call and select */ @@ -4382,7 +4182,6 @@ JNIEXPORT void JNICALL RXTXPort(eventLoop)( JNIEnv *env, jobject jobj ) report_verbose("eventLoop interrupted"); finalize_threads( &eis ); finalize_event_info_struct( &eis ); - LEAVE("eventLoop"); return; } #ifndef WIN32 @@ -4424,7 +4223,7 @@ JNIEXPORT void JNICALL RXTXPort(eventLoop)( JNIEnv *env, jobject jobj ) if ( !initialise_event_info_struct( &eis ) ) goto end; } while( 1 ); end: - LEAVE( "eventLoop: Bailing!\n" ); + return; } /*---------------------------------------------------------- @@ -4485,7 +4284,6 @@ JNIEXPORT jboolean JNICALL RXTXCommDriver(testRead)( char full_windows_name[80]; #endif /* WIN32 */ - ENTER( "RXTXPort:testRead" ); #ifdef TRENT_IS_HERE_DEBUGGING_ENUMERATION /* vmware lies about which ports are there causing irq conflicts */ /* this is for testing only */ @@ -4521,7 +4319,6 @@ JNIEXPORT jboolean JNICALL RXTXCommDriver(testRead)( if ( LOCK( name, pid ) ) { (*env)->ReleaseStringUTFChars(env, tty_name, name); - LEAVE( "\nRXTXPort:testRead no lock" ); //report_error(name); //report_error( " testRead() Lock file failed\n" ); return JNI_FALSE; @@ -4710,7 +4507,6 @@ EAGAIN, continues to be a portability difference that we must deal with." UNLOCK(name, pid ); (*env)->ReleaseStringUTFChars( env, tty_name, name ); localClose( fd ); - LEAVE( "RXTXPort:testRead" ); return ret; #endif /* ! WIN32 */ } @@ -4900,7 +4696,6 @@ JNIEXPORT jboolean JNICALL RXTXCommDriver(isPortPrefixValid)(JNIEnv *env, int fd,i; const char *name = (*env)->GetStringUTFChars(env, tty_name, 0); - ENTER( "RXTXCommDriver:isPortPrefixValid" ); for(i=0;i<64;i++){ #if defined(__sun__) /* Solaris uses /dev/cua/a instead of /dev/cua0 */ @@ -4947,7 +4742,6 @@ JNIEXPORT jboolean JNICALL RXTXCommDriver(isPortPrefixValid)(JNIEnv *env, } } (*env)->ReleaseStringUTFChars(env, tty_name, name); - LEAVE( "RXTXCommDriver:isPortPrefixValid" ); return(result); } @@ -4967,9 +4761,7 @@ JNIEXPORT jstring JNICALL RXTXCommDriver(getDeviceDirectory)(JNIEnv *env, { slf4j_setup_instance(env, jobj); - ENTER( "RXTXCommDriver:getDeviceDirectory" ); return (*env)->NewStringUTF(env, DEVICEDIR); - LEAVE( "RXTXCommDriver:getDeviceDirectory" ); } /*---------------------------------------------------------- @@ -5133,7 +4925,6 @@ jboolean is_interrupted( struct event_info_struct *eis ) int result; JNIEnv *env = eis->env; - ENTER( "is_interrupted" ); (*env)->ExceptionClear(env); result = (*env)->CallBooleanMethod( env, *eis->jobj, eis->checkMonitorThread ); @@ -5144,7 +4935,6 @@ jboolean is_interrupted( struct event_info_struct *eis ) (*env)->ExceptionClear(env); } #endif /* DEBUG */ - LEAVE( "RXTXCommDriver:is_interrupted" ); return(result); } @@ -5204,7 +4994,6 @@ int send_event( struct event_info_struct *eis, jint type, int flag ) if( eis ) env = eis->env; else return(-1); - ENTER( "send_event" ); if( !eis || eis->eventloop_interrupted > 1 ) { report("event loop interrupted\n"); @@ -5227,9 +5016,7 @@ int send_event( struct event_info_struct *eis, jint type, int flag ) (*eis->env)->ExceptionDescribe(eis->env); (*eis->env)->ExceptionClear(eis->env); } -#endif /* asdf */ - /* report("e"); */ - LEAVE( "send_event" ); +#endif return(result); } @@ -5252,14 +5039,10 @@ size_t get_java_var_long( JNIEnv *env, jobject jobj, char *id, char *type ) jclass jclazz = (*env)->GetObjectClass( env, jobj ); jfieldID jfd = (*env)->GetFieldID( env, jclazz, id, type ); -/* - ENTER( "get_java_var" ); -*/ if( !jfd ) { (*env)->ExceptionDescribe( env ); (*env)->ExceptionClear( env ); (*env)->DeleteLocalRef( env, jclazz ); - LEAVE( "get_java_var" ); return result; } if ( !strcmp( type, "J" ) ) { @@ -5271,9 +5054,6 @@ size_t get_java_var_long( JNIEnv *env, jobject jobj, char *id, char *type ) (*env)->DeleteLocalRef( env, jclazz ); if(!strncmp( "fd",id,2) && result == 0) report_error( "get_java_var: invalid file descriptor\n" ); -/* - LEAVE( "get_java_var" ); -*/ return result; } @@ -5293,11 +5073,9 @@ void throw_java_exception( JNIEnv *env, char *exc, char *foo, char *msg ) { char buf[ 60 ]; jclass clazz = (*env)->FindClass( env, exc ); - ENTER( "throw_java_exception" ); if( !clazz ) { (*env)->ExceptionDescribe( env ); (*env)->ExceptionClear( env ); - LEAVE( "throw_java_exception" ); return; } #if defined(_GNU_SOURCE) @@ -5308,7 +5086,6 @@ void throw_java_exception( JNIEnv *env, char *exc, char *foo, char *msg ) (*env)->ThrowNew( env, clazz, buf ); /* ct7 * Added DeleteLocalRef */ (*env)->DeleteLocalRef( env, clazz ); - LEAVE( "throw_java_exception" ); } #ifndef WIN32 diff --git a/src/main/c/src/windows/termios.c b/src/main/c/src/windows/termios.c index bd60cc94..8de7f7e9 100644 --- a/src/main/c/src/windows/termios.c +++ b/src/main/c/src/windows/termios.c @@ -146,7 +146,6 @@ void termios_setflags( int fd, int termios_flags[] ) }; if( !index ) { - LEAVE( "termios_setflags" ); return; } index->event_flag = 0; @@ -189,7 +188,6 @@ int get_fd( char *filename ) { struct termios_list *index = first_tl; - ENTER( "get_fd" ); if( !index ) { return -1; @@ -201,7 +199,6 @@ int get_fd( char *filename ) if( !index->next ) return( -1 ); } - LEAVE( "get_fd" ); return( index->fd ); } @@ -220,7 +217,6 @@ char *get_filename( int fd ) { struct termios_list *index = first_tl; - ENTER( "get_filename" ); if( !index ) return( "bad" ); while( index->fd != fd ) @@ -229,7 +225,6 @@ char *get_filename( int fd ) return( "bad" ); index = index->next; } - LEAVE( "get_filename" ); return( index->filename ); } @@ -308,7 +303,6 @@ CBR_toB() int CBR_to_B( int Baud ) { - ENTER( "CBR_to_B" ); switch ( Baud ) { @@ -367,7 +361,6 @@ B_to_CBR() int B_to_CBR( int Baud ) { int ret; - ENTER( "B_to_CBR" ); switch ( Baud ) { case 0: ret = 0; break; @@ -410,7 +403,6 @@ int B_to_CBR( int Baud ) /* assume custom baudrate */ return Baud; } - LEAVE( "B_to_CBR" ); return ret; } @@ -427,7 +419,6 @@ bytesize_to_termios() int bytesize_to_termios( int ByteSize ) { - ENTER( "bytesize_to_termios" ); switch ( ByteSize ) { case 5: return( CS5 ); @@ -451,7 +442,6 @@ termios_to_bytesize() int termios_to_bytesize( int cflag ) { - ENTER( "termios_to_bytesize" ); switch ( cflag & CSIZE ) { case CS5: return( 5 ); @@ -475,12 +465,10 @@ get_dos_port() const char *get_dos_port( char const *name ) { - ENTER( "get_dos_port" ); if ( !strcmp( name, "/dev/cua0" ) ) return( "COM1" ); if ( !strcmp( name, "/dev/cua1" ) ) return( "COM2" ); if ( !strcmp( name, "/dev/cua2" ) ) return( "COM3" ); if ( !strcmp( name, "/dev/cua3" ) ) return( "COM4" ); - LEAVE( "get_dos_port" ); return( ( const char * ) name ); } @@ -567,8 +555,6 @@ FillDCB() BOOL FillDCB( DCB *dcb, unsigned long *hCommPort, COMMTIMEOUTS Timeout ) { - - ENTER( "FillDCB" ); dcb->DCBlength = sizeof( dcb ); if ( !GetCommState( hCommPort, dcb ) ) { @@ -607,7 +593,6 @@ BOOL FillDCB( DCB *dcb, unsigned long *hCommPort, COMMTIMEOUTS Timeout ) report( "SetCommTimeouts\n" ); return( -1 ); } - LEAVE( "FillDCB" ); return ( TRUE ) ; } @@ -627,7 +612,6 @@ int serial_close( int fd ) struct termios_list *index; /* char message[160]; */ - ENTER( "serial_close" ); if( !first_tl || !first_tl->hComm ) { report( "gotit!" ); @@ -636,7 +620,6 @@ int serial_close( int fd ) index = find_port( fd ); if ( !index ) { - LEAVE( "serial_close" ); return -1; } @@ -689,7 +672,6 @@ int serial_close( int fd ) */ free( index ); } - LEAVE( "serial_close" ); return 0; } @@ -706,14 +688,12 @@ cfmakeraw() void cfmakeraw( struct termios *s_termios ) { - ENTER( "cfmakeraw" ); s_termios->c_iflag &= ~( IGNBRK|BRKINT|PARMRK|ISTRIP |INLCR|IGNCR|ICRNL|IXON ); s_termios->c_oflag &= ~OPOST; s_termios->c_lflag &= ~( ECHO|ECHONL|ICANON|ISIG|IEXTEN ); s_termios->c_cflag &= ~( CSIZE|PARENB ); s_termios->c_cflag |= CS8; - LEAVE( "cfmakeraw" ); } /*---------------------------------------------------------- @@ -729,8 +709,6 @@ init_termios() BOOL init_serial_struct( struct serial_struct *sstruct ) { - ENTER( "init_serial_struct" ); - /* use of custom_divisor and baud_base requires access to kernel space. The kernel does try its best if you just @@ -770,7 +748,6 @@ BOOL init_serial_struct( struct serial_struct *sstruct ) sstruct->iomem_base = NULL; - LEAVE( "init_serial_struct" ); return TRUE; } @@ -787,7 +764,6 @@ init_termios() BOOL init_termios(struct termios *ttyset ) { - ENTER( "init_termios" ); if ( !ttyset ) return FALSE; memset( ttyset, 0, sizeof( struct termios ) ); @@ -812,7 +788,6 @@ BOOL init_termios(struct termios *ttyset ) ttyset->c_cc[VWERASE] = 0x17; /* 14: C-w */ ttyset->c_cc[VLNEXT] = 0x16; /* 15: C-w */ ttyset->c_cc[VEOL2] = '\n'; /* 16: */ - LEAVE( "init_termios" ); return TRUE; /* default VTIME = 0, VMIN = 1: read blocks forever until one byte */ } @@ -832,7 +807,6 @@ int port_opened( const char *filename ) { struct termios_list *index = first_tl; - ENTER( "port_opened" ); if ( ! index ) return 0; if( !strcmp( index->filename, filename ) ) @@ -843,7 +817,6 @@ int port_opened( const char *filename ) if( !strcmp( index->filename, filename ) ) return index->fd; } - LEAVE( "port_opened" ); return 0; } @@ -869,7 +842,6 @@ open_port() int open_port( struct termios_list *port ) { - ENTER( "open_port" ); port->hComm = CreateFile( port->filename, GENERIC_READ | GENERIC_WRITE, 0, @@ -922,7 +894,6 @@ int open_port( struct termios_list *port ) report( "Could not create write overlapped\n" ); goto fail; } - LEAVE( "open_port" ); return( 0 ); fail: return( -1 ); @@ -948,14 +919,12 @@ struct termios_list *find_port( int fd ) char message[160]; struct termios_list *index = first_tl; - ENTER( "find_port" ); if ( fd <= 0 || !first_tl ) goto fail; while( index->fd ) { if ( index->fd == fd ) { - LEAVE( "find_port" ); return index; } if ( !index->next ) @@ -966,7 +935,6 @@ struct termios_list *find_port( int fd ) sprintf( message, "No info known about the port. %i\n", fd ); report( message ); set_errno( EBADF ); - LEAVE( "find_port" ); return NULL; } @@ -986,7 +954,6 @@ int get_free_fd(void) int next, last; struct termios_list *index = first_tl; - ENTER( "get_free_fd" ); if ( !index ) { return( 1 ); @@ -1015,7 +982,6 @@ int get_free_fd(void) index = index->next; last = next; } - LEAVE( "get_free_fd" ); return( index->fd + 1 ); } @@ -1035,8 +1001,6 @@ struct termios_list *add_port( const char *filename ) struct termios_list *index = first_tl; struct termios_list *port; - ENTER( "add_port" ); - port = malloc( sizeof( struct termios_list ) ); if( !port ) goto fail; @@ -1111,7 +1075,6 @@ struct termios_list *add_port( const char *filename ) index->next = port; } } - LEAVE( "add_port" ); return port; fail: @@ -1144,7 +1107,6 @@ int check_port_capabilities( struct termios_list *index ) DCB dcb; char message[160]; - ENTER( "check_port_capabilities" ); /* check for capabilities */ GetCommProperties( index->hComm, &cp ); if ( !( cp.dwProvCapabilities & PCF_DTRDSR ) ) @@ -1176,7 +1138,6 @@ int check_port_capabilities( struct termios_list *index ) report( "GetCommState\n" ); return -1; } - LEAVE( "check_port_capabilities" ); return 0; } @@ -1197,7 +1158,6 @@ int serial_open( const char *filename, int flags, ... ) struct termios_list *index; char message[160]; - ENTER( "serial_open" ); if ( port_opened( filename ) ) { report( "Port is already opened\n" ); @@ -1249,7 +1209,6 @@ int serial_open( const char *filename, int flags, ... ) } if ( first_tl->hComm == INVALID_HANDLE_VALUE ) report( "serial_open: test\n" ); - LEAVE( "serial_open" ); return( index->fd ); } @@ -1274,8 +1233,6 @@ int serial_write( int fd, char *Str, int length ) /* COMSTAT Stat; */ int old_flag; - ENTER( "serial_write" ); - if ( fd <= 0 ) { return 0; @@ -1283,7 +1240,6 @@ int serial_write( int fd, char *Str, int length ) index = find_port( fd ); if ( !index ) { - LEAVE( "serial_write"); return -1; } old_flag = index->event_flag; @@ -1337,7 +1293,6 @@ int serial_write( int fd, char *Str, int length ) /* ClearErrors( index, &Stat ); */ index->event_flag = old_flag; index->tx_happened = 1; - LEAVE( "serial_write" ); return nBytes; } @@ -1367,7 +1322,6 @@ int serial_read( int fd, void *vb, int size ) unsigned char *dest = vb; start = GetTickCount(); - ENTER( "serial_read" ); if ( fd <= 0 ) { @@ -1376,7 +1330,6 @@ int serial_read( int fd, void *vb, int size ) index = find_port( fd ); if ( !index ) { - LEAVE( "serial_read" ); return -1; } @@ -1501,7 +1454,6 @@ int serial_read( int fd, void *vb, int size ) return( total ); } } - LEAVE( "serial_read" ); return total; } @@ -1519,7 +1471,6 @@ int serial_read( int fd, void *vb, int size ) unsigned char *dest = vb; start = GetTickCount(); - ENTER( "serial_read" ); if ( fd <= 0 ) { @@ -1529,7 +1480,6 @@ int serial_read( int fd, void *vb, int size ) index = find_port( fd ); if ( !index ) { - LEAVE( "serial_read 7" ); errno = EIO; printf("2\n"); return -1; @@ -1664,7 +1614,6 @@ int serial_read( int fd, void *vb, int size ) return( total ); } } - LEAVE( "serial_read" ); ClearErrors( index, &Stat); return total; } @@ -1684,7 +1633,6 @@ cfsetospeed() int cfsetospeed( struct termios *s_termios, speed_t speed ) { char message[160]; - ENTER( "cfsetospeed" ); /* clear baudrate */ s_termios->c_cflag &= ~CBAUD; if ( speed & ~CBAUD ) @@ -1705,7 +1653,6 @@ int cfsetospeed( struct termios *s_termios, speed_t speed ) s_termios->c_cflag |= B9600; } s_termios->c_ispeed = s_termios->c_ospeed = speed; - LEAVE( "cfsetospeed" ); return 1; } @@ -1754,7 +1701,6 @@ cfgetospeed() speed_t cfgetospeed( struct termios *s_termios ) { - ENTER( "cfgetospeed" ); return s_termios->c_ospeed; } @@ -1771,7 +1717,6 @@ cfgetispeed() speed_t cfgetispeed( struct termios *s_termios ) { - ENTER( "cfgetospeed" ); return s_termios->c_ispeed; } @@ -1787,7 +1732,6 @@ termios_to_DCB() ----------------------------------------------------------*/ int termios_to_DCB( struct termios *s_termios, DCB *dcb ) { - ENTER( "termios_to_DCB" ); if ( !(s_termios->c_cflag & CBAUDEX) ) s_termios->c_ispeed = s_termios->c_ospeed = s_termios->c_cflag & CBAUD; dcb->BaudRate = B_to_CBR( s_termios->c_ispeed ); @@ -1841,7 +1785,6 @@ int termios_to_DCB( struct termios *s_termios, DCB *dcb ) dcb->fOutxCtsFlow = FALSE; } - LEAVE( "termios_to_DCB" ); return 0; } @@ -1871,11 +1814,9 @@ DCB_to_termios() ----------------------------------------------------------*/ void DCB_to_termios( DCB *dcb, struct termios *s_termios ) { - ENTER( "DCB_to_termios" ); s_termios->c_ispeed = CBR_to_B( dcb->BaudRate ); s_termios->c_ospeed = s_termios->c_ispeed; s_termios->c_cflag |= s_termios->c_ispeed & CBAUD; - LEAVE( "DCB_to_termios" ); } /*---------------------------------------------------------- @@ -2018,13 +1959,11 @@ int tcgetattr( int fd, struct termios *s_termios ) struct termios_list *index; char message[160]; - ENTER( "tcgetattr" ); if ( fd <= 0 ) return 0; index = find_port( fd ); if ( !index ) { - LEAVE( "tcgetattr" ); return -1; } if ( !GetCommState( index->hComm, &myDCB ) ) @@ -2193,7 +2132,6 @@ int tcgetattr( int fd, struct termios *s_termios ) /***** line discipline ( c_line ) ( == c_cc[33] ) *****/ DCB_to_termios( &myDCB, s_termios ); /* baudrate */ - LEAVE( "tcgetattr" ); return 0; } @@ -2238,13 +2176,11 @@ int tcsetattr( int fd, int when, struct termios *s_termios ) COMMTIMEOUTS timeouts; struct termios_list *index; - ENTER( "tcsetattr" ); if ( fd <= 0 ) return 0; index = find_port( fd ); if ( !index ) { - LEAVE( "tcsetattr" ); return -1; } fflush( stdout ); @@ -2402,7 +2338,6 @@ int tcsetattr( int fd, int when, struct termios *s_termios ) return -1; } memcpy( index->ttyset, s_termios, sizeof( struct termios ) ); - LEAVE( "tcsetattr" ); return 0; } @@ -2424,13 +2359,10 @@ int tcsendbreak( int fd, int duration ) struct termios_list *index; COMSTAT Stat; - ENTER( "tcsendbreak" ); - index = find_port( fd ); if ( !index ) { - LEAVE( "tcdrain" ); return -1; } @@ -2442,7 +2374,6 @@ int tcsendbreak( int fd, int duration ) usleep( duration * 250000 ); if( !ClearCommBreak( index->hComm ) ) ClearErrors( index, &Stat ); - LEAVE( "tcsendbreak" ); return 1; } @@ -2463,12 +2394,10 @@ int tcdrain ( int fd ) char message[160]; int old_flag; - ENTER( "tcdrain" ); index = find_port( fd ); if ( !index ) { - LEAVE( "tcdrain" ); return -1; } old_flag = index->event_flag; @@ -2497,7 +2426,6 @@ int tcdrain ( int fd ) } set_errno( EAGAIN ); YACK(); - LEAVE( "tcdrain" ); return -1; } /* @@ -2505,7 +2433,6 @@ int tcdrain ( int fd ) (int) GetLastError() ); report( message ); */ - LEAVE( "tcdrain success" ); index->event_flag |= EV_TXEMPTY; SetCommMask( index->hComm, index->event_flag ); index->event_flag = old_flag; @@ -2537,7 +2464,6 @@ int tcflush( int fd, int queue_selector ) index = find_port( fd ); if( !index) { - LEAVE( "tclflush" ); return(-1); } @@ -2547,10 +2473,8 @@ int tcflush( int fd, int queue_selector ) SetCommMask( index->hComm, index->event_flag ); index->tx_happened = 1; */ - ENTER( "tcflush" ); if ( !index ) { - LEAVE( "tcflush" ); return -1; } @@ -2584,14 +2508,12 @@ int tcflush( int fd, int queue_selector ) set_errno( ENOTSUP ); */ report( "tcflush: Unknown queue_selector\n" ); - LEAVE( "tcflush" ); return -1; } index->event_flag |= EV_TXEMPTY; SetCommMask( index->hComm, index->event_flag ); index->event_flag = old_flag; index->tx_happened = 1; - LEAVE( "tcflush" ); return( 0 ); /* FIXME Need to figure out what the various errors are in @@ -2600,7 +2522,6 @@ int tcflush( int fd, int queue_selector ) */ fail: - LEAVE( "tcflush" ); set_errno( EAGAIN ); YACK(); return -1; @@ -2620,7 +2541,6 @@ tcflow() int tcflow( int fd, int action ) { - ENTER( "tcflow" ); switch ( action ) { /* Suspend transmission of output */ @@ -2633,7 +2553,6 @@ int tcflow( int fd, int action ) case TCION: break; default: return -1; } - LEAVE( "tcflow" ); return 1; } /*---------------------------------------------------------- @@ -2700,13 +2619,11 @@ int ioctl( int fd, int request, ... ) struct serial_icounter_struct *sistruct; #endif /* TIOCGICOUNT */ - ENTER( "ioctl" ); if ( fd <= 0 ) return 0; index = find_port( fd ); if ( !index ) { - LEAVE( "ioctl" ); return -1; } @@ -3029,7 +2946,6 @@ int ioctl( int fd, int request, ... ) return -ENOIOCTLCMD; } va_end( ap ); - LEAVE( "ioctl" ); return 0; } @@ -3051,13 +2967,11 @@ int fcntl( int fd, int command, ... ) struct termios_list *index; char message[160]; - ENTER( "fcntl" ); if ( fd <= 0 ) return 0; index = find_port( fd ); if ( !index ) { - LEAVE( "fcntl" ); return -1; } @@ -3085,7 +2999,6 @@ int fcntl( int fd, int command, ... ) } va_end( ap ); - LEAVE( "fcntl" ); return ret; } @@ -3104,7 +3017,6 @@ void termios_interrupt_event_loop( int fd, int flag ) struct termios_list * index = find_port( fd ); if ( !index ) { - LEAVE( "termios_interrupt_event_loop" ); return; } /* @@ -3140,7 +3052,6 @@ int serial_select( int n, fd_set *readfds, fd_set *writefds, COMSTAT Stat; int ret; - ENTER( "serial_select" ); if ( fd <= 0 ) { /* Baby did a bad baad thing */ @@ -3204,17 +3115,14 @@ int serial_select( int n, fd_set *readfds, fd_set *writefds, end: /* You may want to chop this out for lower latency */ usleep(1000); - LEAVE( "serial_select" ); return( 1 ); timeout: - LEAVE( "serial_select" ); return( 0 ); fail: YACK(); sprintf( message, "< select called error %i\n", n ); report( message ); errno = EBADFD; - LEAVE( "serial_select" ); return( 1 ); } #ifdef asdf @@ -3227,7 +3135,6 @@ int serial_select( int n, fd_set *readfds, fd_set *writefds, struct termios_list *index; char message[160]; - ENTER( "serial_select" ); if ( fd <= 0 ) { usleep(1000); @@ -3236,7 +3143,6 @@ int serial_select( int n, fd_set *readfds, fd_set *writefds, index = find_port( fd ); if ( !index ) { - LEAVE( "serial_select" ); return -1; } if( index->interrupt == 1 ) @@ -3310,7 +3216,6 @@ int serial_select( int n, fd_set *readfds, fd_set *writefds, } } end: - LEAVE( "serial_select" ); return( 1 ); #ifdef asdf /* FIXME this needs to be cleaned up... */ @@ -3319,7 +3224,6 @@ int serial_select( int n, fd_set *readfds, fd_set *writefds, YACK(); report( message ); set_errno( EBADFD ); - LEAVE( "serial_select" ); return( 1 ); #endif /* asdf */ @@ -3343,15 +3247,12 @@ int termiosGetParityErrorChar( int fd ) struct termios_list *index; DCB dcb; - ENTER( "termiosGetParityErrorChar" ); index = find_port( fd ); if( !index ) { - LEAVE( "termiosGetParityErrorChar" ); return(-1); } GetCommState( index->hComm, &dcb ); - LEAVE( "termiosGetParityErrorChar" ); return( dcb.ErrorChar ); } @@ -3371,17 +3272,14 @@ void termiosSetParityError( int fd, char value ) DCB dcb; struct termios_list *index; - ENTER( "termiosGetParityErrorChar" ); index = find_port( fd ); if ( !index ) { - LEAVE( "termiosSetParityError" ); return; } GetCommState( index->hComm, &dcb ); dcb.ErrorChar = value; SetCommState( index->hComm, &dcb ); - LEAVE( "termiosGetParityErrorChar" ); } /*----------------------- END OF LIBRARY -----------------*/ #ifdef PLAYING_AROUND diff --git a/src/main/java/gnu/io/CommPort.java b/src/main/java/gnu/io/CommPort.java index 961e3c8a..880d42fb 100644 --- a/src/main/java/gnu/io/CommPort.java +++ b/src/main/java/gnu/io/CommPort.java @@ -93,14 +93,12 @@ public abstract class CommPort extends Object { public abstract int getInputBufferSize(); public abstract void setOutputBufferSize(int size); public abstract int getOutputBufferSize(); - @SuppressWarnings("static-access") - public void close() { - log.trace("CommPort:close()"); + public void close() { try { CommPortIdentifier cp = CommPortIdentifier.getPortIdentifier(this); if (cp != null) - cp.getPortIdentifier(this).internalClosePort(); + CommPortIdentifier.getPortIdentifier(this).internalClosePort(); } catch (NoSuchPortException e) { } }; diff --git a/src/main/java/gnu/io/CommPortIdentifier.java b/src/main/java/gnu/io/CommPortIdentifier.java index bb40ed3d..3101f231 100644 --- a/src/main/java/gnu/io/CommPortIdentifier.java +++ b/src/main/java/gnu/io/CommPortIdentifier.java @@ -137,8 +137,6 @@ public class CommPortIdentifier extends Object /* extends Vector? */ comments: ------------------------------------------------------------------------------*/ public static void addPortName(String s, int type, CommDriver c) { - - log.trace("CommPortIdentifier:addPortName(" + s + ")"); AddIdentifierToList(new CommPortIdentifier(s, null, type, c)); } /*------------------------------------------------------------------------------ @@ -370,8 +368,6 @@ public synchronized CommPort open(FileDescriptor f) throws UnsupportedCommOperat private boolean HideOwnerEvents; public RXTXPort open(String TheOwner, int i) throws gnu.io.PortInUseException { - log.trace("CommPortIdentifier:open(" + TheOwner + ", " + i + ")"); - boolean isAvailable; synchronized (this) { isAvailable = this.Available; @@ -470,7 +466,6 @@ void internalClosePort() { ------------------------------------------------------------------------------*/ @SuppressWarnings("unchecked") void fireOwnershipEvent(int eventType) { - log.trace("CommPortIdentifier:fireOwnershipEvent( " + eventType + " )"); if (ownershipListener != null) { CommPortOwnershipListener c; for (Enumeration e = ownershipListener.elements(); e.hasMoreElements(); c.ownershipChange(eventType)) diff --git a/src/main/java/gnu/io/RXTXCommDriver.java b/src/main/java/gnu/io/RXTXCommDriver.java index 2e6007ba..9edd1b69 100644 --- a/src/main/java/gnu/io/RXTXCommDriver.java +++ b/src/main/java/gnu/io/RXTXCommDriver.java @@ -175,7 +175,6 @@ private final String[] getValidPortPrefixes(String CandidatePortPrefixes[]) { */ String ValidPortPrefixes[] = new String[getScannedBufferSize()]; - log.trace("RXTXCommDriver:getValidPortPrefixes()"); if (CandidatePortPrefixes == null) { log.debug( "RXTXCommDriver:getValidPortPrefixes() No ports prefixes known for this System. Please check the port prefixes listed for {} in RXTXCommDriver:registerScannedPorts()", @@ -280,7 +279,6 @@ else if (testRead(PortName, PortType)) { } } log.trace("Found Devices: {}", String.join(", ", foundDevices)); - log.trace("Leaving registerValidPorts()"); } /* @@ -302,9 +300,6 @@ else if (testRead(PortName, PortType)) { * Determine the OS and where the OS has the devices located */ public void initialize() { - - log.trace("RXTXCommDriver:initialize()"); - osName = System.getProperty("os.name"); deviceDirectory = getDeviceDirectory(); @@ -742,7 +737,6 @@ private static boolean isClassPresent(final String className) { * returns an object that extends either SerialPort or ParallelPort. */ public CommPort getCommPort(String PortName, int PortType) { - log.trace("RXTXCommDriver:getCommPort(" + PortName + "," + PortType + ")"); try { switch (PortType) { case CommPortIdentifier.PORT_SERIAL : diff --git a/src/main/java/gnu/io/RXTXPort.java b/src/main/java/gnu/io/RXTXPort.java index e2a53807..7eacfb52 100644 --- a/src/main/java/gnu/io/RXTXPort.java +++ b/src/main/java/gnu/io/RXTXPort.java @@ -102,7 +102,6 @@ class MonitorThread extends Thread { */ public void run() { try { - log.trace("RXTXPort:MonitorThread:run()"); monThreadisInterrupted = false; eventLoop(); eis = 0; @@ -113,7 +112,6 @@ public void run() { } } protected void finalize() throws Throwable { - log.trace("RXTXPort:MonitorThread exiting"); } } protected boolean HARDWARE_FAULT = false; @@ -126,7 +124,6 @@ protected void finalize() throws Throwable { } catch (Exception e) { } - log.trace("RXTXPort {}"); // System.loadLibrary( "rxtxSerial" ); SerialManager.getInstance(); @@ -145,7 +142,6 @@ protected void finalize() throws Throwable { * @see gnu.io.SerialPort */ public RXTXPort(String name) throws PortInUseException { - log.trace("RXTXPort:RXTXPort(" + name + ") called"); /* * commapi/javadocs/API_users_guide.html specifies that whenever an application * tries to open a port in use by another application the PortInUseException @@ -168,7 +164,6 @@ public RXTXPort(String name) throws PortInUseException { MonitorThreadAlive = true; // } catch ( PortInUseException e ){} timeout = -1; /* default disabled timeout */ - log.trace("RXTXPort:RXTXPort(" + name + ") returns with fd = " + fd); } private native synchronized int open(String name) throws PortInUseException; @@ -235,7 +230,6 @@ public InputStream getInputStream() { private native int nativeGetParity(int fd); private native int nativeGetFlowControlMode(int fd); public synchronized void setSerialPortParams(int b, int d, int s, int p) throws UnsupportedCommOperationException { - log.trace("RXTXPort:setSerialPortParams(" + b + " " + d + " " + s + " " + p + ") called"); if (nativeSetSerialPortParams(b, d, s, p)) throw new UnsupportedCommOperationException("Invalid Parameter"); speed = b; @@ -245,7 +239,6 @@ public synchronized void setSerialPortParams(int b, int d, int s, int p) throws dataBits = d; stopBits = s; parity = p; - log.trace("RXTXPort:setSerialPortParams(" + b + " " + d + " " + s + " " + p + ") returning"); } /** @@ -300,7 +293,6 @@ public int getParity() { * @see gnu.io.SerialPort#FLOWCONTROL_NONE */ public void setFlowControlMode(int flowcontrol) { - log.trace("RXTXPort:setFlowControlMode( " + flowcontrol + " ) called"); if (monThreadisInterrupted) { log.trace("RXTXPort:setFlowControlMode MonThread was interrupted"); return; @@ -312,7 +304,6 @@ public void setFlowControlMode(int flowcontrol) { return; } flowmode = flowcontrol; - log.trace("RXTXPort:setFlowControlMode( " + flowcontrol + " ) returning"); } /** * @return int representing the flowmode @@ -337,7 +328,6 @@ public void enableReceiveFraming(int f) throws UnsupportedCommOperationException /** */ public void disableReceiveFraming() { - log.trace("RXTXPort:disableReceiveFramming() called and returning (noop)"); } /** * @return true if framing is enabled @@ -372,24 +362,19 @@ public int getReceiveFramingByte() { /** */ public void disableReceiveTimeout() { - log.trace("RXTXPort:disableReceiveTimeout() called"); timeout = -1; NativeEnableReceiveTimeoutThreshold(timeout, threshold, InputBuffer); - log.trace("RXTXPort:disableReceiveTimeout() returning"); } /** * @param time */ public void enableReceiveTimeout(int time) { - // log.trace("Enabling receive timeout: "+time); - log.trace("RXTXPort:enableReceiveTimeout() called"); if (time >= 0) { timeout = time; NativeEnableReceiveTimeoutThreshold(time, threshold, InputBuffer); } else { throw new IllegalArgumentException("Unexpected negative timeout value"); } - log.trace("RXTXPort:enableReceiveTimeout() returning"); } /** * @return boolean true if recieve timeout is enabled @@ -413,7 +398,6 @@ public int getReceiveTimeout() { * threshold */ public void enableReceiveThreshold(int thresh) { - log.trace("RXTXPort:enableReceiveThreshold( " + thresh + " ) called"); if (thresh >= 0) { threshold = thresh; NativeEnableReceiveTimeoutThreshold(timeout, threshold, InputBuffer); @@ -421,7 +405,6 @@ public void enableReceiveThreshold(int thresh) { { throw new IllegalArgumentException("Unexpected negative threshold value"); } - log.trace("RXTXPort:enableReceiveThreshold( " + thresh + " ) returned"); } /** */ @@ -454,12 +437,10 @@ public boolean isReceiveThresholdEnabled() { * @param size */ public void setInputBufferSize(int size) { - log.trace("RXTXPort:setInputBufferSize( " + size + ") called"); if (size < 0) throw new IllegalArgumentException("Unexpected negative buffer size value"); else InputBuffer = size; - log.trace("RXTXPort:setInputBufferSize( " + size + ") returning"); } /** */ @@ -470,13 +451,10 @@ public int getInputBufferSize() { * @param size */ public void setOutputBufferSize(int size) { - log.trace("RXTXPort:setOutputBufferSize( " + size + ") called"); if (size < 0) throw new IllegalArgumentException("Unexpected negative buffer size value"); else OutputBuffer = size; - log.trace("RXTXPort:setOutputBufferSize( " + size + ") returned"); - } /** * @return in the output buffer size @@ -555,13 +533,7 @@ public int getOutputBufferSize() { boolean monThreadisInterrupted = true; private native void interruptEventLoop(); public boolean checkMonitorThread() { - log.trace("RXTXPort:checkMonitorThread()"); - if (monThread != null) { - log.trace("monThreadisInterrupted = " + monThreadisInterrupted); - return monThreadisInterrupted; - } - log.trace("monThread is null "); - return (true); + return monThread != null ? monThreadisInterrupted : true; } /** @@ -689,8 +661,6 @@ public void addEventListener(SerialPortEventListener lsnr) throws TooManyListene /* * Don't let and notification requests happen until the Eventloop is ready */ - - log.trace("RXTXPort:addEventListener()"); if (SPEventListener != null) { throw new TooManyListenersException(); } @@ -703,13 +673,11 @@ public void addEventListener(SerialPortEventListener lsnr) throws TooManyListene waitForTheNativeCodeSilly(); MonitorThreadAlive = true; } - log.trace("RXTXPort:Interrupt=false"); } /** * Remove the serial port event listener */ public void removeEventListener() { - log.trace("RXTXPort:removeEventListener() called"); waitForTheNativeCodeSilly(); // if( monThread != null && monThread.isAlive() ) if (monThreadisInterrupted == true) { @@ -749,7 +717,6 @@ public void removeEventListener() { MonitorThreadLock = false; MonitorThreadAlive = false; monThreadisInterrupted = true; - log.trace("RXTXPort:removeEventListener() returning"); } /** * Give the native code a chance to start listening to the hardware or should we @@ -877,7 +844,6 @@ public void notifyOnBreakInterrupt(boolean enable) { private native void nativeClose(String name); public void close() { - log.trace("RXTXPort:close( " + this.name + " )"); log.debug("Closing port: {}", name); try { @@ -915,14 +881,11 @@ public void close() { } log.debug("Closed port: {}", name); } - } /** Finalize the port */ protected void finalize() { - log.trace("RXTXPort:finalize()"); if (fd > 0) { - log.trace("RXTXPort:calling close()"); close(); } z.finalize(); @@ -970,7 +933,6 @@ class SerialOutputStream extends OutputStream { * IOException */ public void write(int b) throws IOException { - log.trace("RXTXPort:SerialOutputStream:write(int)"); if (speed == 0) return; if (monThreadisInterrupted == true) { @@ -984,7 +946,6 @@ public void write(int b) throws IOException { throw new IOException(); } writeByte(b, monThreadisInterrupted); - log.trace("Leaving RXTXPort:SerialOutputStream:write( int )"); } finally { IOLockedMutex.readLock().unlock(); } @@ -994,7 +955,6 @@ public void write(int b) throws IOException { * IOException */ public void write(byte b[]) throws IOException { - log.trace("Entering RXTXPort:SerialOutputStream:write(" + b.length + ") "/* + new String(b) */ ); if (speed == 0) return; if (monThreadisInterrupted == true) { @@ -1006,7 +966,6 @@ public void write(byte b[]) throws IOException { try { waitForTheNativeCodeSilly(); writeArray(b, 0, b.length, monThreadisInterrupted); - log.trace("Leaving RXTXPort:SerialOutputStream:write(" + b.length + ")"); } finally { IOLockedMutex.readLock().unlock(); } @@ -1027,8 +986,6 @@ public void write(byte b[], int off, int len) throws IOException { byte send[] = new byte[len]; System.arraycopy(b, off, send, 0, len); - log.trace("Entering RXTXPort:SerialOutputStream:write(" + send.length + " " + off + " " + len + " " - + ") " /* + new String(send) */ ); if (fd == 0) throw new IOException(); if (monThreadisInterrupted == true) { @@ -1038,8 +995,6 @@ public void write(byte b[], int off, int len) throws IOException { try { waitForTheNativeCodeSilly(); writeArray(send, 0, len, monThreadisInterrupted); - log.trace("Leaving RXTXPort:SerialOutputStream:write(" + send.length + " " + off + " " + len + " " - + ") " /* + new String(send) */ ); } finally { IOLockedMutex.readLock().unlock(); } @@ -1047,7 +1002,6 @@ public void write(byte b[], int off, int len) throws IOException { /** */ public void flush() throws IOException { - log.trace("RXTXPort:SerialOutputStream:flush() enter"); if (speed == 0) return; if (fd == 0) @@ -1064,7 +1018,6 @@ public void flush() throws IOException { */ if (nativeDrain(monThreadisInterrupted)) sendEvent(SerialPortEvent.OUTPUT_BUFFER_EMPTY, true); - log.trace("RXTXPort:SerialOutputStream:flush() leave"); } finally { IOLockedMutex.readLock().unlock(); } @@ -1218,8 +1171,6 @@ public synchronized int read(byte b[], int off, int len) throws IOException { */ public synchronized int read(byte b[], int off, int len, byte t[]) throws IOException { - log.trace("RXTXPort:SerialInputStream:read(" + b.length + " " + off + " " + len - + ") called" /* + new String(b) */ ); int result; /* * Some sanity checks @@ -1419,7 +1370,6 @@ public static int staticGetStopBits(String port) throws UnsupportedCommOperation public static void staticSetSerialPortParams(String f, int b, int d, int s, int p) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticSetSerialPortParams( " + f + " " + b + " " + d + " " + s + " " + p); nativeStaticSetSerialPortParams(f, b, d, s, p); } @@ -1436,7 +1386,6 @@ public static void staticSetSerialPortParams(String f, int b, int d, int s, int */ public static boolean staticSetDSR(String port, boolean flag) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticSetDSR( " + port + " " + flag); return (nativeStaticSetDSR(port, flag)); } @@ -1453,7 +1402,6 @@ public static boolean staticSetDSR(String port, boolean flag) throws Unsupported */ public static boolean staticSetDTR(String port, boolean flag) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticSetDTR( " + port + " " + flag); return (nativeStaticSetDTR(port, flag)); } @@ -1470,7 +1418,6 @@ public static boolean staticSetDTR(String port, boolean flag) throws Unsupported */ public static boolean staticSetRTS(String port, boolean flag) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticSetRTS( " + port + " " + flag); return (nativeStaticSetRTS(port, flag)); } @@ -1486,7 +1433,6 @@ public static boolean staticSetRTS(String port, boolean flag) throws Unsupported */ public static boolean staticIsRTS(String port) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticIsRTS( " + port + " )"); return (nativeStaticIsRTS(port)); } /** @@ -1501,7 +1447,6 @@ public static boolean staticIsRTS(String port) throws UnsupportedCommOperationEx */ public static boolean staticIsCD(String port) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticIsCD( " + port + " )"); return (nativeStaticIsCD(port)); } /** @@ -1516,7 +1461,6 @@ public static boolean staticIsCD(String port) throws UnsupportedCommOperationExc */ public static boolean staticIsCTS(String port) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticIsCTS( " + port + " )"); return (nativeStaticIsCTS(port)); } /** @@ -1531,7 +1475,6 @@ public static boolean staticIsCTS(String port) throws UnsupportedCommOperationEx */ public static boolean staticIsDSR(String port) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticIsDSR( " + port + " )"); return (nativeStaticIsDSR(port)); } /** @@ -1546,7 +1489,6 @@ public static boolean staticIsDSR(String port) throws UnsupportedCommOperationEx */ public static boolean staticIsDTR(String port) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticIsDTR( " + port + " )"); return (nativeStaticIsDTR(port)); } /** @@ -1561,7 +1503,6 @@ public static boolean staticIsDTR(String port) throws UnsupportedCommOperationEx */ public static boolean staticIsRI(String port) throws UnsupportedCommOperationException { - log.trace("RXTXPort:staticIsRI( " + port + " )"); return (nativeStaticIsRI(port)); } @@ -1592,7 +1533,6 @@ public byte getParityErrorChar() throws UnsupportedCommOperationException { */ public boolean setParityErrorChar(byte b) throws UnsupportedCommOperationException { - log.trace("setParityErrorChar(" + b + ")"); return (nativeSetParityErrorChar(b)); } @@ -1621,7 +1561,6 @@ public byte getEndOfInputChar() throws UnsupportedCommOperationException { */ public boolean setEndOfInputChar(byte b) throws UnsupportedCommOperationException { - log.trace("setEndOfInputChar(" + b + ")"); return (nativeSetEndOfInputChar(b)); } @@ -1637,7 +1576,6 @@ public boolean setEndOfInputChar(byte b) throws UnsupportedCommOperationExceptio * @return boolean true on success UnsupportedCommOperationException; */ public boolean setUARTType(String type, boolean test) throws UnsupportedCommOperationException { - log.trace("RXTXPort:setUARTType()"); return nativeSetUartType(type, test); } /** @@ -1661,7 +1599,6 @@ public String getUARTType() throws UnsupportedCommOperationException { */ public boolean setBaudBase(int BaudBase) throws UnsupportedCommOperationException, IOException { - log.trace("RXTXPort:setBaudBase()"); return nativeSetBaudBase(BaudBase); }