public final class SerialComManager extends Object
Root of this library.
The WIKI page for this project is here : http://www.embeddedunveiled.com/
|
1: System information getOSTypegetCPUArchitecture |
2: Serial ports and device discovery listAvailableComPortslistUSBdevicesWithInfo findComPortFromUSBAttributes isUSBDevConnected |
|
3 : Miscellaneous openComPortcloseComPort createBlockingIOContext unblockBlockingIOOperation destroyBlockingIOContext fineTuneReadBehaviour clearPortIOBuffers getInterruptCount findDriverServingComPort findIRQnumberForComPort getByteCountInPortIOBuffer getPortName |
4 : Data exchange writeBytes (non-blocking)writeSingleByte (non-blocking) writeString (non-blocking) writeSingleInt (non-blocking) writeIntArray (non-blocking) writeBytesDirect (non-blocking) writeBytesBlocking (blocking) readBytes (blocking, non-blocking) readSingleByte (non-blocking) readString (non-blocking) readBytesDirect (non-blocking) readBytesBlocking (blocking) createInputByteStream (blocking, non-blocking) createOutputByteStream (blocking, non-blocking) |
|
5 : Serial port configuration and control configureComPortDataconfigureComPortControl getCurrentConfiguration getLinesStatus setRTS setDTR sendBreak |
6 : Data, control and hot plug events registerDataListenerunregisterDataListener registerLineEventListener unregisterLineEventListener registerUSBHotPlugEventListener unregisterUSBHotPlugEventListener |
|
7 : File transfer protocol sendFilereceiveFile |
8 : IOCTL operations getIOCTLExecutor |
|
9 : Vendor library interfaces getVendorLibInstance |
10 : Serial over USB getSerialComUSBInstance |
|
11 : Human interface device (HID) getSerialComHIDInstance |
12 : Serial data to application as keystroke getSerialComKeyStrokeAppInstance |
| Modifier and Type | Class and Description |
|---|---|
static class |
SerialComManager.BAUDRATE
Pre-defined enum constants for baud rate values.
|
static class |
SerialComManager.DATABITS
Pre-defined enum constants for number of data bits in a serial frame.
|
static class |
SerialComManager.ENDIAN
Pre-defined enum constants for defining endianness of data to be sent over serial port.
|
static class |
SerialComManager.FLOWCONTROL
Pre-defined enum constants for controlling data flow between DTE and DCE.
|
static class |
SerialComManager.FTPPROTO
Pre-defined enum constants for defining file transfer protocol to use.
|
static class |
SerialComManager.FTPVAR
Pre-defined enum constants for defining variant of file transfer protocol to use.
|
static class |
SerialComManager.NUMOFBYTES
Pre-defined enum constants for defining number of bytes given data can be represented in.
|
static class |
SerialComManager.PARITY
Pre-defined enum constants for enabling type of parity in a serial frame.
|
static class |
SerialComManager.SMODE
Pre-defined enum constants for defining behavior of byte stream.
|
static class |
SerialComManager.STOPBITS
Pre-defined enum constants for number of stop bits in a serial frame.
|
| Modifier and Type | Field and Description |
|---|---|
static int |
ABI_ARMEL
The value indicating soft float ABI.
|
static int |
ABI_ARMHF
The value indicating hard float ABI.
|
static int |
ARCH_AMD64
The common value indicating that the library is running on a 64 bit Intel x86_64 (x86-64/x64/Intel 64)
and AMD amd64 based architecture.
|
static int |
ARCH_ARMV5
The value indicating that the library is running on a ARMv5 based architecture CPU.
|
static int |
ARCH_ARMV6
The value indicating that the library is running on a ARMv6 soft float based JVM.
|
static int |
ARCH_ARMV7
The value indicating that the library is running on a ARMv7 soft float based JVM.
|
static int |
ARCH_IA64
The value indicating that the library is running on a 64 bit Intel/HP Itanium based architecture.
|
static int |
ARCH_IA64_32
The value indicating that the library is running on an IA64 32 bit based architecture.
|
static int |
ARCH_PA_RISC32
The value indicating that the library is running on a 32 bit PA-RISC based architecture.
|
static int |
ARCH_PA_RISC64
The value indicating that the library is running on a 64 bit PA-RISC based architecture.
|
static int |
ARCH_PPC32
The value indicating that the library is running on a 32 bit PowerPC based architecture from
Apple–IBM–Motorola.
|
static int |
ARCH_PPC64
The value indicating that the library is running on a 64 bit PowerPC based architecture from
Apple–IBM–Motorola.
|
static int |
ARCH_PPC64LE
The value indicating that the library is running on a 64 bit PowerPC based architecture in
little endian mode from Apple–IBM–Motorola.
|
static int |
ARCH_S390
The value indicating that the library is running on a 32 bit IBM S/390 system.
|
static int |
ARCH_S390X
The value indicating that the library is running on a 64 bit IBM S/390 system.
|
static int |
ARCH_SPARC32
The value indicating that the library is running on a 32 bit Sparc based architecture from
Sun Microsystems.
|
static int |
ARCH_SPARC64
The value indicating that the library is running on a 64 bit Sparc based architecture from
Sun Microsystems.
|
static int |
ARCH_UNKNOWN
The value indicating that platform architecture is unknown to SCM library.
|
static int |
ARCH_X86
The common value indicating that the library is running on a 32 bit Intel
i386/i486/i586/i686/i786/i886/i986/IA-32 based architecture.
|
static int |
CTS
Clear to send mask bit constant for UART control line.
|
static int |
DCD
Data carrier detect mask bit constant for UART control line.
|
static int |
DEFAULT_READBYTECOUNT
Default number of bytes (1024) to read from serial port.
|
static int |
DSR
Data set ready mask bit constant for UART control line.
|
static int |
DTR
Data terminal ready mask bit constant for UART control line.
|
static String |
EXP_UNBLOCKIO
The exception message indicating that a blocked read method has been unblocked
and made to return to caller explicitly (irrespective there was data to read or not).
|
static String |
JAVA_LIB_VERSION
Production release version of the serial communication manager library.
|
static int |
LOOP
Loop indicator mask bit constant for UART control line.
|
static int |
OS_ANDROID
The value indicating the Android operating system.
|
static int |
OS_FREEBSD
The value indicating the FreeBSD operating system..
|
static int |
OS_HP_UX
The value indicating the HP-UX operating system.
|
static int |
OS_IBM_AIX
The value indicating the IBM AIX operating system.
|
static int |
OS_LINUX
The value indicating the Linux operating system.
|
static int |
OS_MAC_OS_X
The value indicating the Mac OS X operating system.
|
static int |
OS_NETBSD
The value indicating the NetBSD operating system.
|
static int |
OS_OPENBSD
The value indicating the OpenBSD operating system.
|
static int |
OS_SOLARIS
The value indicating the Solaris operating system.
|
static int |
OS_UNKNOWN
The value indicating that operating system is unknown to SCM library.
|
static int |
OS_WINDOWS
The value indicating the Windows operating system.
|
static int |
RI
Ring indicator mask bit constant for UART control line.
|
static int |
RTS
Request to send mask bit constant for UART control line.
|
| Constructor and Description |
|---|
SerialComManager()
Allocates a new SerialComManager object.
|
SerialComManager(String directoryPath,
String loadedLibName)
Allocates a new SerialComManager object.
|
| Modifier and Type | Method and Description |
|---|---|
boolean |
clearPortIOBuffers(long handle,
boolean clearRxBuffer,
boolean clearTxBuffer)
Discards data sent to port but not transmitted, or data received but not read.
|
boolean |
closeComPort(long handle)
Close the serial port.
|
boolean |
configureComPortControl(long handle,
SerialComManager.FLOWCONTROL flowctrl,
char xon,
char xoff,
boolean ParFraError,
boolean overFlowErr)
This method configures the way data communication will be controlled between DTE and DCE.
|
boolean |
configureComPortData(long handle,
SerialComManager.DATABITS dataBits,
SerialComManager.STOPBITS stopBits,
SerialComManager.PARITY parity,
SerialComManager.BAUDRATE baudRate,
int custBaud)
This method configures the rate at which communication will occur and the format of UART frame.
|
long |
createBlockingIOContext()
Prepares a context that should be passed to readBytesBlocking, writeBytesBlocking,
readBytes, unblockBlockingIOOperation and destroyBlockingIOContext methods.
|
SerialComInByteStream |
createInputByteStream(long handle,
SerialComManager.SMODE streamMode)
Prepares context and returns an input streams of bytes for receiving data bytes from the
serial port.
|
SerialComOutByteStream |
createOutputByteStream(long handle,
SerialComManager.SMODE streamMode)
Prepares context and returns an output streams of bytes for transferring data bytes out of
serial port.
|
boolean |
destroyBlockingIOContext(long context)
Destroys the context that was created by a call to createBlockingIOContext method for
blocking I/O operations uses.
|
String[] |
findComPortFromUSBAttributes(int usbVidToMatch,
int usbPidToMatch,
String serialNumber)
Gives COM port (COMxx/ttySx) of a connected USB-UART device (CDC/ACM Interface) assigned by operating
system.
|
String |
findDriverServingComPort(String comPortName)
Gives the name of the driver who is driving the given serial port.
|
String |
findIRQnumberForComPort(long handle)
Gives the address and IRQ number associated with the given serial port.
|
boolean |
fineTuneReadBehaviour(long handle,
int vmin,
int vtime,
int rit,
int rttm,
int rttc)
This method gives more fine tune control to application for tuning performance and behavior of read
operations to leverage OS specific facility for read operation.
|
int[] |
getByteCountInPortIOBuffer(long handle)
Get number of bytes in input and output port buffers used by operating system for instance tty buffers
in Unix like systems.
|
int |
getCPUArchitecture()
Gives CPU/Platform architecture as identified by this library.
|
String[] |
getCurrentConfiguration(long handle)
This method gives currently applicable settings associated with particular serial port.
|
int |
getEventsMask(ISerialComEventListener eventListener)
This method return currently applicable mask for events on serial port.
|
int[] |
getInterruptCount(long handle)
This method gives the number of interrupts on serial line that have occurred.
|
SerialComIOCTLExecutor |
getIOCTLExecutor(long handle)
Prepares context for excuting IOCTL operations on the given port.
|
String |
getLibraryVersions()
Gives library versions of java and native library implementations.
|
int[] |
getLinesStatus(long handle)
Gives status of serial port's control lines as supported by underlying operating system.
|
int |
getOSType()
Gives operating system type as identified by this library.
|
String |
getPortName(long handle)
This method gives the port name with which given handle is associated.
|
SerialComBluetooth |
getSerialComBluetoothInstance(int btStack,
String directoryPath,
String loadedLibName)
Initialize and return an instance of SerialComBluetooth for the given bluetooth stack.
|
SerialComDBRelease |
getSerialComDBReleaseInstance(String directoryPath,
String loadedLibName)
Allocate, initialize and return an instance of SerialComDBRelease class on whom APIs can
be called to release COM ports in use.
|
SerialComHID |
getSerialComHIDInstance(int type,
String directoryPath,
String loadedLibName)
Allocate, initialize and return an instance of requested mode for communication with
HID device.
|
SerialComToKeyStrokeToApp |
getSerialComKeyStrokeAppInstance(long handle) |
SerialComPortMapper |
getSerialComPortMapperInstance(String directoryPath,
String loadedLibName)
Allocate, initialize and return an instance of SerialComPortMapper class on whom APIs can
be called to map or unmap a serial port alias.
|
SerialComUSB |
getSerialComUSBInstance()
Get an instance of SerialComUSB class for USB related operations.
|
SerialComVendorLib |
getVendorLibInstance(int vendorLibIdentifier,
String libDirectory,
String vlibName)
Gives an instance of the class which implements API defined by vendor in their propriety library.
|
boolean |
isUSBDevConnected(int vendorID,
int productID,
String serialNumber)
Checks whether a particular USB device identified by vendor id, product id and serial number is
connected to the system or not.
|
String[] |
listAvailableComPorts()
Returns all available UART style ports available on this system, otherwise an empty array of strings,
if no serial style port is found in the system.
|
SerialComBluetoothSPPDevNode[] |
listBTSPPDevNodesWithInfo()
Gives device node, remote bluetooth device address and channel number in use for device nodes
which are using the RFCOMM service for emulating serial port over bluetooth.
|
SerialComUSBdevice[] |
listUSBdevicesWithInfo(int vendorFilter)
Returns an array of SerialComUSBdevice class objects containing information about all the USB devices
found by this library.
|
long |
openComPort(String portName,
boolean enableRead,
boolean enableWrite,
boolean exclusiveOwnerShip)
Opens a serial port for communication.
|
boolean |
pauseListeningEvents(ISerialComEventListener eventListener)
This pauses delivering events to application.
|
byte[] |
readBytes(long handle)
If user does not specify any count, library try to read DEFAULT_READBYTECOUNT (1024 bytes)
bytes as default value.
|
int |
readBytes(long handle,
byte[] buffer,
int offset,
int length,
long context)
Reads data bytes from serial port into given buffer.
|
byte[] |
readBytes(long handle,
int byteCount)
Read specified number of bytes from given serial port.
|
byte[] |
readBytesBlocking(long handle,
int byteCount,
long context)
Read specified number of bytes from given serial port and stay blocked till bytes arrive
at serial port.
|
int |
readBytesDirect(long handle,
ByteBuffer buffer,
int offset,
int length)
Reads the bytes from the serial port into the given direct byte buffer using facilities of
the underlying JVM and operating system.
|
byte[] |
readSingleByte(long handle)
This is a utility method to read a single byte from serial port.
|
String |
readString(long handle)
This method reads data from serial port and converts it into string.
|
String |
readString(long handle,
int byteCount)
This method reads data from serial port and converts it into string.
|
boolean |
receiveFile(long handle,
File fileToReceive,
SerialComManager.FTPPROTO ftpProto,
SerialComManager.FTPVAR ftpVariant,
boolean textMode,
ISerialComXmodemProgress progressListener,
SerialComXModemAbort transferState)
Receives file using specified file transfer protocol.
|
boolean |
registerDataListener(long handle,
ISerialComDataListener dataListener)
This method associate a data looper with the given listener.
|
boolean |
registerLineEventListener(long handle,
ISerialComEventListener eventListener)
This method associate a event looper with the given listener.
|
int |
registerUSBHotPlugEventListener(ISerialComUSBHotPlugListener hotPlugListener,
int filterVID,
int filterPID,
String serialNumber)
This registers a listener who will be invoked whenever a USB device has been plugged or
un-plugged in system.
|
boolean |
resumeListeningEvents(ISerialComEventListener eventListener)
Resume delivering events kept in queue to application.
|
boolean |
sendBreak(long handle,
int duration)
Assert a break condition on the specified port for the duration expressed in milliseconds.
|
boolean |
sendFile(long handle,
File fileToSend,
SerialComManager.FTPPROTO ftpProto,
SerialComManager.FTPVAR ftpVariant,
boolean textMode,
ISerialComXmodemProgress progressListener,
SerialComXModemAbort transferState)
Send given file using specified file transfer protocol.
|
boolean |
setDTR(long handle,
boolean enabled)
This method assert/de-assert DTR line of serial port.
|
boolean |
setEventsMask(ISerialComEventListener eventListener,
int newMask)
Defines for which line events registered event listener will be called.
|
boolean |
setRTS(long handle,
boolean enabled)
This method assert/de-assert RTS line of serial port.
|
boolean |
unblockBlockingIOOperation(long context)
Unblocks any blocked operation if it exist.
|
boolean |
unregisterDataListener(long handle,
ISerialComDataListener dataListener)
This method destroys complete java and native looper subsystem associated with this particular data listener.
|
boolean |
unregisterLineEventListener(long handle,
ISerialComEventListener eventListener)
This method destroys complete java and native looper subsystem associated with this particular event listener.
|
boolean |
unregisterUSBHotPlugEventListener(int opaqueHandle)
This unregisters listener and terminate native thread used for monitoring specified USB device
insertion or removal.
|
boolean |
writeBytes(long handle,
byte[] buffer)
Utility method to call writeBytes without delay between successive bytes.
|
boolean |
writeBytes(long handle,
byte[] buffer,
int delay)
This method writes bytes from the specified byte type buffer.
|
boolean |
writeBytesBlocking(long handle,
byte[] buffer,
long context)
Write bytes from given buffer to the given handle in blocking mode.
|
int |
writeBytesDirect(long handle,
ByteBuffer buffer,
int offset,
int length)
Writes the bytes from the given direct byte buffer using facilities of the underlying JVM
and operating system.
|
boolean |
writeIntArray(long handle,
int[] buffer,
int delay,
SerialComManager.ENDIAN endianness,
SerialComManager.NUMOFBYTES numOfBytes)
This method send an array of integers on the specified port.
|
boolean |
writeSingleByte(long handle,
byte dataByte)
This method writes a single byte to the specified port.
|
boolean |
writeSingleInt(long handle,
int data,
int delay,
SerialComManager.ENDIAN endianness,
SerialComManager.NUMOFBYTES numOfBytes)
Different CPU and OS will have different endianness.
|
boolean |
writeString(long handle,
String data,
Charset charset,
int delay)
This method writes a string to the specified port.
|
boolean |
writeString(long handle,
String data,
int delay)
This method writes a string to the specified port.
|
public static final String JAVA_LIB_VERSION
Production release version of the serial communication manager library.
public static final int OS_UNKNOWN
The value indicating that operating system is unknown to SCM library. Integer constant with value 0x00.
public static final int OS_LINUX
The value indicating the Linux operating system. Integer constant with value 0x01.
public static final int OS_WINDOWS
The value indicating the Windows operating system. Integer constant with value 0x02.
public static final int OS_SOLARIS
The value indicating the Solaris operating system. Integer constant with value 0x03.
public static final int OS_MAC_OS_X
The value indicating the Mac OS X operating system. Integer constant with value 0x04.
public static final int OS_FREEBSD
The value indicating the FreeBSD operating system.. Integer constant with value 0x05.
public static final int OS_NETBSD
The value indicating the NetBSD operating system. Integer constant with value 0x06.
public static final int OS_OPENBSD
The value indicating the OpenBSD operating system. Integer constant with value 0x07.
public static final int OS_IBM_AIX
The value indicating the IBM AIX operating system. Integer constant with value 0x08.
public static final int OS_HP_UX
The value indicating the HP-UX operating system. Integer constant with value 0x09.
public static final int OS_ANDROID
The value indicating the Android operating system. Integer constant with value 0x0A.
public static final int ARCH_UNKNOWN
The value indicating that platform architecture is unknown to SCM library. Integer constant with value 0x00.
public static final int ARCH_X86
The common value indicating that the library is running on a 32 bit Intel i386/i486/i586/i686/i786/i886/i986/IA-32 based architecture. Integer constant with value 0x01.
public static final int ARCH_AMD64
The common value indicating that the library is running on a 64 bit Intel x86_64 (x86-64/x64/Intel 64) and AMD amd64 based architecture. Integer constant with value 0x02.
public static final int ARCH_IA64
The value indicating that the library is running on a 64 bit Intel/HP Itanium based architecture. Integer constant with value 0x03.
public static final int ARCH_IA64_32
The value indicating that the library is running on an IA64 32 bit based architecture. Integer constant with value 0x04.
public static final int ARCH_PPC32
The value indicating that the library is running on a 32 bit PowerPC based architecture from Apple–IBM–Motorola. Integer constant with value 0x05.
public static final int ARCH_PPC64
The value indicating that the library is running on a 64 bit PowerPC based architecture from Apple–IBM–Motorola. Integer constant with value 0x06.
public static final int ARCH_PPC64LE
The value indicating that the library is running on a 64 bit PowerPC based architecture in little endian mode from Apple–IBM–Motorola. Integer constant with value 0x06.
public static final int ARCH_SPARC32
The value indicating that the library is running on a 32 bit Sparc based architecture from Sun Microsystems. Integer constant with value 0x07.
public static final int ARCH_SPARC64
The value indicating that the library is running on a 64 bit Sparc based architecture from Sun Microsystems. Integer constant with value 0x08.
public static final int ARCH_PA_RISC32
The value indicating that the library is running on a 32 bit PA-RISC based architecture. Integer constant with value 0x09.
public static final int ARCH_PA_RISC64
The value indicating that the library is running on a 64 bit PA-RISC based architecture. Integer constant with value 0x0A.
public static final int ARCH_S390
The value indicating that the library is running on a 32 bit IBM S/390 system. Integer constant with value 0x0B.
public static final int ARCH_S390X
The value indicating that the library is running on a 64 bit IBM S/390 system. Integer constant with value 0x0C.
public static final int ARCH_ARMV5
The value indicating that the library is running on a ARMv5 based architecture CPU. Integer constant with value 0x0D.
public static final int ARCH_ARMV6
The value indicating that the library is running on a ARMv6 soft float based JVM. Integer constant with value 0x0E.
public static final int ARCH_ARMV7
The value indicating that the library is running on a ARMv7 soft float based JVM. Integer constant with value 0x10.
public static final int ABI_ARMHF
The value indicating hard float ABI.
public static final int ABI_ARMEL
The value indicating soft float ABI.
public static final int DEFAULT_READBYTECOUNT
Default number of bytes (1024) to read from serial port.
public static final int CTS
Clear to send mask bit constant for UART control line.
public static final int DSR
Data set ready mask bit constant for UART control line.
public static final int DCD
Data carrier detect mask bit constant for UART control line.
public static final int RI
Ring indicator mask bit constant for UART control line.
public static final int LOOP
Loop indicator mask bit constant for UART control line.
public static final int RTS
Request to send mask bit constant for UART control line.
public static final int DTR
Data terminal ready mask bit constant for UART control line.
public static final String EXP_UNBLOCKIO
The exception message indicating that a blocked read method has been unblocked and made to return to caller explicitly (irrespective there was data to read or not).
public SerialComManager()
throws SecurityException,
SerialComUnexpectedException,
SerialComLoadException,
UnsatisfiedLinkError,
SerialComException,
FileNotFoundException,
IOException
Allocates a new SerialComManager object. Identify operating system type, CPU architecture, prepares environment required for running this library, initiates extraction and loading of native libraries.
The native shared library will be extracted in folder named 'scm_tuartx1' inside system/user 'temp' folder or user home folder if access to 'temp' folder is denied.
SecurityException - if java system properties can not be accessed.SerialComUnexpectedException - if java system property is null.SerialComLoadException - if any file system related issue occurs.UnsatisfiedLinkError - if loading/linking shared library fails.FileNotFoundException - if file "/proc/cpuinfo" can not be found for Linux on ARM platform.IOException - if file operations on "/proc/cpuinfo" fails for Linux on ARM platform.SerialComException - if initializing native library fails.public SerialComManager(String directoryPath, String loadedLibName) throws SecurityException, SerialComUnexpectedException, SerialComLoadException, UnsatisfiedLinkError, SerialComException, FileNotFoundException, IOException
Allocates a new SerialComManager object. Identify operating system type, CPU architecture, prepares environment required for running this library, initiates extraction and loading of native libraries.
It extracts native shared library in the folder specified by argument directoryPath and gives library name specified by loadedLibName. This helps in increasing isolation as completely independent applications might also be using this library. Using different folders make sure that independent applications unaware if each other does not override shared library file in file system.
This also increase security as the folder may be given specific user permissions.
directoryPath - absolute path of directory for extraction.loadedLibName - library name without extension (do not append .so, .dll or .dylib etc.).SecurityException - if java system properties can not be accessed.SerialComUnexpectedException - if java system property is null.SerialComLoadException - if any file system related issue occurs.UnsatisfiedLinkError - if loading/linking shared library fails.FileNotFoundException - if file "/proc/cpuinfo" can not be found for Linux on ARM platform.IOException - if file operations on "/proc/cpuinfo" fails for Linux on ARM platform.SerialComException - if initializing native library fails.IllegalArgumentException - if directoryPath is null, directoryPath is empty,
loadedLibName is null or empty.public String getLibraryVersions() throws SerialComException
Gives library versions of java and native library implementations.
SerialComException - if native library version could not be determined.public int getOSType()
Gives operating system type as identified by this library. To interpret returned integer value see the OS_xxxxx defined in SerialComManager class.
This method may be used to develop application with consistent behavior across different operating systems. For example let us assume that in a poll based application calling Thread.sleep(10) make ~10 milliseconds sleep in Linux operating system but causes ~50 milliseconds sleep in Windows because these operating system may have different resolution for sleep timings. To deal with this write the application code in following manner :
int osType = scm.getOSType();
if(osType == SerialComManager.OS_LINUX) {
Thread.sleep(10);
}else if(osType == SerialComManager.OS_WINDOWS) {
Thread.sleep(1);
}else {
Thread.sleep(5);
}
public int getCPUArchitecture()
Gives CPU/Platform architecture as identified by this library. To interpret return integer see constants defined SerialComManager class.
public String[] listAvailableComPorts() throws SerialComException
Returns all available UART style ports available on this system, otherwise an empty array of strings, if no serial style port is found in the system.
This should find regular UART ports, hardware/software virtual COM ports, port server, USB-UART converter, bluetooth/3G dongles, ports connected through USB hub/expander, serial card, serial controller, pseudo terminals, printers and virtual modems etc.
This method may be used to find valid serial ports for communications before opening them for writing more robust application.
Note : The BIOS may ignore UART ports on a PCI card and therefore BIOS settings has to be corrected if you modified default BIOS in OS.
SerialComException - if an I/O error occurs.public SerialComUSBdevice[] listUSBdevicesWithInfo(int vendorFilter) throws SerialComException
Returns an array of SerialComUSBdevice class objects containing information about all the USB devices found by this library. Application can call various methods on SerialComUSBdevice object to get specific information like vendor id and product id etc. The GUI applications may display a dialogue box asking user to connect the end product if the desired product is still not connected to system.
The USB vendor id, USB product id, serial number, product name and manufacturer information is encapsulated in the object of class SerialComUSBdevice returned.
Some USB-UART chip manufactures may give some unique USB PID(s) to end product manufactures at minimal or no cost. Applications written for these end products may be interested in finding devices only from the USB-UART chip manufacturer. For example, an application built for finger print scanner based on FT232 IC will like to list only those devices whose VID matches VID of FTDI. Then further application may verify PID by calling methods on the USBDevice object. For this purpose argument vendorFilter may be used.
vendorFilter - vendor whose devices should be listed (one of the constants SerialComUSB.V_xxxxx or
any valid USB VID).SerialComException - if an I/O error occurs.IllegalArgumentException - if vendorFilter is negative or invalid number.public String[] findComPortFromUSBAttributes(int usbVidToMatch, int usbPidToMatch, String serialNumber) throws SerialComException
Gives COM port (COMxx/ttySx) of a connected USB-UART device (CDC/ACM Interface) assigned by operating system.
Assume a bar code scanner using FTDI chip FT232R is to be used by application at point of sale. First we need to know whether it is connect to system or not. This can be done using listUSBdevicesWithInfo() or by using USB hot plug listener depending upon application design.
Once it is known that the device is connected to system, we application need to open it. For this, application needs to know the COM port number or device node corresponding to the scanner. It is for this purpose this method can be used.
Another use case of this API is to align application design with true spirit of USB hot plugging in operating system. When a USB-UART device is connected, OS may assign different COM port number or device node to the same device depending upon system scenario. Generally we need to write custom udev rules so that device node will be same. Using this API this limitation can be overcome.
The reason why this method returns array instead of string is that two or more USB-UART converters connected to system might have exactly same USB attributes. So this will list COM ports assigned to all of them.
usbVidToMatch - USB vendor id of the device to match.usbPidToMatch - USB product id of the device to match.serialNumber - USB serial number (case insensitive, optional) of device to match or null if not
to be matched.SerialComException - if an I/O error occurs.IllegalArgumentException - if usbVidToMatch or usbPidToMatch is negative or or invalid number.public SerialComBluetoothSPPDevNode[] listBTSPPDevNodesWithInfo() throws SerialComException
Gives device node, remote bluetooth device address and channel number in use for device nodes which are using the RFCOMM service for emulating serial port over bluetooth.
SerialComException - if an I/O error occurs.public long openComPort(String portName, boolean enableRead, boolean enableWrite, boolean exclusiveOwnerShip) throws SerialComException
Opens a serial port for communication. If an attempt is made to open a port which is already opened exception in throw.
For Windows the exclusiveOwnerShip must be true as it does not allow sharing COM ports. An exception is thrown if exclusiveOwnerShip is set to false.
For Solaris, exclusiveOwnerShip should be set to false as of now.
This method is thread safe.
portName - name of the port to be opened for communication.enableRead - allows application to read bytes from this port.enableWrite - allows application to write bytes to this port.exclusiveOwnerShip - application wants to become exclusive owner of this port or not.SerialComException - if trying to become exclusive owner when port is already opened.IllegalArgumentException - if portName is null or invalid length, or if both enableRead and
enableWrite are set to false, if trying to open port in Windows without being exclusive owner.public boolean closeComPort(long handle)
throws SerialComException
Close the serial port. Application should unregister listeners if it has registered any before calling this method.
DTR line is dropped when port is closed.
This method is thread safe.
handle - of the port to be closed.SerialComException - if invalid handle is passed or when it fails in closing the port.IllegalStateException - if application tries to close port while data/event listeners,
or input/output byte streams exist.public boolean writeBytes(long handle,
byte[] buffer,
int delay)
throws SerialComException
This method writes bytes from the specified byte type buffer. If the method returns false, the application should try to re-send bytes. The data has been transmitted out of serial port when this method returns.
If large amount of data need to be written, consider breaking it into chunks of data of size for example 2KB each.
Writing empty buffer i.e. zero length array is not allowed.
It should be noted that on Linux system reading from the terminal after a disconnect causes an end-of-file condition, and writing causes an EIO error to be returned. The terminal device must be closed and reopened to clear the condition.
handle - handle of the opened port on which to write bytes.buffer - byte type buffer containing bytes to be written to port.delay - time gap between transmitting two successive bytes.SerialComException - if an I/O error occurs.IllegalArgumentException - if buffer is null or delay is negative.public boolean writeBytes(long handle,
byte[] buffer)
throws SerialComException
Utility method to call writeBytes without delay between successive bytes.
The writeBytes(handle, buffer) method for class SerialComManager has the same effect as:
writeBytes(handle, buffer, 0)
handle - handle of the opened port on which to write bytes.buffer - byte type buffer containing bytes to be written to port.SerialComException - if an I/O error occurs.IllegalArgumentException - if buffer is null.public boolean writeSingleByte(long handle,
byte dataByte)
throws SerialComException
This method writes a single byte to the specified port. The data has been transmitted out of serial port when this method returns.
handle - handle of the opened port on which to write byte.dataByte - byte to be written to port.SerialComException - if an I/O error occurs.public boolean writeString(long handle,
String data,
int delay)
throws SerialComException
This method writes a string to the specified port. The library internally converts string to byte buffer. The data has been transmitted out of serial port when this method returns.
handle - handle of the opened port on which to write byte.data - the string to be send to port.delay - interval between two successive bytes while sending string.SerialComException - if an I/O error occurs.IllegalArgumentException - if data is null.public boolean writeString(long handle,
String data,
Charset charset,
int delay)
throws UnsupportedEncodingException,
SerialComException
This method writes a string to the specified port. The library internally converts string to byte buffer. The data has been transmitted out of serial port when this method returns.
handle - handle of the opened port on which to write byte.data - the string to be send to port.charset - the character set into which given string will be encoded.delay - time gap between transmitting two successive bytes in this string.SerialComException - if an I/O error occurs.IllegalArgumentException - if data is null.UnsupportedEncodingExceptionpublic boolean writeSingleInt(long handle,
int data,
int delay,
SerialComManager.ENDIAN endianness,
SerialComManager.NUMOFBYTES numOfBytes)
throws SerialComException
Different CPU and OS will have different endianness. It is therefore we handle the endianness conversion as per the requirement. If the given integer is in range −32,768 to 32,767, only two bytes will be needed. In such case we might like to send only 2 bytes to serial port. On the other hand application might be implementing some custom protocol so that the data must be 4 bytes (irrespective of its range) in order to be interpreted correctly by the receiver terminal. This method assumes that integer value can be represented by 32 or less number of bits. On x86_64 architecture, loss of precision will occur if the integer value is of more than 32 bit.
The data has been transmitted physically out of serial port when this method returns.
In java numbers are represented in 2's complement, so number 650 whose binary representation is 0000001010001010 is printed byte by byte, then will be printed as 1 and -118, because 10001010 in 2's complement is negative number.
handle - handle of the opened port on which to write byte.data - an integer number to be sent to port.delay - interval between two successive bytes .endianness - big or little endian sequence to be followed while sending bytes representing
this integer.numOfBytes - number of bytes this integer can be represented in.SerialComException - if an I/O error occurs.IllegalArgumentException - if endianness or numOfBytes is null.public boolean writeIntArray(long handle,
int[] buffer,
int delay,
SerialComManager.ENDIAN endianness,
SerialComManager.NUMOFBYTES numOfBytes)
throws SerialComException
This method send an array of integers on the specified port. The data has been transmitted out of serial port when this method returns.
handle - handle of the opened port on which to write byte.buffer - an array of integers to be sent to port.delay - interval between two successive bytes .endianness - big or little endian sequence to be followed while sending bytes representing
this integer.numOfBytes - number of bytes this integer can be represented in.SerialComException - if an I/O error occurs.IllegalArgumentException - if endianness or numOfBytes is null.public int writeBytesDirect(long handle,
ByteBuffer buffer,
int offset,
int length)
throws SerialComException
Writes the bytes from the given direct byte buffer using facilities of the underlying JVM and operating system. When this method returns data would have sent out of serial port physically.
Consider using this method when developing applications based on Bluetooth serial port profile or applications like printing document using printer.
This method does not modify the direct byte buffer attributes position, capacity, limit and mark. The application design is expected to take care of this as and when required in appropriate manner. Further, this method does not consume or modify the data in the given buffer.
handle - handle of the serial port on which to write bytes.buffer - direct byte buffer containing bytes to be written to port.offset - location from where to start sending data out of serial port.length - number of bytes from offset to sent to serial port.SerialComException - if an I/O error occurs.IllegalArgumentException - if buffer is null, or if position or limit is negative,
or if given buffer is not direct byte buffer, or if length > (buffer.capacity() - offset).public boolean writeBytesBlocking(long handle,
byte[] buffer,
long context)
throws SerialComException
Write bytes from given buffer to the given handle in blocking mode.
Writing empty buffer i.e. zero length array is not allowed.
handle - handle of the opened port on which to write bytes.buffer - byte type buffer containing bytes to be written to port.context - context value obtained form call to createBlockingIOContext method.SerialComException - if an I/O error occurs.IllegalArgumentException - if buffer is null.public int readBytesDirect(long handle,
ByteBuffer buffer,
int offset,
int length)
throws SerialComException
Reads the bytes from the serial port into the given direct byte buffer using facilities of the underlying JVM and operating system.
This method does not modify the direct byte buffer attributes position, capacity, limit and mark. The application design is expected to take care of this as and when required in appropriate manner.
handle - handle of the serial port from which to read data bytes.buffer - direct byte buffer into which data bytes will be placed.offset - location in byte buffer from which to start saving data.length - number of bytes from offset to read in buffer.SerialComException - if an I/O error occurs.IllegalArgumentException - if buffer is null, or if position or limit is negative, or if
given buffer is not direct byte buffer.public long createBlockingIOContext()
throws SerialComException
Prepares a context that should be passed to readBytesBlocking, writeBytesBlocking, readBytes, unblockBlockingIOOperation and destroyBlockingIOContext methods.
SerialComException - if an I/O error occurs.public boolean unblockBlockingIOOperation(long context)
throws SerialComException
Unblocks any blocked operation if it exist. This causes closing of serial port possible gracefully and return the worker thread that called blocking read/write to return and proceed as per application design.
context - context obtained from call to createBlockingIOContext method for blocking
I/O operations.SerialComException - if an I/O error occurs.public boolean destroyBlockingIOContext(long context)
throws SerialComException
Destroys the context that was created by a call to createBlockingIOContext method for blocking I/O operations uses.
context - context obtained from call to createBlockingIOContext method for blocking
I/O operations.SerialComException - if an I/O error occurs.public byte[] readBytesBlocking(long handle,
int byteCount,
long context)
throws SerialComException
Read specified number of bytes from given serial port and stay blocked till bytes arrive at serial port.
1. If data is read from serial port, array of bytes containing data is returned.
2. If there was no data in serial port to read, null is returned. Note that this case is not possible however for blocking read call.
The number of bytes to read must be greater than or equal to 1 and less than or equal to 2048 (1 <= byteCount <= 2048). This method may return less than the requested number of bytes due to reasons like, there is less data in operating system buffer (serial port) or operating system returned less data which is also legal.
Application must catch exception thrown by this method. When this method returns and exception with message SerialComManager.EXP_UNBLOCKIO is thrown, it indicates that the blocked read method was explicitly unblocked by another thread (possibly because serial port is going to be closed).
handle - of the serial port from which to read bytes.byteCount - number of bytes to read from serial port.context - context obtained by a call to createBlockingIOContext method.SerialComException - if an I/O error occurs or if byteCount is greater than 2048.public byte[] readBytes(long handle,
int byteCount)
throws SerialComException
Read specified number of bytes from given serial port.
1. If data is read from serial port, array of bytes containing data is returned.
2. If there was no data in serial port to read, null is returned.
The number of bytes to read must be greater than or equal to 1 and less than or equal to 2048 (1 <= byteCount <= 2048). This method may return less than the requested number of bytes due to reasons like, there is less data in operating system buffer (serial port) or operating system returned less data which is also legal.
handle - of the serial port from which to read bytes.byteCount - number of bytes to read from serial port.SerialComException - if an I/O error occurs or if byteCount is greater than 2048.public byte[] readBytes(long handle)
throws SerialComException
If user does not specify any count, library try to read DEFAULT_READBYTECOUNT (1024 bytes) bytes as default value.
It has same effect as readBytes(handle, 1024)
handle - of the port from which to read bytes.SerialComException - if an I/O error occurs.public String readString(long handle, int byteCount) throws SerialComException
This method reads data from serial port and converts it into string.
It Constructs a new string by decoding the specified array of bytes using the platform's default charset. The length of the new string is a function of the charset, and hence may not be equal to the length of the byte array read from serial port.
handle - of port from which to read bytes.byteCount - number of bytes to read from this port.SerialComException - if an I/O error occurs or if byteCount is greater than 2048.public String readString(long handle) throws SerialComException
This method reads data from serial port and converts it into string.
It Constructs a new string by decoding the specified array of bytes using the platform's default charset. The length of the new string is a function of the charset, and hence may not be equal to the length of the byte array read from serial port.
Note that the length of data bytes read using this method can not be greater than DEFAULT_READBYTECOUNT i.e. 1024.
handle - of the port from which to read bytes.SerialComException - if an I/O error occurs.public byte[] readSingleByte(long handle)
throws SerialComException
This is a utility method to read a single byte from serial port.
Its effect is same as readBytes(handle, 1)
handle - of the port from which to read byte.SerialComException - if an I/O error occurs.public int readBytes(long handle,
byte[] buffer,
int offset,
int length,
long context)
throws SerialComException
Reads data bytes from serial port into given buffer. This method is mainly intended for use in application design which needs to poll serial port continuously for presence of data.
This method can be used in blocking mode or non-blocking mode. If context is -1, this method will not block. For blocking behavior pass context value obtained by call to createBlockingIOContext method. If a valid context is passed, this method will block until there is data to read from serial port.
Application must catch exception thrown by this method if using blocking mode. When this method returns and exception with message SerialComManager.EXP_UNBLOCKIO is thrown, it indicates that the blocked read method was explicitly unblocked by another thread (possibly because serial port is going to be closed).
handle - of the port from which to read data bytes.buffer - data byte buffer in which bytes from serial port will be saved.offset - index in given byte array at which first data byte will be placed.length - number of bytes to read into given buffer (0 <= length <= 2048).context - context obtained by call to createBlockingIOContext method for blocking behavior
or -1 for non-blocking behavior.SerialComException - if an I/O error occurs.NullPointerException - if buffer is null.IndexOutOfBoundsException - if offset is negative, length is negative, or length is
greater than buffer.length - offset.public boolean configureComPortData(long handle,
SerialComManager.DATABITS dataBits,
SerialComManager.STOPBITS stopBits,
SerialComManager.PARITY parity,
SerialComManager.BAUDRATE baudRate,
int custBaud)
throws SerialComException
This method configures the rate at which communication will occur and the format of UART frame. This method must be called before configureComPortControl method.
[1] Most of the DTE/DCE (hardware) does not support different baud rates for transmission and reception and therefore this method takes only single value applicable to both transmission and reception.
[2] All serial devices/drivers/operating systems does not support all the baud rates (maximum change in signal per second), stop bits, data bits etc. Please consult hardware and software manuals as appropriate.[3] If parity is enabled, the parity bit will be removed from UART frame before passing it to this library.
[4] Some USB-UART devices supports non-standard baudrates. How to set these baudrate is device/driver and operating system specific.handle - of opened port to which this configuration applies to.dataBits - number of data bits in one frame (refer DATABITS enum in SerialComManager class for this).stopBits - number of stop bits in one frame (refer STOPBITS enum in SerialComManager class for this).parity - of the frame (refer PARITY enum in SerialComManager class for this).baudRate - of the frame (refer BAUDRATE enum in SerialComManager class for this).custBaud - custom baudrate if the desired rate is not included in BAUDRATE enum.SerialComException - if invalid handle is passed or an error occurs in configuring the port.IllegalArgumentException - if dataBits or stopBits or parity or baudRate is null, or if custBaud is zero or negative.public boolean configureComPortControl(long handle,
SerialComManager.FLOWCONTROL flowctrl,
char xon,
char xoff,
boolean ParFraError,
boolean overFlowErr)
throws SerialComException
This method configures the way data communication will be controlled between DTE and DCE. This specifies flow control and actions that will be taken when an error is encountered in communication.
Some serial devices does not support some flow controls scheme. Please refer to their manuals.
handle - of opened port to which need to be configured.flowctrl - flow control, how data flow will be controlled (refer FLOWCONTROL enum for this).xon - character representing on condition if software flow control is used.xoff - character representing off condition if software flow control is used.ParFraError - true if parity and frame errors are to be checked false otherwise.overFlowErr - true if overflow error is to be detected false otherwise.SerialComException - if invalid handle is passed or an error occurs in configuring the port.IllegalArgumentException - if flowctrl is null.public String[] getCurrentConfiguration(long handle) throws SerialComException
This method gives currently applicable settings associated with particular serial port. The values are bit mask so that application can manipulate them to get required information.
For Unix-like OS the order is : c_iflag, c_oflag, c_cflag, c_lflag, c_line, c_cc[0], c_cc[1], c_cc[2], c_cc[3] c_cc[4], c_cc[5], c_cc[6], c_cc[7], c_cc[8], c_cc[9], c_cc[10], c_cc[11], c_cc[12], c_cc[13], c_cc[14], c_cc[15], c_cc[16], c_ispeed and c_ospeed.
For Windows OS the order is :DCBlength, BaudRate, fBinary, fParity, fOutxCtsFlow, fOutxDsrFlow, fDtrControl, fDsrSensitivity, fTXContinueOnXoff, fOutX, fInX, fErrorChar, fNull, fRtsControl, fAbortOnError, fDummy2, wReserved, XonLim, XoffLim, ByteSize, Parity, StopBits, XonChar, XoffChar, ErrorChar, StopBits, EvtChar, wReserved1.
handle - of the opened port.SerialComException - if invalid handle is passed or an error occurs while reading current settings.public boolean setRTS(long handle,
boolean enabled)
throws SerialComException
This method assert/de-assert RTS line of serial port. Set "true" for asserting signal, false otherwise. This changes the state of RTS line electrically.
RTS and DTR lines can be asserted or de-asserted even when using no flow control on serial port.
The RS-232 standard defines the voltage levels that correspond to logical one and logical zero levels for the data transmission and the control signal lines. Valid signals are either in the range of +3 to +15 volts or the range −3 to −15 volts with respect to the ground/common pin; consequently, the range between −3 to +3 volts is not a valid RS-232 level.
In asserted condition, voltage at pin number 7 (RTS signal) will be greater than 3 volts. Voltage 5.0 volts was observed when using USB-UART converter : http://www.amazon.in/Bafo-USB-Serial-Converter-DB9/dp/B002SCRCDG.
On some hardware IC, signals may be active low and therefore for actual voltage datasheet should be consulted. Also please check if the driver supports setting RTS/DTR lines or not.
handle - of the opened port.enabled - if true RTS will be asserted and vice-versa.SerialComException - if system is unable to complete requested operation.public boolean setDTR(long handle,
boolean enabled)
throws SerialComException
This method assert/de-assert DTR line of serial port. Set "true" for asserting signal, false otherwise. This changes the state of RTS line electrically.
RTS and DTR lines can be asserted or de-asserted even when a serial port is configured as 'flow control none'.
It is possible to establish PPP connections to transmit binary data over a two (or more) wire interface with full handshaking and modem control signaling if the driver is configured for this. Refer application note from FTDI for details : AN232B-09 Using the Modem Emulation Mode in FTDI's VCP Driver.
handle - of the opened port.enabled - if true DTR will be asserted and vice-versa.SerialComException - if system is unable to complete requested operation.public boolean registerDataListener(long handle,
ISerialComDataListener dataListener)
throws SerialComException
This method associate a data looper with the given listener. This looper will keep delivering new data whenever it is made available from native data collection and dispatching subsystem. Note that listener will start receiving new data, even before this method returns.
Application (listener) should implement ISerialComDataListener and override onNewSerialDataAvailable method.
The scm library can manage upto 1024 listeners corresponding to 1024 port handles. Application should not register data listener more than once for the same port otherwise it will lead to inconsistent state.
This method is thread safe.
handle - of the serial port for which given listener will listen for availability of data bytes.dataListener - instance of class which implements ISerialComDataListener interface.SerialComException - if invalid handle passed, handle is null or data listener already exist for this handle.IllegalArgumentException - if dataListener is null.public boolean unregisterDataListener(long handle,
ISerialComDataListener dataListener)
throws SerialComException
This method destroys complete java and native looper subsystem associated with this particular data listener. This has no effect on event looper subsystem. This method returns only after native thread has been terminated successfully.
This method is thread safe.
handle - handle of the serial port for which this data listener was registered.dataListener - instance of class which implemented ISerialComDataListener interface.SerialComException - if null value is passed in dataListener field.IllegalArgumentException - if dataListener is null.public boolean registerLineEventListener(long handle,
ISerialComEventListener eventListener)
throws SerialComException
This method associate a event looper with the given listener. This looper will keep delivering new event whenever it is made available from native event collection and dispatching subsystem.
Application (listener) should implement ISerialComEventListener and override onNewSerialEvent method.
By default all four events are dispatched to listener. However, application can mask events through setEventsMask() method. In current implementation, native code sends all the events irrespective of mask and we actually filter them in java layers, to decide whether this should be sent to application or not (as per the mask set by setEventsMask() method).
Before calling this method, make sure that port has been configured for hardware flow control using configureComPortControl method. Application should not register event listener more than once for the same port otherwise it will lead to inconsistent state.
This method is thread safe.
handle - of the port opened.eventListener - instance of class which implements ISerialComEventListener interface.SerialComException - if invalid handle passed, handle is null or event listener already exist for this handle.IllegalArgumentException - if eventListener is null.public boolean unregisterLineEventListener(long handle,
ISerialComEventListener eventListener)
throws SerialComException
This method destroys complete java and native looper subsystem associated with this particular event listener. This has no effect on data looper subsystem.
This method is thread safe.
handle - handle for which this listener was registered.eventListener - instance of class which implemented ISerialComEventListener interface.SerialComException - if an error occurs.IllegalArgumentException - if eventListener is null.public boolean pauseListeningEvents(ISerialComEventListener eventListener) throws SerialComException
This pauses delivering events to application. The events kept accumulating in queue.
eventListener - instance of class which implemented ISerialComEventListener interface.SerialComException - if null is passed for eventListener field.IllegalArgumentException - if eventListener is null.public boolean resumeListeningEvents(ISerialComEventListener eventListener) throws SerialComException
Resume delivering events kept in queue to application.
eventListener - is an instance of class which implements ISerialComEventListener.SerialComException - if error occurs.IllegalArgumentException - if eventListener is null.public boolean fineTuneReadBehaviour(long handle,
int vmin,
int vtime,
int rit,
int rttm,
int rttc)
throws SerialComException
This method gives more fine tune control to application for tuning performance and behavior of read operations to leverage OS specific facility for read operation. The read operations can be optimized for receiving for example high volume data speedily or low volume data but received in burst mode.
If more than one client has opened the same port, then all the clients will be affected by new settings.
When this method is called application should make sure that previous read or write operation is not in progress.
handle - of the opened port.vmin - c_cc[VMIN] field of termios structure.vtime - c_cc[VTIME] field of termios structure (10th of a second).rit - ReadIntervalTimeout field of COMMTIMEOUTS structure.rttm - ReadTotalTimeoutMultiplier field of COMMTIMEOUTS structure.rttc - ReadTotalTimeoutConstant field of COMMTIMEOUTS structure.SerialComException - if wrong handle is passed or operation can not be done successfully.IllegalArgumentException - if invalid combination of arguments is passed.public boolean setEventsMask(ISerialComEventListener eventListener, int newMask) throws SerialComException
Defines for which line events registered event listener will be called.
In future we may shift modifying mask in the native code itself, so as to prevent JNI transitions. This filters what events should be sent to application. Note that, although we sent only those event for which user has set mask, however native code send all the events to java layer as of now.
eventListener - instance of class which implemented ISerialComEventListener interface.SerialComException - if invalid listener is passed.IllegalArgumentException - if eventListener is null.public int getEventsMask(ISerialComEventListener eventListener) throws SerialComException
This method return currently applicable mask for events on serial port.
eventListener - instance of class which implemented ISerialComEventListener interface.SerialComException - if null or wrong listener is passed.IllegalArgumentException - if eventListener is null.public boolean clearPortIOBuffers(long handle,
boolean clearRxBuffer,
boolean clearTxBuffer)
throws SerialComException
Discards data sent to port but not transmitted, or data received but not read. Some device/OS/driver might not have support for this, but most of them may have. If there is some data to be pending for transmission, it will be discarded and therefore no longer sent. If the application wants to make sure that all data has been transmitted before discarding anything, it must first flush data and then call this method.
handle - of the opened port.clearRxBuffer - if true receive buffer will be cleared otherwise will be left untouched.clearTxBuffer - if true transmit buffer will be cleared otherwise will be left untouched.SerialComException - if invalid handle is passed or operation can not be completed successfully.IllegalArgumentException - if both purgeTxBuffer and purgeRxBuffer are false.public boolean sendBreak(long handle,
int duration)
throws SerialComException
Assert a break condition on the specified port for the duration expressed in milliseconds. If the line is held in the logic low condition (space in UART jargon) for longer than a character time, this is a break condition that can be detected by the UART.
A "break condition" occurs when the receiver input is at the "space" level for longer than some duration of time, typically, for more than a character time. This is not necessarily an error, but appears to the receiver as a character of all zero bits with a framing error. The term "break" derives from current loop Signaling, which was the traditional signaling used for tele-typewriters. The "spacing" condition of a current loop line is indicated by no current flowing, and a very long period of no current flowing is often caused by a break or other fault in the line.
Recognizing break condition on line is the responsibility of the UART IC, but if for some reason (such as a limited UART that does not implement this functionality) the UART fails to do so, reception of a break will manifest itself as a large number of framing errors.All UART devices (or driver) may not support all break timings. For example CP2105 can set break for from 1 to 125 ms or for infinite time. Developers should consult data sheet to know device capabilities.
handle - of the opened port.duration - the time in milliseconds for which break will be active.SerialComException - if invalid handle is passed or operation can not be successfully completed.IllegalArgumentException - if duration is zero or negative.public int[] getInterruptCount(long handle)
throws SerialComException
This method gives the number of interrupts on serial line that have occurred. The interrupt count is in following order in array beginning from index 0 and ending at index 11 : CTS, DSR, RING, CARRIER DETECT, RECEIVER BUFFER, TRANSMIT BUFFER, FRAME ERROR, OVERRUN ERROR, PARITY ERROR, BREAK AND BUFFER OVERRUN.
This is applicable for Linux onle. For other operating systems, this will return 0 for all the indexes.
handle - of the port opened on which interrupts might have occurred.SerialComException - if invalid handle is passed or operation can not be performed successfully.public int[] getLinesStatus(long handle)
throws SerialComException
Gives status of serial port's control lines as supported by underlying operating system. The sequence of status in returned array is :
Linux OS : CTS, DSR, DCD, RI, LOOP, RTS, DTR respectively.
MAC OS X : CTS, DSR, DCD, RI, 0, RTS, DTR respectively.
Windows OS : CTS, DSR, DCD, RI, 0, 0, 0 respectively.
handle - of the port whose status is to be read.SerialComException - if invalid handle is passed or operation can not be completed successfully.public String findDriverServingComPort(String comPortName) throws SerialComException
Gives the name of the driver who is driving the given serial port.
comPortName - name only for windows (for ex; COM52), full path for unix-like os (for ex; /dev/ttyUSB0).SerialComException - if operation can not be completed successfully.IllegalArgumentException - if argument comPortName is null or is an empty string.public String findIRQnumberForComPort(long handle) throws SerialComException
Gives the address and IRQ number associated with the given serial port.
handle - handle of the opened serial port.SerialComException - if operation can not be completed successfully.public int[] getByteCountInPortIOBuffer(long handle)
throws SerialComException
Get number of bytes in input and output port buffers used by operating system for instance tty buffers in Unix like systems. Sequence of data in array is : Input buffer byte count, Output buffer byte count.
It should be noted that some chipset specially USB to UART converters might have FIFO buffers in chipset itself. For example FT232R has internal buffers controlled by FIFO CONTROLLERS. For this reason this method should be tested carefully if application is using USB-UART converters. This is driver and OS specific scenario.
handle - of the opened port for which counts need to be determined.SerialComException - if invalid handle is passed or operation can not be completed successfully.public int registerUSBHotPlugEventListener(ISerialComUSBHotPlugListener hotPlugListener, int filterVID, int filterPID, String serialNumber) throws SerialComException
This registers a listener who will be invoked whenever a USB device has been plugged or un-plugged in system. This method can be used to write auto discovery applications for example when a hardware USB device is added to system, application can automatically detect and identify it and launch appropriate service.
This API can be used for detecting both USB-HID and USB-CDC devices. Essentially this API is USB interface agnostic; meaning it would invoke listener for matching USB device irresepective of functionality offered by the USB device.
Application must implement ISerialComUSBHotPlugListener interface and override onUSBHotPlugEvent method. The event value SerialComUSB.DEV_ADDED indicates USB device has been added to the system. The event value SerialComUSB.DEV_REMOVED indicates USB device has been removed from system.
Application can specify the usb device for which callback should be called based on USB VID and USB PID. If the value of filterVID is specified however the value of filterPID is constant SerialComUSB.DEV_ANY, then callback will be called for USB device which matches given VID and its PID can have any value. If the value of filterPID is specified however the value of filterVID is constant SerialComUSB.DEV_ANY, then callback will be called for USB device which matches given PID and its VID can have any value.
If both filterVID and filterPID are set to SerialComUSB.DEV_ANY, then callback will be called for every USB device. Further in listener, USBVID will be 0, if SerialComUSB.DEV_ANY was passed to registerUSBHotPlugEventListener for filterVID argument. USBPID will be 0, if SerialComUSB.DEV_ANY was passed to registerUSBHotPlugEventListener for filterPID and serialNumber will be empty string if null was passed to registerUSBHotPlugEventListener for serialNumber argument.
If the application do not know the USB attributes like the VID/PID/Serial of the device use listUSBdevicesWithInfo() along with hot plug listener. For example; call listUSBdevicesWithInfo(SerialComUSB.V_ALL) and create and arraylist to know what all USB devices are present in system and register this hotplug listener. Now whenever a USB device is attached to system, listener will be called. From with this listener call listUSBdevicesWithInfo(SerialComUSB.V_ALL) and create arraylist again. Compare these two list to find information about newly added device and take next appropriate step
hotPlugListener - object of class which implements ISerialComUSBHotPlugListener interface.filterVID - USB vendor ID to match.filterPID - USB product ID to match.serialNumber - serial number of USB device (case insensitive, optional, can be null) to match.SerialComException - if registration fails due to some reason.IllegalArgumentException - if hotPlugListener is null or if USB VID or USB PID are invalid numbers.public boolean unregisterUSBHotPlugEventListener(int opaqueHandle)
throws SerialComException
This unregisters listener and terminate native thread used for monitoring specified USB device insertion or removal.
opaqueHandle - handle returned by registerUSBHotPlugEventListener method for this listener.SerialComException - if un-registration fails due to some reason.IllegalArgumentException - if argument opaqueHandle is negative.public String getPortName(long handle) throws SerialComException
This method gives the port name with which given handle is associated. If the given handle is unknown to SCM library, null is returned. A serial port is known to SCM if it was opened using SCM library.
handle - for which the port name is to be found.SerialComException - if invalid handle is passed.public boolean sendFile(long handle,
File fileToSend,
SerialComManager.FTPPROTO ftpProto,
SerialComManager.FTPVAR ftpVariant,
boolean textMode,
ISerialComXmodemProgress progressListener,
SerialComXModemAbort transferState)
throws SerialComException,
SecurityException,
FileNotFoundException,
SerialComTimeOutException,
IOException
Send given file using specified file transfer protocol.
handle - of the port on which file is to be sent.fileToSend - File instance representing file to be sent.ftpProto - file transfer protocol to use for communication over serial port.ftpVariant - variant of file transfer protocol to use.textMode - if true file will be sent as text file (ASCII mode), if false file will be sent as binary file.
The text file must contain only valid ASCII characters.progressListener - object of class which implements ISerialComXmodemProgress interface and is interested in knowing
how many blocks have been sent to file receiver till now. If progressListener is null, update will not
be delivered to application.transferState - if application wish to abort sending file at instant of time due to any reason, it can call
abortTransfer method on this object. If the application does not wishes to abort sending file explicitly
transferState can be null.SerialComException - if invalid handle is passed.SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file.FileNotFoundException - if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.SerialComTimeOutException - if timeout occurs as per file transfer protocol.IOException - if error occurs while reading data from file to be sent.IllegalArgumentException - if fileToSend or ftpProto or ftpVariant or ftpMode argument is null.public boolean receiveFile(long handle,
File fileToReceive,
SerialComManager.FTPPROTO ftpProto,
SerialComManager.FTPVAR ftpVariant,
boolean textMode,
ISerialComXmodemProgress progressListener,
SerialComXModemAbort transferState)
throws SerialComException,
SecurityException,
FileNotFoundException,
SerialComTimeOutException,
IOException
Receives file using specified file transfer protocol.
handle - of the port on which file is to be sent.fileToReceive - File instance representing file to be sent.ftpProto - file transfer protocol to use for communication over serial port.ftpVariant - variant of file transfer protocol to use.textMode - if true file will be received as text file (ASCII mode), if false file will be received as binary file.progressListener - object of class which implements ISerialComXmodemProgress interface and is interested in knowing
how many blocks have been received from file sender till now. If progressListener is null, update will not
be delivered to application.transferState - if application wish to abort receiving file at instant of time due to any reason, it can call
abortTransfer method on this object. If the application does not wishes to abort receiving file explicitly
transferState can be null.SerialComException - if invalid handle is passed.SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file.FileNotFoundException - if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.SerialComTimeOutException - if timeout occurs as per file transfer protocol.IOException - if error occurs while reading data from file to be sent.IllegalArgumentException - if fileToReceive or ftpProto or ftpVariant or ftpMode argument is null.public SerialComInByteStream createInputByteStream(long handle, SerialComManager.SMODE streamMode) throws SerialComException
Prepares context and returns an input streams of bytes for receiving data bytes from the serial port.
A serial port handle can have only one input stream associated with it. Application should close the created stream after it is no longer required.
handle - handle of the opened port from which to read data bytes.SerialComException - if input stream already exist for this handle or invalid handle is passed.IllegalArgumentException - if streamMode is null.public SerialComOutByteStream createOutputByteStream(long handle, SerialComManager.SMODE streamMode) throws SerialComException
Prepares context and returns an output streams of bytes for transferring data bytes out of serial port.
A serial port handle can have only one output stream associated with it. Application should close the created stream after it is no longer required.
Using SerialComOutByteStream for writing data while not using SerialComInByteStream for reading is a valid use case.
handle - handle of the opened port on which to write data bytes.SerialComException - if output stream already exist for this handle or invalid handle is passed.IllegalArgumentException - if streamMode is null.public SerialComIOCTLExecutor getIOCTLExecutor(long handle) throws SerialComException
Prepares context for excuting IOCTL operations on the given port.
handle - handle of the opened port on which to execute ioctl operations.SerialComException - if invalid handle is passed.public boolean isUSBDevConnected(int vendorID,
int productID,
String serialNumber)
throws SerialComException
Checks whether a particular USB device identified by vendor id, product id and serial number is connected to the system or not. The connection infomration is obtained from the operating system.
vendorID - USB-IF vendor ID of the USB device to match.productID - product ID of the USB device to match.serialNumber - USB device's serial number (case insensitive, optional). If not required it can be null.SerialComException - if an I/O error occurs.IllegalArgumentException - if productID or vendorID is negative or invalid.public SerialComVendorLib getVendorLibInstance(int vendorLibIdentifier, String libDirectory, String vlibName) throws UnsatisfiedLinkError, SerialComLoadException, SerialComUnexpectedException, SecurityException, FileNotFoundException
Gives an instance of the class which implements API defined by vendor in their propriety library.
For FTDI d2xx, instance of SerialComFTDID2XX class is returned.
vendorLibIdentifier - one of the constant VLIB_XXXX_XXXX in SerialComVendorLib class.libDirectory - absolute directory path where vendor library is placed.vlibName - full name of the vendor library (for ex. libftd2xx.so.1.1.12).SerialComUnexpectedException - if a critical java system property is null in system.SecurityException - if any java system property can not be accessed.FileNotFoundException - if the vendor library file is not found.UnsatisfiedLinkError - if loading/linking shared library fails.SerialComException - if an I/O error occurs.SerialComLoadException - if the library can not be found, extracted or loaded
if the mentioned library is not supported by vendor for
operating system and cpu architecture combination.IllegalArgumentException - if argument vlibName is null or is an empty string.public SerialComUSB getSerialComUSBInstance() throws SerialComException
Get an instance of SerialComUSB class for USB related operations.
SerialComException - if could not instantiate class due to some reason.public SerialComBluetooth getSerialComBluetoothInstance(int btStack, String directoryPath, String loadedLibName) throws SecurityException, SerialComUnexpectedException, SerialComLoadException, UnsatisfiedLinkError, SerialComException, FileNotFoundException, IOException
Initialize and return an instance of SerialComBluetooth for the given bluetooth stack. It prepares context for serial port communication over Bluetooth using 'serial port profile' (SPP) specification of bluetooth standard.
This method will extract native library in directory as specified by directoryPath argument or default directory will be used if directoryPath is null. The native library loaded will be given name as specified by loadedLibName argument or default name will be used if loadedLibName is null.
btStack - one of the constants BTSTACK_XX_XX defined in SerialComBluetooth class.directoryPath - absolute path of directory to be used for extraction.loadedLibName - library name without extension (do not append .so, .dll or .dylib etc.).SerialComException - if could not instantiate class due to some reason.SecurityException - if java system properties can not be accessed.SerialComUnexpectedException - if java system property is null.SerialComLoadException - if any file system related issue occurs.UnsatisfiedLinkError - if loading/linking shared library fails.FileNotFoundException - if file "/proc/cpuinfo" can not be found for Linux on ARM platform.IOException - if file operations on "/proc/cpuinfo" fails for Linux on ARM platform.SerialComException - if initializing native library fails.IllegalArgumentException - if btStack is an invalid constant.public SerialComHID getSerialComHIDInstance(int type, String directoryPath, String loadedLibName) throws SecurityException, SerialComUnexpectedException, SerialComLoadException, UnsatisfiedLinkError, SerialComException, FileNotFoundException, IOException
Allocate, initialize and return an instance of requested mode for communication with HID device. If the value of variable type is MODE_RAW, instance of class SerialComRawHID is returned. In this mode raw reports are sent and received with device (no report parsing is done). If the type is MODE_PARSED, reports are parsed by operating system as described by report descriptor of the HID device.
HID transport specific APIs defined in SerialComUSBHID and SerialComBluetoothHID can be accessed from with-in SerialComRawHID class.
This method will extract native library in directory as specified by directoryPath argument or default directory will be used if directoryPath is null. The native library loaded will be given name as specified by loadedLibName argument or default name will be used if loadedLibName is null.
type - one of the constants MODE_XXXX defined in SerialComHID class.directoryPath - absolute path of directory to be used for extraction.loadedLibName - library name without extension (do not append .so, .dll or .dylib etc.).SerialComException - if could not instantiate class due to some reason.SecurityException - if java system properties can not be accessed.SerialComUnexpectedException - if java system property is null.SerialComLoadException - if any file system related issue occurs.UnsatisfiedLinkError - if loading/linking shared library fails.FileNotFoundException - if file "/proc/cpuinfo" can not be found for Linux on ARM platform.IOException - if file operations on "/proc/cpuinfo" fails for Linux on ARM platform.SerialComException - if initializing native library fails.IllegalArgumentException - if type is an invalid constant.public SerialComPortMapper getSerialComPortMapperInstance(String directoryPath, String loadedLibName) throws SerialComException, SecurityException, SerialComUnexpectedException, SerialComLoadException, UnsatisfiedLinkError
Allocate, initialize and return an instance of SerialComPortMapper class on whom APIs can be called to map or unmap a serial port alias.
This method will extract native library in directory as specified by directoryPath argument or default directory will be used if directoryPath is null. The native library loaded will be given name as specified by loadedLibName argument or default name will be used if loadedLibName is null.
directoryPath - absolute path of directory to be used for extraction.loadedLibName - library name without extension (do not append .so, .dll or .dylib etc.).SerialComException - if could not instantiate class due to some reason.SecurityException - if java system properties can not be accessed.SerialComUnexpectedException - if java system property is null.SerialComLoadException - if any file system related issue occurs.UnsatisfiedLinkError - if loading/linking shared library fails.FileNotFoundException - if file "/proc/cpuinfo" can not be found for Linux on ARM platform.IOException - if file operations on "/proc/cpuinfo" fails for Linux on ARM platform.SerialComException - if an error occurs.public SerialComDBRelease getSerialComDBReleaseInstance(String directoryPath, String loadedLibName) throws SerialComException, SecurityException, SerialComUnexpectedException, SerialComLoadException, UnsatisfiedLinkError
Allocate, initialize and return an instance of SerialComDBRelease class on whom APIs can be called to release COM ports in use. This methed is applicable for Windows operating system only.
The Windows operating system maintains a database of all COM ports. This database is typically supports com port numbers from 1(COM1) to 256(COM256). This database can get exhausted for example if more than 256 USB-UART devices are connected one after the other in system. This generally happens in factory testing environment. Using the APIs in SerialComDBRelease class, test application can manage the port assignment and its release programatically making production testing faster and less cumbersome.
This method will extract native library in directory as specified by directoryPath argument or default directory will be used if directoryPath is null. The native library loaded will be given name as specified by loadedLibName argument or default name will be used if loadedLibName is null.
directoryPath - absolute path of directory to be used for extraction.loadedLibName - library name without extension (do not append .so, .dll or .dylib etc.).SerialComException - if could not instantiate class due to some reason.SecurityException - if java system properties can not be accessed.SerialComUnexpectedException - if java system property is null.SerialComLoadException - if any file system related issue occurs.UnsatisfiedLinkError - if loading/linking shared library fails.FileNotFoundException - if file "/proc/cpuinfo" can not be found for Linux on ARM platform.IOException - if file operations on "/proc/cpuinfo" fails for Linux on ARM platform.SerialComException - if initializing native library fails.public SerialComToKeyStrokeToApp getSerialComKeyStrokeAppInstance(long handle) throws AWTException
AWTExceptionCopyright © 2016. All rights reserved.