Communicate with serial devices

When the serial port is open you can communicate with the serial device connected to it, transmitting and receiving data.

Send data

You can send data through the serial port. To do so, you need to get the serial port’s output stream. From the OutputStream object invoke one of the existing write() methods.

Sending serial data 
import java.io.OutputStream;
import com.digi.android.serial.SerialPort;
 
[...]
 
SerialPort port = ...;
 
String dataToSend = "This is the data to send";
 
// Get the port output stream.
OutputStream outStream = port.getOutputStream();
 
// Send data through the serial port.
outStream.write(dataToSend.getBytes());
 
[...]

Note When you are done with the serial port you need to:

  1. Unsubscribe your registered listener (if any) with unregisterEventListener() method.
  2. Then close the port by calling the close() method.

Receive data

You can receive data from the serial port by getting its input stream. From the InputStream object invoke one of the existing read() methods.

Receiving serial data 
import java.io.InputStream;
import com.digi.android.serial.SerialPort;

[...]

SerialPort port = ...;
 
[...]

private void readData() {
	// Get the port input stream.
	InputStream inStream = port.getInputStream();

	int availableBytes = inStream.available();
	if (availableBytes > 0) {
		byte[] readBuffer = new byte[availableBytes];
	
		// Read the serial port.
		int numBytes = inStream.read(readBuffer, 0, availableBytes);
	
		if (numBytes > 0)
			System.out.println("Read: " + new String(readBuffer, 0, availableBytes));
	}
}
[...]

Use the data available serial port event (EventType.DATA_AVAILABLE) of your registered ISerialPortEventListener to know when to read data:

ISerialPortEventListener implementation example, MySerialPortListener 
import com.digi.android.serial.ISerialPortEventListener;
import com.digi.android.serial.SerialPort;
import com.digi.android.serial.SerialPortEvent;

public class MySerialPortListener implements ISerialPortEventListener {
	@Override
	public void serialEvent(SerialPortEvent event) {
		switch (event.getEventType()) {
			case DATA_AVAILABLE:
				readData();
				break;
		}
	}
}

Do not forget to subscribe your listener to receive data available events and to enable this notification on your SerialPort object.

Registering for serial port events notifications 
import com.digi.android.serial.SerialPort;
 
[...]
 
SerialPort port = ...;
 
// Create the serial port listener.
MySerialPortListener mySerialPortListener = ...;
 
// Register the serial port listener.
port.registerEventListener(mySerialPortListener);
 
// Enable data available notifications.
port.notifyOnDataAvailable(true);
 
[...]

Note When you are done with the serial port you need to:

  1. Unsubscribe your registered listener (if any) with unregisterEventListener() method.
  2. Then close the port by calling the close() method.