Initial commit.
SmartBotKit/serial/master This commit looks good

This commit is contained in:
2019-04-29 18:04:51 +02:00
commit 3f119e261f
54 changed files with 3990 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
# Eclipse
.classpath
.project
.settings/
# Intellij
.idea/
*.iml
*.iws
# Mac
.DS_Store
# Maven
log/
target/
Vendored
+32
View File
@@ -0,0 +1,32 @@
#!groovy
// this groovy script is executed by jenkins
node {
def server = Artifactory.server 'project.nes.uni-due.de'
def mvnBuild = Artifactory.newMavenBuild()
def mvnInfo
mvnBuild.tool = 'maven-3.3.9'
mvnBuild.opts = '-Xmx2048m'
mvnBuild.deployer server: server, releaseRepo: 'internal-releases', snapshotRepo: 'internal-snapshots', deployArtifacts: false
// checkout code from scm
stage('Checkout') {
checkout scm
}
// build the source code with release profile
stage('Build') {
mvnInfo = mvnBuild.run pom: 'pom.xml', goals: '-Djenkins.build.number=${env.BUILD_NUMBER} -B -U clean install'
}
// deploy the final ear
stage ('Deploy') {
if (env.BRANCH_NAME == "master") {
mvnBuild.deployer.deployArtifacts mvnInfo
} else {
echo "Skipping deployment for non-master branch."
}
}
}
+53
View File
@@ -0,0 +1,53 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.smartbotkit</groupId>
<artifactId>serial</artifactId>
<packaging>pom</packaging>
<name>SmartBotKit Serial</name>
<description>SmartBotKit Serial Communication Library</description>
<version>1.0.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<version.android>4.4.2_r4</version.android>
<version.rxtx>2.1.7</version.rxtx>
</properties>
<modules>
<module>serial-core</module>
<module>serial-test</module>
<module>serial-android</module>
<module>serial-rxtx</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
+36
View File
@@ -0,0 +1,36 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>serial</artifactId>
<groupId>com.smartbotkit</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>serial-android</artifactId>
<packaging>jar</packaging>
<name>SmartBotKit Serial-Android</name>
<description>SmartBotKit Serial Communication Library Android</description>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.smartbotkit</groupId>
<artifactId>serial-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>android</groupId>
<artifactId>android</artifactId>
<version>${version.android}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,149 @@
package com.smartbotkit.serial.android;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import com.smartbotkit.serial.IFlowControlListener;
import com.smartbotkit.serial.ILineErrorListener;
import com.smartbotkit.serial.ISerialPort;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* A base class for serial ports that handles the configuration
* and handlers.
*/
public abstract class AbstractSerialPort implements ISerialPort {
/**
* The error listener which may be null.
*/
protected ILineErrorListener lineErrorListener;
/**
* The flow control listener which may be null.
*/
protected IFlowControlListener flowControlListener;
/**
* The current config.
*/
protected SerialConfig config;
/**
* The usb manager to open connections.
*/
protected UsbManager manager;
/**
* The usb manager to open connections.
*/
protected UsbDevice device;
/**
* The usb interface to open the connection.
*/
protected UsbInterface inter;
/**
* The input endpoint.
*/
protected UsbEndpoint in;
/**
* The output endpoint.
*/
protected UsbEndpoint out;
/**
* The connection.
*/
protected UsbDeviceConnection connection;
/**
* Creates a new port with the manager, device and config.
*
* @param config The serial config of the port.
* @param device The usb device.
* @param manager The usb manager.
*/
public AbstractSerialPort(UsbManager manager, UsbDevice device, SerialConfig config) {
this.config = config;
this.manager = manager;
this.device = device;
}
@Override
public SerialConfig getConfig() {
return config;
}
@Override
public void setLineErrorListener(ILineErrorListener lineErrorListener) {
this.lineErrorListener = lineErrorListener;
}
@Override
public void setFlowControlListener(IFlowControlListener flowControlListener) {
this.flowControlListener = flowControlListener;
}
/**
* Opens the connection to the device. This method requires the interface to be set.
* Subclasses should overwrite this to find the interface first.
*
* @throws IOException Thrown if the interface cannot be found, if the device cannot be opened,
* if the interface cannot be claimed or if the input and output endpoint cannot be found.
*/
protected void initConnection() throws IOException {
connection = manager.openDevice(device);
if (connection == null) throw new IOException("Failed to open device.");
try {
if (! connection.claimInterface(inter, true)) throw new IOException("Failed to claim interface.");
try {
for (int i = 0, s = inter.getEndpointCount(); i < s; i++) {
UsbEndpoint end = inter.getEndpoint(i);
if (end.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (end.getDirection() == UsbConstants.USB_DIR_IN) {
in = end;
} else if (end.getDirection() == UsbConstants.USB_DIR_OUT) {
out = end;
}
}
}
if (in == null) throw new IOException("Failed to find input endpoint.");
if (out == null) throw new IOException("Failed to find output endpoint.");
} catch (IOException e) {
connection.releaseInterface(inter);
throw e;
}
} catch (IOException e) {
connection.close();
throw e;
}
}
@Override
public void close() throws IOException {
connection.releaseInterface(inter);
connection.close();
}
/**
* Validates the value of result and throws an exception, if the
* result is negative.
*
* @param result The result to check.
* @param message The message to throw, if the result is negative.
* @throws IOException Thrown if the result is negative.
*/
protected void throwIfNegative(int result, String message) throws IOException {
if (result < 0) throw new IOException(String.format(message, result));
}
}
@@ -0,0 +1,358 @@
package com.smartbotkit.serial.android;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import com.smartbotkit.serial.FlowControl;
import com.smartbotkit.serial.InputControlLine;
import com.smartbotkit.serial.LineError;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* A serial port implementation for chips following the CDC ACM (communication device class, abstract control model).
* The documentation can be found <a href="https://www.usb.org/document-library/class-definitions-communication-devices-12">here</a>.
*
* This chipset is used by the OpenCR board of the turtlebot 3.
*
* @author Marcus
*/
public class CDCSerialPort extends AbstractSerialPort {
private static final int REQTYPE_HOST2DEVICE = 0x21;
private static final int REQTYPE_DEVICE2HOST = 0xA1;
private static final int SET_LINE_CODING = 0x20;
private static final int SERIAL_STATE = 0x20;
private static final int SET_CONTROL_LINE_STATE = 0x22;
private static final int CONTROL_LINE_RTS = 0x2;
private static final int CONTROL_LINE_DTR = 0x1;
private static final byte LINE_CODING_DATA_BITS_5 = 0x05;
private static final byte LINE_CODING_DATA_BITS_6 = 0x06;
private static final byte LINE_CODING_DATA_BITS_7 = 0x07;
private static final byte LINE_CODING_DATA_BITS_8 = 0x08;
private static final byte LINE_CODING_STOP_BITS_1 = 0x00;
private static final byte LINE_CODING_STOP_BITS_1_5 = 0x01;
private static final byte LINE_CODING_STOP_BITS_2 = 0x02;
private static final byte LINE_CODING_PARITY_NONE = 0x00;
private static final byte LINE_CODING_PARITY_ODD = 0x01;
private static final byte LINE_CODING_PARITY_EVEN = 0x02;
private static final byte LINE_CODING_PARITY_MARK = 0x03;
private static final byte LINE_CODING_PARITY_SPACE = 0x04;
/**
* The buffer used to read the serial state.
*/
private byte[] statusBuffer = new byte[2];
/**
* The current control line state.
*/
private int controlLine = 0;
/**
* Creates a new serial port with the specified config, manager and device.
*
* @param config The port configuration.
* @param manager The usb manager.
* @param device The device.
* @throws IOException Thrown if the port cannot be opened.
*/
public CDCSerialPort(SerialConfig config, UsbManager manager, UsbDevice device) throws IOException {
super(manager, device, config);
init();
}
/**
* Initializes the port or throws an io exception if the
* initialization fails.
*
* @throws IOException Thrown if the initialization fails.
*/
protected void init() throws IOException {
initConnection();
try {
initParameters();
setControlLine(controlLine);
} catch (IOException e) {
close();
throw e;
}
}
/**
* Opens the connection to the device.
*
* @throws IOException Thrown if the interface cannot be found, if the device cannot be opened,
* if the interface cannot be claimed or if the input and output endpoint cannot be found.
*/
protected void initConnection() throws IOException {
for (int i = 0, s = device.getInterfaceCount(); i < s; i++) {
if (device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) {
inter = device.getInterface(i);
break;
}
}
if (inter == null) throw new IOException("Failed to find interface.");
super.initConnection();
}
/**
* Initializes the connection parameters set
*
* @throws IOException
*/
protected void initParameters() throws IOException {
byte[] lineCoding = new byte[7];
setBaudRate(lineCoding);
setDataBits(lineCoding);
setStopBits(lineCoding);
setParity(lineCoding);
if (config.getFlowControl() != FlowControl.NONE) {
throw new IOException("Unsupported flow control configuration.");
}
sendControlTransfer(SET_LINE_CODING, 0, lineCoding);
}
/**
* Sets the baud rate in the line encoding array.
*
* @param lineCoding The line encoding array.
* @throws IOException Thrown if the baud rate is not supported.
*/
protected void setBaudRate(byte[] lineCoding) throws IOException {
int value = 0;
switch (config.getBaudRate()) {
case RATE_300:
value = 300;
break;
case RATE_600:
value = 600;
break;
case RATE_1200:
value = 1200;
break;
case RATE_2400:
value = 2400;
break;
case RATE_4800:
value = 4800;
break;
case RATE_9600:
value = 9600;
break;
case RATE_19200:
value = 19200;
break;
case RATE_38400:
value = 38400;
break;
case RATE_57600:
value = 57600;
break;
case RATE_115200:
value = 115200;
break;
case RATE_230400:
value = 230400;
break;
case RATE_460800:
value = 460800;
break;
case RATE_921600:
value = 921600;
break;
default:
throw new IOException("Unsupported baud rate configuration.");
}
lineCoding[0] = (byte) (value & 0xff);
lineCoding[1] = (byte) (value >> 8 & 0xff);
lineCoding[2] = (byte) (value >> 16 & 0xff);
lineCoding[3] = (byte) (value >> 24 & 0xff);
}
protected void setDataBits(byte[] lineCoding) throws IOException {
switch (config.getDataBits()) {
case BITS_5:
lineCoding[6] = LINE_CODING_DATA_BITS_5;
break;
case BITS_6:
lineCoding[6] = LINE_CODING_DATA_BITS_6;
break;
case BITS_7:
lineCoding[6] = LINE_CODING_DATA_BITS_7;
break;
case BITS_8:
lineCoding[6] = LINE_CODING_DATA_BITS_8;
break;
default:
throw new IOException("Unsupported data bits configuration.");
}
}
/**
* Sets the parity configuration in the line coding.
*
* @param lineCoding The line coding to update.
* @throws IOException Thrown if the parity configuration is unsupported.
*/
protected void setParity(byte[] lineCoding) throws IOException {
switch (config.getParity()) {
case NONE:
lineCoding[5] = LINE_CODING_PARITY_NONE;
break;
case ODD:
lineCoding[5] = LINE_CODING_PARITY_ODD;
break;
case EVEN:
lineCoding[5] = LINE_CODING_PARITY_EVEN;
break;
case MARK:
lineCoding[5] = LINE_CODING_PARITY_MARK;
break;
case SPACE:
lineCoding[5] = LINE_CODING_PARITY_SPACE;
break;
default:
throw new IOException("Unsupported parity configuration.");
}
}
/**
* Sets the stop bits configuration in the line coding.
*
* @param lineCoding The line coding to update.
* @throws IOException Thrown if the stop bits configuration is unsupported.
*/
protected void setStopBits(byte[] lineCoding) throws IOException {
switch (config.getStopBits()) {
case BITS_1:
lineCoding[4] = LINE_CODING_STOP_BITS_1;
break;
case BITS_1_5:
lineCoding[4] = LINE_CODING_STOP_BITS_1_5;
break;
case BITS_2:
lineCoding[4] = LINE_CODING_STOP_BITS_2;
break;
default:
throw new IOException("Unsupported stop bits configuration.");
}
}
/**
* Sets the control line state which defines whether rts and dtr are
* high or low.
*
* @param state The state.
* @throws IOException Thrown if the state cannot be set.
*/
protected void setControlLine(int state) throws IOException {
throwIfNegative(sendControlTransfer(SET_CONTROL_LINE_STATE, state, null), "Failed to set control line state (error: %d).");
}
/**
* Performs a control transfer from host to device with the specified request
* type and value and data with an unlimited timeout using the default interface.
*
* @param type The request type.
* @param value The request value.
* @param data The data to send or null, if none.
* @return A negative number, if the control transfer failed, zero or a
* positive number otherwise.
*/
protected int sendControlTransfer(int type, int value, byte[] data) {
int length = 0;
if(data != null) length = data.length;
return connection.controlTransfer(REQTYPE_HOST2DEVICE, type, value, 0, data, length, 0);
}
/**
* Performs a control transfer from device to host with the specified request
* type and value into the specified data array with an unlimited timeout using
* the default interface.
*
* @param type The request type.
* @param value The request value.
* @param data The data buffer to receive.
* @return A negative number, if the control transfer failed, zero or a
* positive number with the written bytes.
*/
protected int receiveControlTransfer(int type, int value, byte[] data) {
int length = 0;
if(data != null) length = data.length;
return connection.controlTransfer(REQTYPE_DEVICE2HOST, type, value, 0, data, length, 0);
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
int mask = 0;
switch (line) {
case RTS:
mask = CONTROL_LINE_RTS;
break;
case DTR:
mask = CONTROL_LINE_DTR;
break;
default:
throw new IOException("Unsupported control line.");
}
if (value) {
controlLine |= mask;
} else {
controlLine &= ~mask;
}
setControlLine(controlLine);
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int read = connection.bulkTransfer(in, buffer, length, 0);
if (read < 0) return read;
throwIfNegative(receiveControlTransfer(SERIAL_STATE, 0, statusBuffer), "Failed to read modem status (error: %s).");
interpretModemData(statusBuffer[0], statusBuffer[1]);
return read;
}
/**
* Interprets the modem data received from the serial state control transfer.
*
* @param data1 The first byte.
* @param data2 The second byte.
*/
protected void interpretModemData(byte data1, byte data2) {
// check listener multiple times to handle reentrant code
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.CTS, (data1 & 0x01) == 0x02);
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.DSR, (data1 & 0x02) == 0x02);
if (lineErrorListener != null && (data1 & 0x04) == 0x04) lineErrorListener.onLineError(LineError.BREAK);
if (lineErrorListener != null && (data1 & 0x10) == 0x10) lineErrorListener.onLineError(LineError.FRAMING);
if (lineErrorListener != null && (data1 & 0x20) == 0x20) lineErrorListener.onLineError(LineError.PARITY);
if (lineErrorListener != null && (data1 & 0x40) == 0x40) lineErrorListener.onLineError(LineError.OVERRUN);
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
while (length > 0) {
int res = connection.bulkTransfer(out, buffer, offset, buffer.length, 0);
if (res < 0) throw new IOException(String.format("Failed to write bytes (error: %d)", res));
offset += res;
length -= res;
}
}
@Override
public void close() throws IOException {
sendControlTransfer(SET_CONTROL_LINE_STATE, 0, null);
super.close();
}
}
@@ -0,0 +1,418 @@
package com.smartbotkit.serial.android;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import com.smartbotkit.serial.InputControlLine;
import com.smartbotkit.serial.LineError;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* An implementation of the serial port driver for the CP210x chip set family.
* The implementation is a literal translation from https://github.com/felHR85.
*
* This chip set is used by the LDS shipped with the TurtleBot 3.
*
* @author Marcus
*/
public class CP210XSerialPort extends AbstractSerialPort {
private static final int PURGE = 0x12;
private static final int IFC_ENABLE = 0x00;
private static final int SET_LINE_CTL = 0x03;
private static final int GET_LINE_CTL = 0x04;
private static final int SET_MHS = 0x07;
private static final int SET_BAUDRATE = 0x1E;
private static final int SET_FLOW = 0x13;
private static final int SET_CHARS = 0x19;
private static final int GET_MDMSTS = 0x08;
private static final int GET_COMM_STATUS = 0x10;
private static final int REQTYPE_HOST2DEVICE = 0x41;
private static final int REQTYPE_DEVICE2HOST = 0xC1;
private static final int MHS_RTS_ON = 0x202;
private static final int MHS_RTS_OFF = 0x200;
private static final int MHS_DTR_ON = 0x101;
private static final int MHS_DTR_OFF = 0x100;
private static final int PURGE_ALL = 0x000f;
private static final int UART_ENABLE = 0x0001;
private static final int UART_DISABLE = 0x0000;
/**
* A buffer to fetch the comm state.
*/
private byte[] commState = new byte[19];
/**
* A buffer to fetch the line state.
*/
private byte[] lineState = new byte[2];
/**
* A buffer to fetch the modem state.
*/
private byte[] modemState = new byte[1];
/**
* Creates a new serial port with the specified config, manager and device.
*
* @param config The port configuration.
* @param manager The usb manager.
* @param device The device.
* @throws IOException Thrown if the port cannot be opened.
*/
public CP210XSerialPort(UsbManager manager, UsbDevice device, SerialConfig config) throws IOException {
super(manager, device, config);
init();
}
/**
* Opens and initializes the connection based on the settings.
*
* @throws IOException Thrown if the connection cannot be opened.
*/
protected void init() throws IOException {
initConnection();
try {
throwIfNegative(sendControlTransfer(IFC_ENABLE, UART_ENABLE, null), "Failed to enable uart (error: %d).");
throwIfNegative(initParameters(), "Failed to set parameters (error: %d).");
throwIfNegative(initFlowControl(), "Failed to set flow control (error: %d).");
throwIfNegative(initBaudRate(), "Failed to set baud rate (error: %d).");
} catch (IOException e) {
close();
throw e;
}
}
/**
* Initializes the connection parameters.
*
* @return The number of bytes written or negative, if failed.
* @throws IOException Thrown if something fails.
*/
protected int initParameters() throws IOException {
int config = getStopBits() | getDataBits() | getParity();
return sendControlTransfer(SET_LINE_CTL, config, null);
}
/**
* Returns the bit mask to configure the stop bits.
*
* @return The bit mask for the config.
* @throws IOException Thrown if the config is not supported.
*/
protected int getStopBits() throws IOException {
switch (config.getStopBits()) {
case BITS_1:
return 0;
case BITS_1_5:
return 1;
case BITS_2:
return 2;
}
throw new IOException("Unsupported stop bits configuration.");
}
/**
* Returns the bit mask to configure the parity.
*
* @return The bit mask for the config.
* @throws IOException Thrown if the config is not supported.
*/
protected int getParity() throws IOException {
switch (config.getParity()) {
case NONE:
return 0x0000;
case ODD:
return 0x0010;
case EVEN:
return 0x0020;
case MARK:
return 0x0030;
case SPACE:
return 0x0040;
}
throw new IOException("Unsupported parity configuration.");
}
/**
* Returns the bit mask to configure the data bits.
*
* @return The bit mask for the config.
* @throws IOException Thrown if the config is not supported.
*/
protected int getDataBits() throws IOException {
switch (config.getDataBits()) {
case BITS_5:
return 0x0500;
case BITS_6:
return 0x0600;
case BITS_7:
return 0x0700;
case BITS_8:
return 0x0800;
}
throw new IOException("Unsupported data bits configuration.");
}
/**
* Initializes the flow control based on the config.
*
* @return A negative number, if failed.
* @throws IOException Thrown if the flow control config is unsupported.
*/
protected int initFlowControl() throws IOException {
switch (config.getFlowControl()) {
case NONE:
byte[] dataOff = new byte[]{
(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00
};
return sendControlTransfer(SET_FLOW, 0, dataOff);
case DSR_DTR:
byte[] dataDSRDTR = new byte[]{
(byte) 0x11, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00
};
return sendControlTransfer(SET_FLOW, 0, dataDSRDTR);
case RTS_CTS:
byte[] dataRTSCTS = new byte[]{
(byte) 0x09, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x40, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00
};
return sendControlTransfer(SET_FLOW, 0, dataRTSCTS);
case XON_XOFF:
byte[] dataXONXOFF = new byte[]{
(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x43, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x20, (byte) 0x00, (byte) 0x00
};
byte[] dataChars = new byte[] {
(byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x11, (byte) 0x13
};
int res = sendControlTransfer(SET_CHARS, 0, dataChars);
return Math.min(res, sendControlTransfer(SET_FLOW, 0, dataXONXOFF));
}
throw new IOException("Unsupported flow control configuration.");
}
/**
* Initializes the baud rage based on the configuration.
*
* @throws IOException Thrown if the baud rage cannot be set.
*/
protected int initBaudRate() throws IOException {
int value = 0;
switch (config.getBaudRate()) {
case RATE_300:
value = 300;
break;
case RATE_600:
value = 600;
break;
case RATE_1200:
value = 1200;
break;
case RATE_2400:
value = 2400;
break;
case RATE_4800:
value = 4800;
break;
case RATE_9600:
value = 9600;
break;
case RATE_19200:
value = 19200;
break;
case RATE_38400:
value = 38400;
break;
case RATE_57600:
value = 57600;
break;
case RATE_115200:
value = 115200;
break;
case RATE_230400:
value = 230400;
break;
case RATE_460800:
value = 460800;
break;
case RATE_921600:
value = 921600;
break;
default:
throw new IOException("Unsupported baud rate configuration.");
}
byte[] data = new byte[] {
(byte) (value & 0xff),
(byte) (value >> 8 & 0xff),
(byte) (value >> 16 & 0xff),
(byte) (value >> 24 & 0xff)
};
return sendControlTransfer(SET_BAUDRATE, 0, data);
}
/**
* Opens the connection to the device.
*
* @throws IOException Thrown if the interface cannot be found, if the device cannot be opened,
* if the interface cannot be claimed or if the input and output endpoint cannot be found.
*/
protected void initConnection() throws IOException {
if (device.getInterfaceCount() == 0) throw new IOException("Failed to find interface.");
inter = device.getInterface(0);
super.initConnection();
}
/**
* Performs a control transfer from host to device with the specified request
* type and value and data with an unlimited timeout using the default interface.
*
* @param type The request type.
* @param value The request value.
* @param data The data to send or null, if none.
* @return A negative number, if the control transfer failed, zero or a
* positive number otherwise.
*/
protected int sendControlTransfer(int type, int value, byte[] data) {
int length = 0;
if(data != null) length = data.length;
return connection.controlTransfer(REQTYPE_HOST2DEVICE, type, value, inter.getId(), data, length, 0);
}
/**
* Performs a control transfer from device to host with the specified request
* type and value into the specified data array with an unlimited timeout using
* the default interface.
*
* @param type The request type.
* @param value The request value.
* @param data The data buffer to receive.
* @return A negative number, if the control transfer failed, zero or a
* positive number with the written bytes.
*/
protected int receiveControlTransfer(int type, int value, byte[] data) {
int length = 0;
if (data != null) length = data.length;
return connection.controlTransfer(REQTYPE_DEVICE2HOST, type, value, inter.getId(), data, length, 0);
}
/**
* Returns a byte array representing the modem status.
*
* @return A byte array representing the modem status.
* @throws IOException Thrown if the status cannot be retrieved.
*/
protected byte[] getModemState() throws IOException {
throwIfNegative(receiveControlTransfer(GET_MDMSTS, 0, modemState), "Failed to read modem state (error: %d).");
return modemState;
}
/**
* Returns a byte array representing the comm status.
*
* @return A byte array representing the comm status.
* @throws IOException Thrown if the status cannot be retrieved.
*/
protected byte[] getCommStatus() throws IOException {
throwIfNegative(receiveControlTransfer(GET_COMM_STATUS, 0, commState), "Failed to read comm state (error: %d).");
return commState;
}
/**
* Returns a short representing the current line configuration from the
* chip. This is the inverse of the setting done during init parameters.
*
* @return A short representing the current line configuration.
* @throws IOException Thrown if the status cannot be retrieved.
*/
protected short getLineCtl() throws IOException {
throwIfNegative(receiveControlTransfer(GET_LINE_CTL, 0, lineState), "Failed to read line state (error: %d).");
return (short)((lineState[1] << 8) | (lineState[0] & 0xFF));
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
int flag = 0;
switch (line) {
case DTR:
if (value) flag = MHS_DTR_ON;
else flag = MHS_DTR_OFF;
break;
case RTS:
if (value) flag = MHS_RTS_ON;
else flag = MHS_RTS_OFF;
break;
default:
throw new IOException("Invalid line configuration.");
}
throwIfNegative(sendControlTransfer(SET_MHS, flag, null), "Failed to set line (error: %d).");
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int read = connection.bulkTransfer(in, buffer, length, 0);
if (read < 0) return read;
interpretModemData(getModemState()[0], getCommStatus()[0]);
return read;
}
/**
* Interprets the modem data received from the serial state control transfer.
*
* @param data1 The first byte.
* @param data2 The second byte.
*/
protected void interpretModemData(byte data1, byte data2) {
// check listener multiple times to handle reentrant code
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.CTS, (data1 & 0x10) == 0x10);
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.DSR, (data1 & 0x20) == 0x20);
if (lineErrorListener != null && (data1 & 0x01) == 0x01) lineErrorListener.onLineError(LineError.BREAK);
if (lineErrorListener != null && (data1 & 0x02) == 0x02) lineErrorListener.onLineError(LineError.FRAMING);
if (lineErrorListener != null && (data1 & 0x10) == 0x10) lineErrorListener.onLineError(LineError.PARITY);
if (lineErrorListener != null && ((data1 & 0x04) == 0x04 || (data1 & 0x08) == 0x08)) lineErrorListener.onLineError(LineError.OVERRUN);
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
while (length > 0) {
int res = connection.bulkTransfer(out, buffer, offset, buffer.length, 0);
if (res < 0) throw new IOException(String.format("Failed to write bytes (error: %d)", res));
offset += res;
length -= res;
}
}
@Override
public void close() throws IOException {
sendControlTransfer(PURGE, PURGE_ALL, null);
sendControlTransfer(IFC_ENABLE, UART_DISABLE, null);
super.close();
}
}
@@ -0,0 +1,400 @@
package com.smartbotkit.serial.android;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import com.smartbotkit.serial.InputControlLine;
import com.smartbotkit.serial.LineError;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* Implements a serial port for an FTDI chip. This implementation is
* a literal translation the one found at https://github.com/felHR85.
*
* This chip set is used by the Kobuki base of the TurtleBot 2.
*
* @author Marcus
*/
public class FTDISerialPort extends AbstractSerialPort {
private static final int REQTYPE_HOST2DEVICE = 0x40;
private static final int SIO_RESET = 0;
private static final int SIO_MODEM_CTRL = 1;
private static final int SIO_SET_FLOW_CTRL = 2;
private static final int SIO_SET_BAUD_RATE = 3;
private static final int SIO_SET_DATA = 4;
private static final int SIO_SET_DTR_MASK = 0x1;
private static final int SIO_SET_DTR_HIGH = (1 | (SIO_SET_DTR_MASK << 8));
private static final int SIO_SET_DTR_LOW = (0 | (SIO_SET_DTR_MASK << 8));
private static final int SIO_SET_RTS_MASK = 0x2;
private static final int SIO_SET_RTS_HIGH = (2 | (SIO_SET_RTS_MASK << 8));
private static final int SIO_SET_RTS_LOW = (0 | (SIO_SET_RTS_MASK << 8));
private static final int BAUDRATE_300 = 0x2710;
private static final int BAUDRATE_600 = 0x1388;
private static final int BAUDRATE_1200 = 0x09c4;
private static final int BAUDRATE_2400 = 0x04e2;
private static final int BAUDRATE_4800 = 0x0271;
private static final int BAUDRATE_9600 = 0x4138;
private static final int BAUDRATE_19200 = 0x809c;
private static final int BAUDRATE_38400 = 0xc04e;
private static final int BAUDRATE_57600 = 0x0034;
private static final int BAUDRATE_115200 = 0x001a;
private static final int BAUDRATE_230400 = 0x000d;
private static final int BAUDRATE_460800 = 0x4006;
private static final int BAUDRATE_921600 = 0x8003;
private static final int SET_MODEM_CTRL_DEFAULT1 = 0x0101;
private static final int SET_MODEM_CTRL_DEFAULT2 = 0x0202;
private static final int SET_MODEM_CTRL_DEFAULT3 = 0x0100;
private static final int SET_MODEM_CTRL_DEFAULT4 = 0x0200;
private static final int SET_FLOW_CTRL_DEFAULT = 0x0000;
private static final int SET_FLOW_CTRL_SOFTWARE = 0x1311;
private static final int INTERFACE_OFFSET_DEFAULT = 1;
private static final int INTERFACE_OFFSET_RTS_CTS = 2;
private static final int INTERFACE_OFFSET_DSR_DTR = 3;
private static final int INTERFACE_OFFSET_XON_XOFF = 5;
/**
* The buffer to read data with the length initialized
* to maximum + 2 bytes for the status.
*/
protected byte[] readBuffer = new byte[4096 + 2];
/**
* Creates a new serial port with the specified config, manager and device.
*
* @param config The port configuration.
* @param manager The usb manager.
* @param device The device.
* @throws IOException Thrown if the port cannot be opened.
*/
public FTDISerialPort(UsbManager manager, UsbDevice device, SerialConfig config) throws IOException {
super(manager, device, config);
init();
}
/**
* Opens and initializes the connection based on the settings.
*
* @throws IOException Thrown if the connection cannot be opened.
*/
protected void init() throws IOException {
initConnection();
try {
throwIfNegative(sendReset(), "Failed to reset device (error: %d).");
throwIfNegative(initParameters(), "Failed to set parameters (error: %d).");
throwIfNegative(initFlowControl(), "Failed to set flow control (error: %d).");
throwIfNegative(initBaudRate(), "Failed to set baud rate (error: %d).");
} catch (IOException e) {
close();
throw e;
}
}
/**
* Opens the connection to the device.
*
* @throws IOException Thrown if the interface cannot be found, if the device cannot be opened,
* if the interface cannot be claimed or if the input and output endpoint cannot be found.
*/
protected void initConnection() throws IOException {
if (device.getInterfaceCount() == 0) throw new IOException("Failed to find interface.");
inter = device.getInterface(0);
super.initConnection();
}
/**
* Sends a reset.
*
* @return The value of the reset.
*/
protected int sendReset() {
int result = sendControlTransfer(SIO_RESET, 0);
result = Math.min(result, sendControlTransfer(SIO_MODEM_CTRL, SET_MODEM_CTRL_DEFAULT1));
result = Math.min(result, sendControlTransfer(SIO_MODEM_CTRL, SET_MODEM_CTRL_DEFAULT2));
return result;
}
/**
* Initializes the baud rate and returns the result of the control command.
*
* @return A negative value if failed, zero or positive, if success.
* @throws IOException Thrown if the baud rate is not supported.
*/
protected int initBaudRate() throws IOException {
switch (config.getBaudRate()) {
case RATE_300:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_300);
case RATE_600:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_600);
case RATE_1200:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_1200);
case RATE_2400:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_2400);
case RATE_4800:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_4800);
case RATE_9600:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_9600);
case RATE_19200:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_19200);
case RATE_38400:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_38400);
case RATE_57600:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_57600);
case RATE_115200:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_115200);
case RATE_230400:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_230400);
case RATE_460800:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_460800);
case RATE_921600:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_921600);
default:
throw new IOException("Unsupported baud rate configuration.");
}
}
/**
* Initializes the connection parameters (parity, data bits and stop bits).
*
* @return A negative value if failed, zero or positive, if success.
* @throws IOException Thrown if the parity, data bits or stop bits
* are not supported.
*/
protected int initParameters() throws IOException {
int value = setDatabits(0);
value = setParity(value);
value = setStopBits(value);
return sendControlTransfer(SIO_SET_DATA, value);
}
/**
* Sets the bits in the value according to the data bits
* configured in the serial config.
*
* @param value The base value.
* @return The adjusted value.
* @throws IOException Thrown if the configuration is not supported.
*/
protected int setDatabits(int value) throws IOException {
switch (config.getDataBits()) {
case BITS_5:
value |= 1;
value &= ~(1 << 1);
value |= (1 << 2);
value &= ~(1 << 3);
break;
case BITS_6:
value &= ~1;
value |= (1 << 1);
value |= (1 << 2);
value &= ~(1 << 3);
break;
case BITS_7:
value |= 1;
value |= (1 << 1);
value |= (1 << 2);
value &= ~(1 << 3);
break;
case BITS_8:
value &= ~1;
value &= ~(1 << 1);
value &= ~(1 << 2);
value |= (1 << 3);
break;
default:
throw new IOException("Unsupported data bits configuration.");
}
return value;
}
/**
* Sets the bits in the value according to the stop bits
* configured in the serial config.
*
* @param value The base value.
* @return The adjusted value.
* @throws IOException Thrown if the configuration is not supported.
*/
protected int setStopBits(int value) throws IOException {
switch (config.getStopBits()) {
case BITS_1:
value &= ~(1 << 11);
value &= ~(1 << 12);
value &= ~(1 << 13);
break;
case BITS_1_5:
value |= (1 << 11);
value &= ~(1 << 12);
value &= ~(1 << 13);
break;
case BITS_2:
value &= ~(1 << 11);
value |= (1 << 12);
value &= ~(1 << 13);
break;
default:
throw new IOException("Unsupported stop bits configuration.");
}
return value;
}
/**
* Sets the bits in the value according to the parity
* configured in the serial config.
*
* @param value The base value.
* @return The adjusted value.
* @throws IOException Thrown if the configuration is not supported.
*/
protected int setParity(int value) throws IOException {
switch (config.getParity()) {
case NONE:
value &= ~(1 << 8);
value &= ~(1 << 9);
value &= ~(1 << 10);
break;
case ODD:
value |= (1 << 8);
value &= ~(1 << 9);
value &= ~(1 << 10);
break;
case EVEN:
value &= ~(1 << 8);
value |= (1 << 9);
value &= ~(1 << 10);
break;
case MARK:
value |= (1 << 8);
value |= (1 << 9);
value &= ~(1 << 10);
break;
case SPACE:
value &= ~(1 << 8);
value &= ~(1 << 9);
value |= (1 << 10);
break;
default:
throw new IOException("Unsupported parity configuration.");
}
return value;
}
/**
* Performs a control transfer with the specified request type and value
* and zero data with an unlimited timeout using the default interface.
*
* @param type The request type.
* @param value The request value.
* @return A negative number, if the control transfer failed, zero or a
* positive number otherwise.
*/
protected int sendControlTransfer(int type, int value) {
return sendControlTransfer(type, value, INTERFACE_OFFSET_DEFAULT);
}
/**
* Performs a control transfer with the specified request type and value
* and zero data with an unlimited timeout using the specified interface
* offset.
*
* @param type The request type.
* @param value The request value.
* @param interfaceOffset The interface offset.
* @return A negative number, if the control transfer failed, zero or a
* positive number otherwise.
*/
protected int sendControlTransfer(int type, int value, int interfaceOffset) {
return connection.controlTransfer(REQTYPE_HOST2DEVICE, type, value, inter.getId() + interfaceOffset, null, 0, 0);
}
/**
* Configures the flow control value according to the
* configuration of the serial config.
*
* @return The result of the control transfer.
* @throws IOException Thrown if the configuration
*/
protected int initFlowControl() throws IOException {
switch (config.getFlowControl()) {
case NONE:
return sendControlTransfer(SIO_SET_FLOW_CTRL, SET_FLOW_CTRL_DEFAULT, INTERFACE_OFFSET_DEFAULT);
case DSR_DTR:
return sendControlTransfer(SIO_SET_FLOW_CTRL, SET_FLOW_CTRL_DEFAULT, INTERFACE_OFFSET_DSR_DTR);
case RTS_CTS:
return sendControlTransfer(SIO_SET_FLOW_CTRL, SET_FLOW_CTRL_DEFAULT, INTERFACE_OFFSET_RTS_CTS);
case XON_XOFF:
return sendControlTransfer(SIO_SET_FLOW_CTRL, SET_FLOW_CTRL_SOFTWARE, INTERFACE_OFFSET_XON_XOFF);
default:
throw new IOException("Unsupported flow control configuration.");
}
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
switch (line) {
case RTS:
throwIfNegative(sendControlTransfer(SIO_MODEM_CTRL, value?SIO_SET_RTS_HIGH:SIO_SET_RTS_LOW), "Failed to set rts value (error: %d).");
break;
case DTR:
throwIfNegative(sendControlTransfer(SIO_MODEM_CTRL, value?SIO_SET_DTR_HIGH:SIO_SET_DTR_LOW), "Failed to set dtr value (error: %d).");
break;
default:
throw new IOException("Unsupported control line.");
}
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int maximum = Math.min(length + 2, readBuffer.length);
int read = connection.bulkTransfer(in, readBuffer, maximum, 0);
if (read < 2) throw new IOException("Failed to read modem data.");
interpretModemData(readBuffer[0], readBuffer[1]);
if (read > 2) System.arraycopy(readBuffer, 2, buffer, offset, read - 2);
return read - 2;
}
/**
* Interprets the modem data send as part of each bulk transfer
* to the in endpoint.
*
* @param data1 The first byte.
* @param data2 The second byte.
*/
protected void interpretModemData(byte data1, byte data2) {
// check listener multiple times to handle reentrant code
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.CTS, (data1 & 0x10) == 0x10);
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.DSR, (data1 & 0x20) == 0x20);
if (lineErrorListener != null && (data2 & 0x10) == 0x10) lineErrorListener.onLineError(LineError.BREAK);
if (lineErrorListener != null && (data2 & 0x20) == 0x20) lineErrorListener.onLineError(LineError.OVERRUN);
if (lineErrorListener != null && (data2 & 0x40) == 0x40) lineErrorListener.onLineError(LineError.PARITY);
if (lineErrorListener != null && (data2 & 0x80) == 0x80) lineErrorListener.onLineError(LineError.FRAMING);
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
while (length > 0) {
int res = connection.bulkTransfer(out, buffer, offset, buffer.length, 0);
if (res < 0) throw new IOException(String.format("Failed to write bytes (error: %d)", res));
offset += res;
length -= res;
}
}
@Override
public void close() throws IOException {
sendControlTransfer(SIO_MODEM_CTRL, SET_MODEM_CTRL_DEFAULT3);
sendControlTransfer(SIO_MODEM_CTRL, SET_MODEM_CTRL_DEFAULT4);
super.close();
}
}
+22
View File
@@ -0,0 +1,22 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>serial</artifactId>
<groupId>com.smartbotkit</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>serial-core</artifactId>
<packaging>jar</packaging>
<name>SmartBotKit Serial-Core</name>
<description>SmartBotKit Serial Communication Library Core</description>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,35 @@
package com.smartbotkit.serial;
/**
* The baud rate of the serial connection.
*
* @author Marcus
*/
public enum BaudRate {
/** 300 symbols per second **/
RATE_300,
/** 600 symbols per second **/
RATE_600,
/** 1200 symbols per second **/
RATE_1200,
/** 2400 symbols per second **/
RATE_2400,
/** 4800 symbols per second **/
RATE_4800,
/** 9600 symbols per second **/
RATE_9600,
/** 19200 symbols per second **/
RATE_19200,
/** 38400 symbols per second **/
RATE_38400,
/** 57600 symbols per second **/
RATE_57600,
/** 115200 symbols per second **/
RATE_115200,
/** 230400 symbols per second **/
RATE_230400,
/** 460800 symbols per second **/
RATE_460800,
/** 921600 symbols per second **/
RATE_921600;
}
@@ -0,0 +1,17 @@
package com.smartbotkit.serial;
/**
* The number of data bits in each character.
*
* @author Marcus
*/
public enum DataBits {
/** 5 bits per character **/
BITS_5,
/** 6 bits per character **/
BITS_6,
/** 7 bits per character **/
BITS_7,
/** 8 bits per character **/
BITS_8;
}
@@ -0,0 +1,18 @@
package com.smartbotkit.serial;
/**
* The flow control used on the connection.
*
* @author Marcus
*/
public enum FlowControl {
/** No flow control. **/
NONE,
/** Hardware flow control over rts and cts. **/
RTS_CTS,
/** Hardware flow control over dsr and dtr. **/
DSR_DTR,
/** Software flow control over xon and xoff. **/
XON_XOFF;
}
@@ -0,0 +1,18 @@
package com.smartbotkit.serial;
/**
* An interface to receive the state of input lines.
*
* @author Marcus
*/
public interface IFlowControlListener {
/**
* Called when the input control line has been read.
*
* @param line The line.
* @param state The state (true for high, false for low).
*/
void onLineSet(InputControlLine line, boolean state);
}
@@ -0,0 +1,18 @@
package com.smartbotkit.serial;
/**
* A listener for errors raised during the
* communication.
*
* @author Marcus
*/
public interface ILineErrorListener {
/**
* Called when an error is detected.
*
* @param error The error type.
*/
void onLineError(LineError error);
}
@@ -0,0 +1,73 @@
package com.smartbotkit.serial;
import java.io.IOException;
/**
* An abstraction for a serial port.
*
* @author Marcus
*/
public interface ISerialPort {
/**
* Returns the serial port configuration.
*
* @return The serial port configuration.
*/
SerialConfig getConfig();
/**
* Changes the value of the output line.
*
* @param line The line.
* @param value The value (true for high, false for low).
* @throws IOException Thro
*/
void setLine(OutputControlLine line, boolean value) throws IOException;
/**
* Sets and unsets the listener that will receive errors.
*
* @param lineErrorListener The listener to set or null, to unset.
*/
void setLineErrorListener(ILineErrorListener lineErrorListener);
/**
* Sets or unsets the listener to receive the state of flow control lines.
*
* @param flowControlListener The listener to set or null, to unset.
*/
void setFlowControlListener(IFlowControlListener flowControlListener);
/**
* Writes a number of bytes to the port.
*
* @param buffer The buffer to write.
* @param offset The offset to start from.
* @param length The length to write.
* @throws IOException Thrown if something fails.
*/
void write(byte[] buffer, int offset, int length) throws IOException;
/**
* Reads a number of bytes from the port.
*
* @param buffer The buffer to write to.
* @param offset The offset to start from.
* @param length The length to write to.
* @return The number of bytes read.
* @throws IOException Thrown if something fails.
*/
int read(byte[] buffer, int offset, int length) throws IOException;
/**
* Closes the serial port.
*
* @throws IOException Thrown if something fails.
*/
void close() throws IOException;
}
@@ -0,0 +1,15 @@
package com.smartbotkit.serial;
/**
* Constants for the input control lines whose value is read.
*/
public enum InputControlLine {
/**
* The clear to send line.
*/
CTS,
/**
* The data set ready line.
*/
DSR;
}
@@ -0,0 +1,26 @@
package com.smartbotkit.serial;
/**
* An enumeration of error types signaled
* by the error listener during communication.
*
* @author Marcus
*/
public enum LineError {
/**
* A break signal.
*/
BREAK,
/**
* A buffer overrun.
*/
OVERRUN,
/**
* A parity failure.
*/
PARITY,
/**
* A framing failure.
*/
FRAMING;
}
@@ -0,0 +1,18 @@
package com.smartbotkit.serial;
/**
* The output control lines whose value can be set.
*
* @author Marcus
*/
public enum OutputControlLine {
/**
* The request to send line.
*/
RTS,
/**
* The data terminal ready line.
*/
DTR;
}
@@ -0,0 +1,20 @@
package com.smartbotkit.serial;
/**
* The parity check applied to the data bits.
*
* @author Marcus
*/
public enum Parity {
/** No parity check. **/
NONE,
/** Parity bit set so that the number of ones is odd. **/
ODD,
/** Parity bit set so that the number of ones is even. **/
EVEN,
/** Parity bit set to the mark signal condition. **/
MARK,
/** Parity bit set to the space signal condition. **/
SPACE;
}
@@ -0,0 +1,116 @@
package com.smartbotkit.serial;
/**
* Represents the configuration of a serial port with baud rate, data and stop bits,
* flow control and parity settings.
*
* @author Marcus
*/
public class SerialConfig {
/** The baud rate. **/
private BaudRate baudRate;
/** The number of stop bits. **/
private StopBits stopBits;
/** The parity check. **/
private Parity parity;
/** The flow control mode. **/
private FlowControl flowControl;
/** The number of data bits. **/
private DataBits dataBits;
/**
* Creates a configuration for the serial port.
*
* @param dataBits The number of data bits.
* @param stopBits The number of stop bits.
* @param parity The parity check.
* @param flowControl The flow control mode.
* @param baudRate The baud rate.
* @throws IllegalArgumentException Thrown if any of the parameters is null.
*/
public SerialConfig(DataBits dataBits, StopBits stopBits, Parity parity, FlowControl flowControl, BaudRate baudRate) {
throwIfNull(dataBits, "DataBits must not be null.");
this.dataBits = dataBits;
throwIfNull(stopBits, "StopBits must not be null.");
this.stopBits = stopBits;
throwIfNull(parity, "Parity must not be null.");
this.parity = parity;
throwIfNull(flowControl, "FlowControl must not be null.");
this.flowControl = flowControl;
throwIfNull(baudRate, "BaudRate must not be null.");
this.baudRate = baudRate;
}
/**
* Throws an illegal argument exception with the specified message, if
* the passed object is null.
*
* @param o The object to test.
* @param message The message to throw.
* @throws IllegalArgumentException Thrown if the object is null.
*/
protected void throwIfNull(Object o, String message) throws IllegalArgumentException {
if (o == null) throw new IllegalArgumentException(message);
}
/**
* Returns the baud rate.
*
* @return The baud rate.
*/
public BaudRate getBaudRate() {
return baudRate;
}
/**
* Returns the number of data bits.
*
* @return The number of data bits.
*/
public DataBits getDataBits() {
return dataBits;
}
/**
* Returns the flow control mode.
*
* @return The flow control mode.
*/
public FlowControl getFlowControl() {
return flowControl;
}
/**
* Returns the parity check.
*
* @return The parity check.
*/
public Parity getParity() {
return parity;
}
/**
* Returns the number of stop bits.
*
* @return The number of stop bits.
*/
public StopBits getStopBits() {
return stopBits;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) return false;
SerialConfig o = (SerialConfig)obj;
return o.parity == parity && o.baudRate == baudRate &&
o.flowControl == flowControl && o.stopBits == stopBits &&
o.dataBits == dataBits;
}
@Override
public String toString() {
return String.format("DataBits: %1s, StopBits: %2s, Parity: %3s, FlowControl: %4, BaudRate: %5s",
dataBits, stopBits, parity, flowControl, baudRate);
}
}
@@ -0,0 +1,13 @@
package com.smartbotkit.serial;
/**
* The number of bits sent after each character.
*/
public enum StopBits {
/** One stop bit. **/
BITS_1,
/** One and a half stop bits. **/
BITS_1_5,
/** Two stop bits. **/
BITS_2;
}
View File
+34
View File
@@ -0,0 +1,34 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>serial</artifactId>
<groupId>com.smartbotkit</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>serial-rxtx</artifactId>
<packaging>jar</packaging>
<name>SmartBotKit Serial-RxTx</name>
<description>SmartBotKit Serial Communication Library RxTx</description>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.smartbotkit</groupId>
<artifactId>serial-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.rxtx</groupId>
<artifactId>rxtx</artifactId>
<version>${version.rxtx}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,307 @@
package com.smartbotkit.serial.rxtx;
import com.smartbotkit.serial.IFlowControlListener;
import com.smartbotkit.serial.ILineErrorListener;
import com.smartbotkit.serial.ISerialPort;
import com.smartbotkit.serial.InputControlLine;
import com.smartbotkit.serial.LineError;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.TooManyListenersException;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
/**
* A serial port abstraction on top of the RXTX library that can
* be used for PC-based protocol and application development.
*
* @author Marcus
*/
public class RxTxSerialPort implements ISerialPort {
/**
* The serial port.
*/
private SerialPort port;
/**
* The serial configuration.
*/
private SerialConfig config;
/**
* The input stream to read from.
*/
private InputStream input;
/**
* The output stream to write to.
*/
private OutputStream output;
/**
* The flow control listener.
*/
private IFlowControlListener flowControlListener;
/**
* The line error listener.
*/
private ILineErrorListener lineErrorListener;
/**
* A serial port listener that forwards the events to the listeners.
*/
private SerialPortEventListener serialPortListener = new SerialPortEventListener() {
@Override
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.DSR:
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.DSR, serialPortEvent.getNewValue());
break;
case SerialPortEvent.CTS:
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.CTS, serialPortEvent.getNewValue());
break;
case SerialPortEvent.FE:
if (lineErrorListener != null) lineErrorListener.onLineError(LineError.FRAMING);
break;
case SerialPortEvent.PE:
if (lineErrorListener != null) lineErrorListener.onLineError(LineError.PARITY);
break;
case SerialPortEvent.OE:
if (lineErrorListener != null) lineErrorListener.onLineError(LineError.OVERRUN);
break;
case SerialPortEvent.BI:
if (lineErrorListener != null) lineErrorListener.onLineError(LineError.BREAK);
break;
}
}
};
/**
* Creates a new serial port with the configuration on the port naem.
*
* @param config The port configuration to apply.
* @param portName The port name, e.g. "COM6".
* @throws IOException Thrown if something fails.
*/
public RxTxSerialPort(SerialConfig config, String portName) throws IOException {
this.config = config;
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
this.port = (SerialPort) commPort;
try {
init();
} catch (IOException e) {
port.close();
throw e;
}
} else {
commPort.close();
throw new IOException("Port is not a serial port.");
}
} catch (NoSuchPortException e) {
throw new IOException("Port not found.", e);
} catch (PortInUseException e) {
throw new IOException("Port is already in use.", e);
}
}
/**
* Initializes the port.
*
* @throws IOException Thrown if the port cannot be setup.
*/
protected void init() throws IOException {
try {
port.setSerialPortParams(getBaudRate(), getDataBits(), getStopBits(), getParity());
port.setFlowControlMode(getFlowControl());
input = port.getInputStream();
output = port.getOutputStream();
port.addEventListener(serialPortListener);
} catch (UnsupportedCommOperationException e) {
throw new IOException("Failed to setup port.", e);
} catch (TooManyListenersException e) {
throw new IOException("Failed to setup listener.", e);
}
}
/**
* Returns the configured baud rate.
*
* @return The configured baud rate.
* @throws IOException Thrown if the configuration is unsupported.
*/
private int getBaudRate() throws IOException {
switch (config.getBaudRate()) {
case RATE_921600:
return 921600;
case RATE_460800:
return 460800;
case RATE_230400:
return 230400;
case RATE_115200:
return 115200;
case RATE_57600:
return 57600;
case RATE_38400:
return 38400;
case RATE_19200:
return 19200;
case RATE_9600:
return 9600;
case RATE_4800:
return 4800;
case RATE_2400:
return 2400;
case RATE_1200:
return 1200;
case RATE_600:
return 600;
case RATE_300:
return 300;
default:
throw new IOException("Unsupported baud rate configuration.");
}
}
/**
* Returns the configured stop bits.
*
* @return The configured stop bits.
* @throws IOException Thrown if the configuration is unsupported.
*/
private int getStopBits() throws IOException {
switch (config.getStopBits()) {
case BITS_2:
return SerialPort.STOPBITS_2;
case BITS_1:
return SerialPort.STOPBITS_1;
case BITS_1_5:
return SerialPort.STOPBITS_1_5;
default:
throw new IOException("Unsupported stop bits configuration.");
}
}
/**
* Returns the configured data bits.
*
* @return The configured data bits.
* @throws IOException Thrown if the configuration is unsupported.
*/
private int getDataBits() throws IOException {
switch (config.getDataBits()) {
case BITS_8:
return SerialPort.DATABITS_8;
case BITS_7:
return SerialPort.DATABITS_7;
case BITS_6:
return SerialPort.DATABITS_6;
case BITS_5:
return SerialPort.DATABITS_5;
default:
throw new IOException("Unsupported data bits configuration.");
}
}
/**
* Returns the configured parity.
*
* @return The configured parity.
* @throws IOException Thrown if the configuration is unsupported.
*/
private int getParity() throws IOException {
switch (config.getParity()) {
case NONE:
return SerialPort.PARITY_NONE;
case ODD:
return SerialPort.PARITY_ODD;
case EVEN:
return SerialPort.PARITY_EVEN;
case MARK:
return SerialPort.PARITY_MARK;
case SPACE:
return SerialPort.PARITY_SPACE;
default:
throw new IOException("Unsupported parity configuration.");
}
}
/**
* Returns the configured flow control mode.
*
* @return The configured flow control.
* @throws IOException Thrown if the configuration is unsupported.
*/
private int getFlowControl() throws IOException {
switch (config.getFlowControl()) {
case NONE:
return SerialPort.FLOWCONTROL_NONE;
case DSR_DTR:
return SerialPort.FLOWCONTROL_RTSCTS_IN;
case RTS_CTS:
return SerialPort.FLOWCONTROL_RTSCTS_OUT;
case XON_XOFF:
return SerialPort.FLOWCONTROL_XONXOFF_IN;
default:
throw new IOException("Unsupported flow control configuration.");
}
}
@Override
public SerialConfig getConfig() {
return config;
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
switch (line) {
case RTS:
port.setRTS(value);
break;
case DTR:
port.setDTR(value);
break;
}
}
@Override
public void setLineErrorListener(ILineErrorListener lineErrorListener) {
this.lineErrorListener = lineErrorListener;
}
@Override
public void setFlowControlListener(IFlowControlListener flowControlListener) {
this.flowControlListener = flowControlListener;
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
output.write(buffer, offset, length);
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
return input.read(buffer, offset, length);
}
@Override
public void close() throws IOException {
port.removeEventListener();
input.close();
output.close();
port.close();
}
}
View File
+29
View File
@@ -0,0 +1,29 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>serial</artifactId>
<groupId>com.smartbotkit</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>serial-test</artifactId>
<packaging>jar</packaging>
<name>SmartBotKit Serial-Test</name>
<description>SmartBotKit Serial Communication Library Test</description>
<build>
<plugins>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.smartbotkit</groupId>
<artifactId>serial-core</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,92 @@
package com.smartbotkit.serial.test;
import com.smartbotkit.serial.IFlowControlListener;
import com.smartbotkit.serial.ILineErrorListener;
import com.smartbotkit.serial.ISerialPort;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* A serial port intended for unit testing. The port
* will continuously replay the data specified in
* the constructor.
*
* @author Marcus
*/
public class TestSerialPort implements ISerialPort {
/**
* The configuration of the port.
*/
protected SerialConfig config;
/**
* The data to be playing.
*/
protected byte[] data;
/**
* The current pointer into the data array.
*/
protected int read = 0;
/**
* A flag to indicate whether the port has been closed.
*/
protected boolean closed = false;
/**
* Creates a new serial port with the configuration
* and the data to play back.
*
* @param config The port configuration.
* @param data The data to play back.
*/
public TestSerialPort(SerialConfig config, byte[] data) {
this.config = config;
this.data = data;
}
@Override
public SerialConfig getConfig() {
return config;
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
if (closed) throw new IOException("Serial port is closed.");
}
@Override
public void setLineErrorListener(ILineErrorListener lineErrorListener) {
// do nothing
}
@Override
public void setFlowControlListener(IFlowControlListener flowControlListener) {
// do nothing
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
if (closed) throw new IOException("Serial port is closed.");
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
if (closed) throw new IOException("Serial port is closed.");
int remainder = data.length - read;
int max = Math.min(remainder, length);
System.arraycopy(data, read, buffer, offset, max);
read += max;
if (read == data.length) read = 0;
return max;
}
@Override
public void close() throws IOException {
this.closed = true;
}
}
@@ -0,0 +1,35 @@
package com.smartbotkit.serial;
/**
* The baud rate of the serial connection.
*
* @author Marcus
*/
public enum BaudRate {
/** 300 symbols per second **/
RATE_300,
/** 600 symbols per second **/
RATE_600,
/** 1200 symbols per second **/
RATE_1200,
/** 2400 symbols per second **/
RATE_2400,
/** 4800 symbols per second **/
RATE_4800,
/** 9600 symbols per second **/
RATE_9600,
/** 19200 symbols per second **/
RATE_19200,
/** 38400 symbols per second **/
RATE_38400,
/** 57600 symbols per second **/
RATE_57600,
/** 115200 symbols per second **/
RATE_115200,
/** 230400 symbols per second **/
RATE_230400,
/** 460800 symbols per second **/
RATE_460800,
/** 921600 symbols per second **/
RATE_921600;
}
@@ -0,0 +1,17 @@
package com.smartbotkit.serial;
/**
* The number of data bits in each character.
*
* @author Marcus
*/
public enum DataBits {
/** 5 bits per character **/
BITS_5,
/** 6 bits per character **/
BITS_6,
/** 7 bits per character **/
BITS_7,
/** 8 bits per character **/
BITS_8;
}
@@ -0,0 +1,18 @@
package com.smartbotkit.serial;
/**
* The flow control used on the connection.
*
* @author Marcus
*/
public enum FlowControl {
/** No flow control. **/
NONE,
/** Hardware flow control over rts and cts. **/
RTS_CTS,
/** Hardware flow control over dsr and dtr. **/
DSR_DTR,
/** Software flow control over xon and xoff. **/
XON_XOFF;
}
@@ -0,0 +1,18 @@
package com.smartbotkit.serial;
/**
* An interface to receive the state of input lines.
*
* @author Marcus
*/
public interface IFlowControlListener {
/**
* Called when the input control line has been read.
*
* @param line The line.
* @param state The state (true for high, false for low).
*/
void onLineSet(InputControlLine line, boolean state);
}
@@ -0,0 +1,18 @@
package com.smartbotkit.serial;
/**
* A listener for errors raised during the
* communication.
*
* @author Marcus
*/
public interface ILineErrorListener {
/**
* Called when an error is detected.
*
* @param error The error type.
*/
void onLineError(LineError error);
}
@@ -0,0 +1,73 @@
package com.smartbotkit.serial;
import java.io.IOException;
/**
* An abstraction for a serial port.
*
* @author Marcus
*/
public interface ISerialPort {
/**
* Returns the serial port configuration.
*
* @return The serial port configuration.
*/
SerialConfig getConfig();
/**
* Changes the value of the output line.
*
* @param line The line.
* @param value The value (true for high, false for low).
* @throws IOException Thro
*/
void setLine(OutputControlLine line, boolean value) throws IOException;
/**
* Sets and unsets the listener that will receive errors.
*
* @param lineErrorListener The listener to set or null, to unset.
*/
void setLineErrorListener(ILineErrorListener lineErrorListener);
/**
* Sets or unsets the listener to receive the state of flow control lines.
*
* @param flowControlListener The listener to set or null, to unset.
*/
void setFlowControlListener(IFlowControlListener flowControlListener);
/**
* Writes a number of bytes to the port.
*
* @param buffer The buffer to write.
* @param offset The offset to start from.
* @param length The length to write.
* @throws IOException Thrown if something fails.
*/
void write(byte[] buffer, int offset, int length) throws IOException;
/**
* Reads a number of bytes from the port.
*
* @param buffer The buffer to write to.
* @param offset The offset to start from.
* @param length The length to write to.
* @return The number of bytes read.
* @throws IOException Thrown if something fails.
*/
int read(byte[] buffer, int offset, int length) throws IOException;
/**
* Closes the serial port.
*
* @throws IOException Thrown if something fails.
*/
void close() throws IOException;
}
@@ -0,0 +1,15 @@
package com.smartbotkit.serial;
/**
* Constants for the input control lines whose value is read.
*/
public enum InputControlLine {
/**
* The clear to send line.
*/
CTS,
/**
* The data set ready line.
*/
DSR;
}
@@ -0,0 +1,26 @@
package com.smartbotkit.serial;
/**
* An enumeration of error types signaled
* by the error listener during communication.
*
* @author Marcus
*/
public enum LineError {
/**
* A break signal.
*/
BREAK,
/**
* A buffer overrun.
*/
OVERRUN,
/**
* A parity failure.
*/
PARITY,
/**
* A framing failure.
*/
FRAMING;
}
@@ -0,0 +1,18 @@
package com.smartbotkit.serial;
/**
* The output control lines whose value can be set.
*
* @author Marcus
*/
public enum OutputControlLine {
/**
* The request to send line.
*/
RTS,
/**
* The data terminal ready line.
*/
DTR;
}
@@ -0,0 +1,20 @@
package com.smartbotkit.serial;
/**
* The parity check applied to the data bits.
*
* @author Marcus
*/
public enum Parity {
/** No parity check. **/
NONE,
/** Parity bit set so that the number of ones is odd. **/
ODD,
/** Parity bit set so that the number of ones is even. **/
EVEN,
/** Parity bit set to the mark signal condition. **/
MARK,
/** Parity bit set to the space signal condition. **/
SPACE;
}
@@ -0,0 +1,105 @@
package com.smartbotkit.serial;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* The configuration of a serial port.
*
* @author Marcus
*/
public class SerialConfig {
/** The baud rate. **/
private @NonNull BaudRate baudRate;
/** The number of stop bits. **/
private @NonNull StopBits stopBits;
/** The parity check. **/
private @NonNull Parity parity;
/** The flow control mode. **/
private @NonNull FlowControl flowControl;
/** The number of data bits. **/
private @NonNull DataBits dataBits;
/**
* Creates a configuration for the serial port.
*
* @param dataBits The number of data bits.
* @param stopBits The number of stop bits.
* @param parity The parity check.
* @param flowControl The flow control mode.
* @param baudRate The baud rate.
*/
public SerialConfig(@NonNull DataBits dataBits, @NonNull StopBits stopBits, @NonNull Parity parity, @NonNull FlowControl flowControl, @NonNull BaudRate baudRate) {
this.dataBits = dataBits;
this.stopBits = stopBits;
this.parity = parity;
this.flowControl = flowControl;
this.baudRate = baudRate;
}
/**
* Returns the baud rate.
*
* @return The baud rate.
*/
@NonNull
public BaudRate getBaudRate() {
return baudRate;
}
/**
* Returns the number of data bits.
*
* @return The number of data bits.
*/
@NonNull
public DataBits getDataBits() {
return dataBits;
}
/**
* Returns the flow control mode.
*
* @return The flow control mode.
*/
@NonNull
public FlowControl getFlowControl() {
return flowControl;
}
/**
* Returns the parity check.
*
* @return The parity check.
*/
@NonNull
public Parity getParity() {
return parity;
}
/**
* Returns the number of stop bits.
*
* @return The number of stop bits.
*/
@NonNull
public StopBits getStopBits() {
return stopBits;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj == null || obj.getClass() != getClass()) return false;
SerialConfig o = (SerialConfig)obj;
return o.parity == parity && o.baudRate == baudRate &&
o.flowControl == flowControl && o.stopBits == stopBits &&
o.dataBits == dataBits;
}
@NonNull
@Override
public String toString() {
return String.format("DataBits: %1s, StopBits: %2s, Parity: %3s, FlowControl: %4, BaudRate: %5s",
dataBits, stopBits, parity, flowControl, baudRate);
}
}
@@ -0,0 +1,13 @@
package com.smartbotkit.serial;
/**
* The number of bits sent after each character.
*/
public enum StopBits {
/** One stop bit. **/
BITS_1,
/** One and a half stop bits. **/
BITS_1_5,
/** Two stop bits. **/
BITS_2;
}
@@ -0,0 +1,151 @@
package com.smartbotkit.serial.android;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import com.smartbotkit.serial.IFlowControlListener;
import com.smartbotkit.serial.ILineErrorListener;
import com.smartbotkit.serial.ISerialPort;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* A base class for serial ports that handles the configuration
* and handlers.
*/
public abstract class AbstractSerialPort implements ISerialPort {
/**
* The error listener which may be null.
*/
protected ILineErrorListener lineErrorListener;
/**
* The flow control listener which may be null.
*/
protected IFlowControlListener flowControlListener;
/**
* The current config.
*/
protected SerialConfig config;
/**
* The usb manager to open connections.
*/
protected UsbManager manager;
/**
* The usb manager to open connections.
*/
protected UsbDevice device;
/**
* The usb interface to open the connection.
*/
protected UsbInterface inter;
/**
* The input endpoint.
*/
protected UsbEndpoint in;
/**
* The output endpoint.
*/
protected UsbEndpoint out;
/**
* The connection.
*/
protected UsbDeviceConnection connection;
/**
* Creates a new port with the manager, device and config.
*
* @param config The serial config of the port.
* @param device The usb device.
* @param manager The usb manager.
*/
public AbstractSerialPort(UsbManager manager, UsbDevice device, SerialConfig config) {
this.config = config;
this.manager = manager;
this.device = device;
}
@Override
public SerialConfig getConfig() {
return config;
}
@Override
public void setLineErrorListener(ILineErrorListener lineErrorListener) {
this.lineErrorListener = lineErrorListener;
}
@Override
public void setFlowControlListener(IFlowControlListener flowControlListener) {
this.flowControlListener = flowControlListener;
}
/**
* Opens the connection to the device. This method requires the interface to be set.
* Subclasses should overwrite this to find the interface first.
*
* @throws IOException Thrown if the interface cannot be found, if the device cannot be opened,
* if the interface cannot be claimed or if the input and output endpoint cannot be found.
*/
protected void initConnection() throws IOException {
connection = manager.openDevice(device);
if (connection == null) throw new IOException("Failed to open device.");
try {
if (! connection.claimInterface(inter, true)) throw new IOException("Failed to claim interface.");
try {
for (int i = 0, s = inter.getEndpointCount(); i < s; i++) {
UsbEndpoint end = inter.getEndpoint(i);
if (end.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (end.getDirection() == UsbConstants.USB_DIR_IN) {
in = end;
} else if (end.getDirection() == UsbConstants.USB_DIR_OUT) {
out = end;
}
}
}
if (in == null) throw new IOException("Failed to find input endpoint.");
if (out == null) throw new IOException("Failed to find output endpoint.");
} catch (IOException e) {
connection.releaseInterface(inter);
throw e;
}
} catch (IOException e) {
connection.close();
throw e;
}
}
@Override
public void close() throws IOException {
connection.releaseInterface(inter);
connection.close();
}
/**
* Validates the value of result and throws an exception, if the
* result is negative.
*
* @param result The result to check.
* @param message The message to throw, if the result is negative.
* @throws IOException Thrown if the result is negative.
*/
protected void throwIfNegative(int result, String message) throws IOException {
if (result < 0) throw new IOException(String.format(message, result));
}
}
@@ -0,0 +1,359 @@
package com.smartbotkit.serial.android;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import com.smartbotkit.serial.FlowControl;
import com.smartbotkit.serial.InputControlLine;
import com.smartbotkit.serial.LineError;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* A serial port implementation for chips following the
* CDC ACM. The protocol documentation can be found at
* https://cscott.net/usb_dev/data/devclass/usbcdc11.pdf.
*
* This chipset is used by the OpenCR board of the turtlebot 3.
*
* @author Marcus
*/
public class CDCSerialPort extends AbstractSerialPort {
private static final int REQTYPE_HOST2DEVICE = 0x21;
private static final int REQTYPE_DEVICE2HOST = 0xA1;
private static final int SET_LINE_CODING = 0x20;
private static final int SERIAL_STATE = 0x20;
private static final int SET_CONTROL_LINE_STATE = 0x22;
private static final int CONTROL_LINE_RTS = 0x2;
private static final int CONTROL_LINE_DTR = 0x1;
private static final byte LINE_CODING_DATA_BITS_5 = 0x05;
private static final byte LINE_CODING_DATA_BITS_6 = 0x06;
private static final byte LINE_CODING_DATA_BITS_7 = 0x07;
private static final byte LINE_CODING_DATA_BITS_8 = 0x08;
private static final byte LINE_CODING_STOP_BITS_1 = 0x00;
private static final byte LINE_CODING_STOP_BITS_1_5 = 0x01;
private static final byte LINE_CODING_STOP_BITS_2 = 0x02;
private static final byte LINE_CODING_PARITY_NONE = 0x00;
private static final byte LINE_CODING_PARITY_ODD = 0x01;
private static final byte LINE_CODING_PARITY_EVEN = 0x02;
private static final byte LINE_CODING_PARITY_MARK = 0x03;
private static final byte LINE_CODING_PARITY_SPACE = 0x04;
/**
* The buffer used to read the serial state.
*/
private byte[] statusBuffer = new byte[2];
/**
* The current control line state.
*/
private int controlLine = 0;
/**
* Creates a new serial port with the specified config, manager and device.
*
* @param config The port configuration.
* @param manager The usb manager.
* @param device The device.
* @throws IOException Thrown if the port cannot be opened.
*/
public CDCSerialPort(SerialConfig config, UsbManager manager, UsbDevice device) throws IOException {
super(manager, device, config);
init();
}
/**
* Initializes the port or throws an io exception if the
* initialization fails.
*
* @throws IOException Thrown if the initialization fails.
*/
protected void init() throws IOException {
initConnection();
try {
initParameters();
setControlLine(controlLine);
} catch (IOException e) {
close();
throw e;
}
}
/**
* Opens the connection to the device.
*
* @throws IOException Thrown if the interface cannot be found, if the device cannot be opened,
* if the interface cannot be claimed or if the input and output endpoint cannot be found.
*/
protected void initConnection() throws IOException {
for (int i = 0, s = device.getInterfaceCount(); i < s; i++) {
if (device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) {
inter = device.getInterface(i);
break;
}
}
if (inter == null) throw new IOException("Failed to find interface.");
super.initConnection();
}
/**
* Initializes the connection parameters set
*
* @throws IOException
*/
protected void initParameters() throws IOException {
byte[] lineCoding = new byte[7];
setBaudRate(lineCoding);
setDataBits(lineCoding);
setStopBits(lineCoding);
setParity(lineCoding);
if (config.getFlowControl() != FlowControl.NONE) {
throw new IOException("Unsupported flow control configuration.");
}
sendControlTransfer(SET_LINE_CODING, 0, lineCoding);
}
/**
* Sets the baud rate in the line encoding array.
*
* @param lineCoding The line encoding array.
* @throws IOException Thrown if the baud rate is not supported.
*/
protected void setBaudRate(byte[] lineCoding) throws IOException {
int value = 0;
switch (config.getBaudRate()) {
case RATE_300:
value = 300;
break;
case RATE_600:
value = 600;
break;
case RATE_1200:
value = 1200;
break;
case RATE_2400:
value = 2400;
break;
case RATE_4800:
value = 4800;
break;
case RATE_9600:
value = 9600;
break;
case RATE_19200:
value = 19200;
break;
case RATE_38400:
value = 38400;
break;
case RATE_57600:
value = 57600;
break;
case RATE_115200:
value = 115200;
break;
case RATE_230400:
value = 230400;
break;
case RATE_460800:
value = 460800;
break;
case RATE_921600:
value = 921600;
break;
default:
throw new IOException("Unsupported baud rate configuration.");
}
lineCoding[0] = (byte) (value & 0xff);
lineCoding[1] = (byte) (value >> 8 & 0xff);
lineCoding[2] = (byte) (value >> 16 & 0xff);
lineCoding[3] = (byte) (value >> 24 & 0xff);
}
protected void setDataBits(byte[] lineCoding) throws IOException {
switch (config.getDataBits()) {
case BITS_5:
lineCoding[6] = LINE_CODING_DATA_BITS_5;
break;
case BITS_6:
lineCoding[6] = LINE_CODING_DATA_BITS_6;
break;
case BITS_7:
lineCoding[6] = LINE_CODING_DATA_BITS_7;
break;
case BITS_8:
lineCoding[6] = LINE_CODING_DATA_BITS_8;
break;
default:
throw new IOException("Unsupported data bits configuration.");
}
}
/**
* Sets the parity configuration in the line coding.
*
* @param lineCoding The line coding to update.
* @throws IOException Thrown if the parity configuration is unsupported.
*/
protected void setParity(byte[] lineCoding) throws IOException {
switch (config.getParity()) {
case NONE:
lineCoding[5] = LINE_CODING_PARITY_NONE;
break;
case ODD:
lineCoding[5] = LINE_CODING_PARITY_ODD;
break;
case EVEN:
lineCoding[5] = LINE_CODING_PARITY_EVEN;
break;
case MARK:
lineCoding[5] = LINE_CODING_PARITY_MARK;
break;
case SPACE:
lineCoding[5] = LINE_CODING_PARITY_SPACE;
break;
default:
throw new IOException("Unsupported parity configuration.");
}
}
/**
* Sets the stop bits configuration in the line coding.
*
* @param lineCoding The line coding to update.
* @throws IOException Thrown if the stop bits configuration is unsupported.
*/
protected void setStopBits(byte[] lineCoding) throws IOException {
switch (config.getStopBits()) {
case BITS_1:
lineCoding[4] = LINE_CODING_STOP_BITS_1;
break;
case BITS_1_5:
lineCoding[4] = LINE_CODING_STOP_BITS_1_5;
break;
case BITS_2:
lineCoding[4] = LINE_CODING_STOP_BITS_2;
break;
default:
throw new IOException("Unsupported stop bits configuration.");
}
}
/**
* Sets the control line state which defines whether rts and dtr are
* high or low.
*
* @param state The state.
* @throws IOException Thrown if the state cannot be set.
*/
protected void setControlLine(int state) throws IOException {
throwIfNegative(sendControlTransfer(SET_CONTROL_LINE_STATE, state, null), "Failed to set control line state (error: %d).");
}
/**
* Performs a control transfer from host to device with the specified request
* type and value and data with an unlimited timeout using the default interface.
*
* @param type The request type.
* @param value The request value.
* @param data The data to send or null, if none.
* @return A negative number, if the control transfer failed, zero or a
* positive number otherwise.
*/
protected int sendControlTransfer(int type, int value, byte[] data) {
int length = 0;
if(data != null) length = data.length;
return connection.controlTransfer(REQTYPE_HOST2DEVICE, type, value, 0, data, length, 0);
}
/**
* Performs a control transfer from device to host with the specified request
* type and value into the specified data array with an unlimited timeout using
* the default interface.
*
* @param type The request type.
* @param value The request value.
* @param data The data buffer to receive.
* @return A negative number, if the control transfer failed, zero or a
* positive number with the written bytes.
*/
protected int receiveControlTransfer(int type, int value, byte[] data) {
int length = 0;
if(data != null) length = data.length;
return connection.controlTransfer(REQTYPE_DEVICE2HOST, type, value, 0, data, length, 0);
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
int mask = 0;
switch (line) {
case RTS:
mask = CONTROL_LINE_RTS;
break;
case DTR:
mask = CONTROL_LINE_DTR;
break;
default:
throw new IOException("Unsupported control line.");
}
if (value) {
controlLine |= mask;
} else {
controlLine &= ~mask;
}
setControlLine(controlLine);
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int read = connection.bulkTransfer(in, buffer, length, 0);
if (read < 0) return read;
throwIfNegative(receiveControlTransfer(SERIAL_STATE, 0, statusBuffer), "Failed to read modem status (error: %s).");
interpretModemData(statusBuffer[0], statusBuffer[1]);
return read;
}
/**
* Interprets the modem data received from the serial state control transfer.
*
* @param data1 The first byte.
* @param data2 The second byte.
*/
protected void interpretModemData(byte data1, byte data2) {
// check listener multiple times to handle reentrant code
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.CTS, (data1 & 0x01) == 0x02);
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.DSR, (data1 & 0x02) == 0x02);
if (lineErrorListener != null && (data1 & 0x04) == 0x04) lineErrorListener.onLineError(LineError.BREAK);
if (lineErrorListener != null && (data1 & 0x10) == 0x10) lineErrorListener.onLineError(LineError.FRAMING);
if (lineErrorListener != null && (data1 & 0x20) == 0x20) lineErrorListener.onLineError(LineError.PARITY);
if (lineErrorListener != null && (data1 & 0x40) == 0x40) lineErrorListener.onLineError(LineError.OVERRUN);
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
while (length > 0) {
int res = connection.bulkTransfer(out, buffer, offset, buffer.length, 0);
if (res < 0) throw new IOException(String.format("Failed to write bytes (error: %d)", res));
offset += res;
length -= res;
}
}
@Override
public void close() throws IOException {
sendControlTransfer(SET_CONTROL_LINE_STATE, 0, null);
super.close();
}
}
@@ -0,0 +1,277 @@
package com.smartbotkit.serial.android;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import com.smartbotkit.serial.InputControlLine;
import com.smartbotkit.serial.LineError;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* An implementation of the serial port driver for
* the cp210x chipset. The implementation is taken from
*
*
*/
public class CP210XSerialPort extends AbstractSerialPort {
private static final int PURGE = 0x12;
private static final int IFC_ENABLE = 0x00;
private static final int SET_BAUDDIV = 0x01;
private static final int SET_LINE_CTL = 0x03;
private static final int GET_LINE_CTL = 0x04;
private static final int SET_MHS = 0x07;
private static final int SET_BAUDRATE = 0x1E;
private static final int SET_FLOW = 0x13;
private static final int SET_XON = 0x09;
private static final int SET_XOFF = 0x0A;
private static final int SET_CHARS = 0x19;
private static final int GET_MDMSTS = 0x08;
private static final int GET_COMM_STATUS = 0x10;
private static final int REQTYPE_HOST2DEVICE = 0x41;
private static final int REQTYPE_DEVICE2HOST = 0xC1;
private static final int MHS_RTS_ON = 0x202;
private static final int MHS_RTS_OFF = 0x200;
private static final int MHS_DTR_ON = 0x101;
private static final int MHS_DTR_OFF = 0x100;
private static final int PURGE_ALL = 0x000f;
private static final int UART_ENABLE = 0x0001;
private static final int UART_DISABLE = 0x0000;
/**
* Creates a new serial port with the specified config, manager and device.
*
* @param config The port configuration.
* @param manager The usb manager.
* @param device The device.
* @throws IOException Thrown if the port cannot be opened.
*/
public CP210XSerialPort(UsbManager manager, UsbDevice device, SerialConfig config) throws IOException {
super(manager, device, config);
init();
}
/**
* Opens and initializes the connection based on the settings.
*
* @throws IOException Thrown if the connection cannot be opened.
*/
protected void init() throws IOException {
initConnection();
try {
throwIfNegative(initParameters(), "Failed to set parameters (error: %d).");
throwIfNegative(initFlowControl(), "Failed to set flow control (error: %d).");
throwIfNegative(initBaudRate(), "Failed to set baud rate (error: %d).");
} catch (IOException e) {
close();
throw e;
}
}
protected void initParameters() throws IOException {
}
protected void initFlowControl() throws IOException {
}
/**
* Initializes the baud rage based on the configuration.
*
* @throws IOException Thrown if the baud rage cannot be set.
*/
protected int initBaudRate() throws IOException {
int value = 0;
switch (config.getBaudRate()) {
case RATE_300:
value = 300;
break;
case RATE_600:
value = 600;
break;
case RATE_1200:
value = 1200;
break;
case RATE_2400:
value = 2400;
break;
case RATE_4800:
value = 4800;
break;
case RATE_9600:
value = 9600;
break;
case RATE_19200:
value = 19200;
break;
case RATE_38400:
value = 38400;
break;
case RATE_57600:
value = 57600;
break;
case RATE_115200:
value = 115200;
break;
case RATE_230400:
value = 230400;
break;
case RATE_460800:
value = 460800;
break;
case RATE_921600:
value = 921600;
break;
default:
throw new IOException("Unsupported baud rate configuration.");
}
byte[] data = new byte[] {
(byte) (value & 0xff),
(byte) (value >> 8 & 0xff),
(byte) (value >> 16 & 0xff),
(byte) (value >> 24 & 0xff)
};
return sendControlTransfer(SET_BAUDRATE, 0, data);
}
/**
* Opens the connection to the device.
*
* @throws IOException Thrown if the interface cannot be found, if the device cannot be opened,
* if the interface cannot be claimed or if the input and output endpoint cannot be found.
*/
protected void initConnection() throws IOException {
if (device.getInterfaceCount() == 0) throw new IOException("Failed to find interface.");
inter = device.getInterface(0);
super.initConnection();
}
/**
* Performs a control transfer from host to device with the specified request
* type and value and data with an unlimited timeout using the default interface.
*
* @param type The request type.
* @param value The request value.
* @param data The data to send or null, if none.
* @return A negative number, if the control transfer failed, zero or a
* positive number otherwise.
*/
protected int sendControlTransfer(int type, int value, byte[] data) {
int length = 0;
if(data != null) length = data.length;
return connection.controlTransfer(REQTYPE_HOST2DEVICE, type, value, inter.getId(), data, length, 0);
}
/**
* Performs a control transfer from device to host with the specified request
* type and value into the specified data array with an unlimited timeout using
* the default interface.
*
* @param type The request type.
* @param value The request value.
* @param data The data buffer to receive.
* @return A negative number, if the control transfer failed, zero or a
* positive number with the written bytes.
*/
protected int receiveControlTransfer(int type, int value, byte[] data) {
int length = 0;
if(data != null) length = data.length;
return connection.controlTransfer(REQTYPE_DEVICE2HOST, type, value, inter.getId(), data, length, 0);
}
private byte[] getModemState() throws IOException {
byte[] data = new byte[1];
throwIfNegative(receiveControlTransfer(GET_MDMSTS, 0, data), "Failed to read modem state (error: %d).");
return data;
}
private byte[] getCommStatus() throws IOException {
byte[] data = new byte[19];
throwIfNegative(receiveControlTransfer(GET_COMM_STATUS, 0, data), "Failed to read comm state (error: %d).");
return data;
}
private short getCTL() throws IOException {
byte[] data = new byte[2];
throwIfNegative(receiveControlTransfer(GET_LINE_CTL, 0, data), "Failed to read line state (error: %d).");
return (short)((data[1] << 8) | (data[0] & 0xFF));
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
int flag = 0;
switch (line) {
case DTR:
if (value) flag = MHS_DTR_ON;
else flag = MHS_DTR_OFF;
break;
case RTS:
if (value) flag = MHS_RTS_ON;
else flag = MHS_RTS_OFF;
break;
default:
throw new IOException("Invalid line configuration.");
}
throwIfNegative(sendControlTransfer(SET_MHS, flag, null), "Failed to set line (error: %d).");
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int read = connection.bulkTransfer(in, buffer, length, 0);
if (read < 0) return read;
throwIfNegative(receiveControlTransfer(SERIAL_STATE, 0, statusBuffer), "Failed to read modem status (error: %s).");
interpretModemData(statusBuffer[0], statusBuffer[1]);
return read;
}
/**
* Interprets the modem data received from the serial state control transfer.
*
* @param data1 The first byte.
* @param data2 The second byte.
*/
protected void interpretModemData(byte data1, byte data2) {
// check listener multiple times to handle reentrant code
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.CTS, (data1 & 0x01) == 0x02);
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.DSR, (data1 & 0x02) == 0x02);
if (lineErrorListener != null && (data1 & 0x04) == 0x04) lineErrorListener.onLineError(LineError.BREAK);
if (lineErrorListener != null && (data1 & 0x10) == 0x10) lineErrorListener.onLineError(LineError.FRAMING);
if (lineErrorListener != null && (data1 & 0x20) == 0x20) lineErrorListener.onLineError(LineError.PARITY);
if (lineErrorListener != null && (data1 & 0x40) == 0x40) lineErrorListener.onLineError(LineError.OVERRUN);
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
while (length > 0) {
int res = connection.bulkTransfer(out, buffer, offset, buffer.length, 0);
if (res < 0) throw new IOException(String.format("Failed to write bytes (error: %d)", res));
offset += res;
length -= res;
}
}
@Override
public void close() throws IOException {
sendControlTransfer(PURGE, PURGE_ALL, null);
sendControlTransfer(IFC_ENABLE, UART_DISABLE, null);
super.close();
}
}
@@ -0,0 +1,402 @@
package com.smartbotkit.serial.android;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import com.smartbotkit.serial.InputControlLine;
import com.smartbotkit.serial.LineError;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* Implements a serial port for an FTDI chip. This implementation is
* almost a literal translation of the FTDI implementation in
* https://github.com/felHR85.
*
* This chipset is used by the Kobuki base of the turtlebot 2.
*
* @author Marcus
*/
public class FTDISerialPort extends AbstractSerialPort {
private static final int REQTYPE_HOST2DEVICE = 0x40;
private static final int SIO_RESET = 0;
private static final int SIO_MODEM_CTRL = 1;
private static final int SIO_SET_FLOW_CTRL = 2;
private static final int SIO_SET_BAUD_RATE = 3;
private static final int SIO_SET_DATA = 4;
private static final int SIO_SET_DTR_MASK = 0x1;
private static final int SIO_SET_DTR_HIGH = (1 | (SIO_SET_DTR_MASK << 8));
private static final int SIO_SET_DTR_LOW = (0 | (SIO_SET_DTR_MASK << 8));
private static final int SIO_SET_RTS_MASK = 0x2;
private static final int SIO_SET_RTS_HIGH = (2 | (SIO_SET_RTS_MASK << 8));
private static final int SIO_SET_RTS_LOW = (0 | (SIO_SET_RTS_MASK << 8));
private static final int BAUDRATE_300 = 0x2710;
private static final int BAUDRATE_600 = 0x1388;
private static final int BAUDRATE_1200 = 0x09c4;
private static final int BAUDRATE_2400 = 0x04e2;
private static final int BAUDRATE_4800 = 0x0271;
private static final int BAUDRATE_9600 = 0x4138;
private static final int BAUDRATE_19200 = 0x809c;
private static final int BAUDRATE_38400 = 0xc04e;
private static final int BAUDRATE_57600 = 0x0034;
private static final int BAUDRATE_115200 = 0x001a;
private static final int BAUDRATE_230400 = 0x000d;
private static final int BAUDRATE_460800 = 0x4006;
private static final int BAUDRATE_921600 = 0x8003;
private static final int SET_DATA_DEFAULT = 0x0008;
private static final int SET_MODEM_CTRL_DEFAULT1 = 0x0101;
private static final int SET_MODEM_CTRL_DEFAULT2 = 0x0202;
private static final int SET_MODEM_CTRL_DEFAULT3 = 0x0100;
private static final int SET_MODEM_CTRL_DEFAULT4 = 0x0200;
private static final int SET_FLOW_CTRL_DEFAULT = 0x0000;
private static final int SET_FLOW_CTRL_SOFTWARE = 0x1311;
private static final int INTERFACE_OFFSET_DEFAULT = 1;
private static final int INTERFACE_OFFSET_RTS_CTS = 2;
private static final int INTERFACE_OFFSET_DSR_DTR = 3;
private static final int INTERFACE_OFFSET_XON_XOFF = 5;
/**
* The buffer to read data with the length initialized
* to maximum + 2 bytes for the status.
*/
protected byte[] readBuffer = new byte[4096 + 2];
/**
* Creates a new serial port with the specified config, manager and device.
*
* @param config The port configuration.
* @param manager The usb manager.
* @param device The device.
* @throws IOException Thrown if the port cannot be opened.
*/
public FTDISerialPort(UsbManager manager, UsbDevice device, SerialConfig config) throws IOException {
super(manager, device, config);
init();
}
/**
* Opens and initializes the connection based on the settings.
*
* @throws IOException Thrown if the connection cannot be opened.
*/
protected void init() throws IOException {
initConnection();
try {
throwIfNegative(sendReset(), "Failed to reset device (error: %d).");
throwIfNegative(initParameters(), "Failed to set parameters (error: %d).");
throwIfNegative(initFlowControl(), "Failed to set flow control (error: %d).");
throwIfNegative(initBaudRate(), "Failed to set baud rate (error: %d).");
} catch (IOException e) {
close();
throw e;
}
}
/**
* Opens the connection to the device.
*
* @throws IOException Thrown if the interface cannot be found, if the device cannot be opened,
* if the interface cannot be claimed or if the input and output endpoint cannot be found.
*/
protected void initConnection() throws IOException {
if (device.getInterfaceCount() == 0) throw new IOException("Failed to find interface.");
inter = device.getInterface(0);
super.initConnection();
}
/**
* Sends a reset.
*
* @return The value of the reset.
*/
protected int sendReset() {
int result = sendControlTransfer(SIO_RESET, 0);
result = Math.min(result, sendControlTransfer(SIO_MODEM_CTRL, SET_MODEM_CTRL_DEFAULT1));
result = Math.min(result, sendControlTransfer(SIO_MODEM_CTRL, SET_MODEM_CTRL_DEFAULT2));
return result;
}
/**
* Initializes the baud rate and returns the result of the control command.
*
* @return A negative value if failed, zero or positive, if success.
* @throws IOException Thrown if the baud rate is not supported.
*/
protected int initBaudRate() throws IOException {
switch (config.getBaudRate()) {
case RATE_300:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_300);
case RATE_600:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_600);
case RATE_1200:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_1200);
case RATE_2400:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_2400);
case RATE_4800:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_4800);
case RATE_9600:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_9600);
case RATE_19200:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_19200);
case RATE_38400:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_38400);
case RATE_57600:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_57600);
case RATE_115200:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_115200);
case RATE_230400:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_230400);
case RATE_460800:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_460800);
case RATE_921600:
return sendControlTransfer(SIO_SET_BAUD_RATE, BAUDRATE_921600);
default:
throw new IOException("Unsupported baud rate configuration.");
}
}
/**
* Initializes the connection parameters (parity, data bits and stop bits).
*
* @return A negative value if failed, zero or positive, if success.
* @throws IOException Thrown if the parity, data bits or stop bits
* are not supported.
*/
protected int initParameters() throws IOException {
int value = setDatabits(0);
value = setParity(value);
value = setStopBits(value);
return sendControlTransfer(SIO_SET_DATA, value);
}
/**
* Sets the bits in the value according to the data bits
* configured in the serial config.
*
* @param value The base value.
* @return The adjusted value.
* @throws IOException Thrown if the configuration is not supported.
*/
protected int setDatabits(int value) throws IOException {
switch (config.getDataBits()) {
case BITS_5:
value |= 1;
value &= ~(1 << 1);
value |= (1 << 2);
value &= ~(1 << 3);
break;
case BITS_6:
value &= ~1;
value |= (1 << 1);
value |= (1 << 2);
value &= ~(1 << 3);
break;
case BITS_7:
value |= 1;
value |= (1 << 1);
value |= (1 << 2);
value &= ~(1 << 3);
break;
case BITS_8:
value &= ~1;
value &= ~(1 << 1);
value &= ~(1 << 2);
value |= (1 << 3);
break;
default:
throw new IOException("Unsupported data bits configuration.");
}
return value;
}
/**
* Sets the bits in the value according to the stop bits
* configured in the serial config.
*
* @param value The base value.
* @return The adjusted value.
* @throws IOException Thrown if the configuration is not supported.
*/
protected int setStopBits(int value) throws IOException {
switch (config.getStopBits()) {
case BITS_1:
value &= ~(1 << 11);
value &= ~(1 << 12);
value &= ~(1 << 13);
break;
case BITS_1_5:
value |= (1 << 11);
value &= ~(1 << 12);
value &= ~(1 << 13);
break;
case BITS_2:
value &= ~(1 << 11);
value |= (1 << 12);
value &= ~(1 << 13);
break;
default:
throw new IOException("Unsupported stop bits configuration.");
}
return value;
}
/**
* Sets the bits in the value according to the parity
* configured in the serial config.
*
* @param value The base value.
* @return The adjusted value.
* @throws IOException Thrown if the configuration is not supported.
*/
protected int setParity(int value) throws IOException {
switch (config.getParity()) {
case NONE:
value &= ~(1 << 8);
value &= ~(1 << 9);
value &= ~(1 << 10);
break;
case ODD:
value |= (1 << 8);
value &= ~(1 << 9);
value &= ~(1 << 10);
break;
case EVEN:
value &= ~(1 << 8);
value |= (1 << 9);
value &= ~(1 << 10);
break;
case MARK:
value |= (1 << 8);
value |= (1 << 9);
value &= ~(1 << 10);
break;
case SPACE:
value &= ~(1 << 8);
value &= ~(1 << 9);
value |= (1 << 10);
break;
default:
throw new IOException("Unsupported parity configuration.");
}
return value;
}
/**
* Performs a control transfer with the specified request type and value
* and zero data with an unlimited timeout using the default interface.
*
* @param type The request type.
* @param value The request value.
* @return A negative number, if the control transfer failed, zero or a
* positive number otherwise.
*/
protected int sendControlTransfer(int type, int value) {
return sendControlTransfer(type, value, INTERFACE_OFFSET_DEFAULT);
}
/**
* Performs a control transfer with the specified request type and value
* and zero data with an unlimited timeout using the specified interface
* offset.
*
* @param type The request type.
* @param value The request value.
* @param interfaceOffset The interface offset.
* @return A negative number, if the control transfer failed, zero or a
* positive number otherwise.
*/
protected int sendControlTransfer(int type, int value, int interfaceOffset) {
return connection.controlTransfer(REQTYPE_HOST2DEVICE, type, value, inter.getId() + interfaceOffset, null, 0, 0);
}
/**
* Configures the flow control value according to the
* configuration of the serial config.
*
* @return The result of the control transfer.
* @throws IOException Thrown if the configuration
*/
protected int initFlowControl() throws IOException {
switch (config.getFlowControl()) {
case NONE:
return sendControlTransfer(SIO_SET_FLOW_CTRL, SET_FLOW_CTRL_DEFAULT, INTERFACE_OFFSET_DEFAULT);
case DSR_DTR:
return sendControlTransfer(SIO_SET_FLOW_CTRL, SET_FLOW_CTRL_DEFAULT, INTERFACE_OFFSET_DSR_DTR);
case RTS_CTS:
return sendControlTransfer(SIO_SET_FLOW_CTRL, SET_FLOW_CTRL_DEFAULT, INTERFACE_OFFSET_RTS_CTS);
case XON_XOFF:
return sendControlTransfer(SIO_SET_FLOW_CTRL, SET_FLOW_CTRL_SOFTWARE, INTERFACE_OFFSET_XON_XOFF);
default:
throw new IOException("Unsupported flow control configuration.");
}
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
switch (line) {
case RTS:
throwIfNegative(sendControlTransfer(SIO_MODEM_CTRL, value?SIO_SET_RTS_HIGH:SIO_SET_RTS_LOW), "Failed to set rts value (error: %d).");
break;
case DTR:
throwIfNegative(sendControlTransfer(SIO_MODEM_CTRL, value?SIO_SET_DTR_HIGH:SIO_SET_DTR_LOW), "Failed to set dtr value (error: %d).");
break;
default:
throw new IOException("Unsupported control line.");
}
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
int maximum = Math.min(length + 2, readBuffer.length);
int read = connection.bulkTransfer(in, readBuffer, maximum, 0);
if (read < 2) throw new IOException("Failed to read modem data.");
interpretModemData(readBuffer[0], readBuffer[1]);
if (read > 2) System.arraycopy(readBuffer, 2, buffer, offset, read - 2);
return read - 2;
}
/**
* Interprets the modem data send as part of each bulk transfer
* to the in endpoint.
*
* @param data1 The first byte.
* @param data2 The second byte.
*/
protected void interpretModemData(byte data1, byte data2) {
// check listener multiple times to handle reentrant code
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.CTS, (data1 & 0x10) == 0x10);
if (flowControlListener != null) flowControlListener.onLineSet(InputControlLine.DSR, (data1 & 0x20) == 0x20);
if (lineErrorListener != null && (data2 & 0x10) == 0x10) lineErrorListener.onLineError(LineError.BREAK);
if (lineErrorListener != null && (data2 & 0x20) == 0x20) lineErrorListener.onLineError(LineError.OVERRUN);
if (lineErrorListener != null && (data2 & 0x40) == 0x40) lineErrorListener.onLineError(LineError.PARITY);
if (lineErrorListener != null && (data2 & 0x80) == 0x80) lineErrorListener.onLineError(LineError.FRAMING);
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
while (length > 0) {
int res = connection.bulkTransfer(out, buffer, offset, buffer.length, 0);
if (res < 0) throw new IOException(String.format("Failed to write bytes (error: %d)", res));
offset += res;
length -= res;
}
}
@Override
public void close() throws IOException {
sendControlTransfer(SIO_MODEM_CTRL, SET_MODEM_CTRL_DEFAULT3);
sendControlTransfer(SIO_MODEM_CTRL, SET_MODEM_CTRL_DEFAULT4);
super.close();
}
}
@@ -0,0 +1,92 @@
package com.smartbotkit.serial.test;
import com.smartbotkit.serial.IFlowControlListener;
import com.smartbotkit.serial.ILineErrorListener;
import com.smartbotkit.serial.ISerialPort;
import com.smartbotkit.serial.OutputControlLine;
import com.smartbotkit.serial.SerialConfig;
import java.io.IOException;
/**
* A serial port intended for unit testing. The port
* will continuously replay the data specified in
* the constructor.
*
* @author Marcus
*/
public class TestSerialPort implements ISerialPort {
/**
* The configuration of the port.
*/
protected SerialConfig config;
/**
* The data to be playing.
*/
protected byte[] data;
/**
* The current pointer into the data array.
*/
protected int read = 0;
/**
* A flag to indicate whether the port has been closed.
*/
protected boolean closed = false;
/**
* Creates a new serial port with the configuration
* and the data to play back.
*
* @param config The port configuration.
* @param data The data to play back.
*/
public TestSerialPort(SerialConfig config, byte[] data) {
this.config = config;
this.data = data;
}
@Override
public SerialConfig getConfig() {
return config;
}
@Override
public void setLine(OutputControlLine line, boolean value) throws IOException {
if (closed) throw new IOException("Serial port is closed.");
}
@Override
public void setLineErrorListener(ILineErrorListener lineErrorListener) {
// do nothing
}
@Override
public void setFlowControlListener(IFlowControlListener flowControlListener) {
// do nothing
}
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
if (closed) throw new IOException("Serial port is closed.");
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
if (closed) throw new IOException("Serial port is closed.");
int remainder = data.length - read;
int max = Math.min(remainder, length);
System.arraycopy(data, read, buffer, offset, max);
read += max;
if (read == data.length) read = 0;
return max;
}
@Override
public void close() throws IOException {
this.closed = true;
}
}