org.bidib.jbidibc.scm.ScmSerialConnector Maven / Gradle / Ivy
package org.bidib.jbidibc.scm;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.bidib.jbidibc.core.BidibLibrary;
import org.bidib.jbidibc.core.MessageReceiver;
import org.bidib.jbidibc.core.base.AbstractBaseBidib;
import org.bidib.jbidibc.core.base.RawMessageListener;
import org.bidib.jbidibc.core.exception.InvalidConfigurationException;
import org.bidib.jbidibc.core.exception.InvalidLibraryException;
import org.bidib.jbidibc.core.exception.PortNotFoundException;
import org.bidib.jbidibc.core.exception.PortNotOpenedException;
import org.bidib.jbidibc.core.exception.PortNotReadyForSendException;
import org.bidib.jbidibc.core.helpers.Context;
import org.bidib.jbidibc.core.utils.ByteUtils;
import org.bidib.jbidibc.serial.LineStatusListener;
import org.bidib.jbidibc.serial.SerialMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.serialpundit.core.SerialComException;
import com.serialpundit.serial.ISerialComDataListener;
import com.serialpundit.serial.ISerialComEventListener;
import com.serialpundit.serial.SerialComLineEvent;
import com.serialpundit.serial.SerialComManager;
import com.serialpundit.serial.SerialComManager.BAUDRATE;
import com.serialpundit.serial.SerialComManager.DATABITS;
import com.serialpundit.serial.SerialComManager.FLOWCONTROL;
import com.serialpundit.serial.SerialComManager.PARITY;
import com.serialpundit.serial.SerialComManager.STOPBITS;
public class ScmSerialConnector extends AbstractBaseBidib {
private static final Logger LOGGER = LoggerFactory.getLogger(ScmSerialConnector.class);
private static final Logger MSG_RAW_LOGGER = LoggerFactory.getLogger("RAW");
private String libraryDirectoryName = "jbidibc";
private SerialComManager scm;
private long handle = -1;
private ISerialComDataListener dataListener;
private ISerialComEventListener eventListener;
private boolean addEventListener = false;
private boolean useHardwareFlowControl = false;
private ByteArrayOutputStream sendBuffer = new ByteArrayOutputStream(100);
private MessageReceiver messageReceiver;
private LineStatusListener lineStatusListener;
/**
* @return the messageReceiver
*/
@Override
public MessageReceiver getMessageReceiver() {
return messageReceiver;
}
/**
* @param messageReceiver
* the messageReceiver to set
*/
@Override
public void setMessageReceiver(MessageReceiver messageReceiver) {
this.messageReceiver = messageReceiver;
}
/**
* @return the libraryDirectoryName
*/
public String getLibraryDirectoryName() {
return libraryDirectoryName;
}
/**
* @param libraryDirectoryName
* the libraryDirectoryName to set
*/
public void setLibraryDirectoryName(String libraryDirectoryName) {
this.libraryDirectoryName = libraryDirectoryName;
}
/**
* @return the lineStatusListener
*/
public LineStatusListener getLineStatusListener() {
return lineStatusListener;
}
/**
* @param lineStatusListener
* the lineStatusListener to set
*/
public void setLineStatusListener(LineStatusListener lineStatusListener) {
this.lineStatusListener = lineStatusListener;
}
// @Override
protected boolean isImplAvaiable() {
return (scm != null);
}
@Override
public boolean isOpened() {
boolean isOpened = (handle > 0);
return isOpened;
}
private BAUDRATE getBaudRate(int baudRate) {
for (BAUDRATE br : BAUDRATE.values()) {
if (br.getValue() == baudRate) {
return br;
}
}
return BAUDRATE.B115200;
}
@Override
protected void internalOpen(String portName, final Context context)
throws PortNotFoundException, PortNotOpenedException {
super.internalOpen(portName, context);
final MessageReceiver serialMessageReceiver = getMessageReceiver();
String tempDir = System.getProperty("java.io.tmpdir");
File temp = new File(tempDir, libraryDirectoryName);
try {
scm = new SerialComManager("scm", temp.getAbsolutePath(), true, false);
Boolean useHardwareFlowControl = context.get("serial.useHardwareFlowControl", Boolean.class, Boolean.TRUE);
LOGGER.info("Open port with portName: {}, useHardwareFlowControl: {}", portName, useHardwareFlowControl);
// open the port
handle = scm.openComPort(portName, true, true, true);
LOGGER.info("Opened serial port, handle: {}", handle);
if (useHardwareFlowControl) {
scm.configureComPortControl(handle, FLOWCONTROL.RTS_CTS, 'x', 'x', false, true);
}
else {
scm.configureComPortControl(handle, FLOWCONTROL.NONE, 'x', 'x', false, true);
}
Integer baudRate = context.get("serial.baudrate", Integer.class, Integer.valueOf(115200));
LOGGER.info("Open port with baudRate: {}", baudRate);
BAUDRATE scmBaudRate = getBaudRate(baudRate);
scm.configureComPortData(handle, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, scmBaudRate, 0);
}
catch (IOException ex) {
LOGGER.warn("Configure SCM com port failed.", ex);
throw new InvalidConfigurationException("Configure SCM com port failed.");
}
startReceiverAndQueues(serialMessageReceiver, context);
// add event listener
if (addEventListener) {
eventListener = new ISerialComEventListener() {
@Override
public void onNewSerialEvent(SerialComLineEvent lineEvent) {
LOGGER.error("eventCTS : {}, eventDSR : {}", lineEvent.getCTS(), lineEvent.getDSR());
}
};
try {
scm.registerLineEventListener(handle, eventListener);
}
catch (SerialComException ex) {
LOGGER.warn("Register line event listener to SCM com port failed.", ex);
throw new InvalidConfigurationException("Register line event listener to SCM com port failed.");
}
}
dataListener = new ISerialComDataListener() {
@Override
public void onNewSerialDataAvailable(final byte[] data) {
// TODO remove the logger
MSG_RAW_LOGGER
.info("<<<< Serial data available, len: {}, data: {}", data.length, ByteUtils.bytesToHex(data));
receive(data, data.length);
// TODO remove the logger
MSG_RAW_LOGGER.info("<<<< Serial data received.");
}
@Override
public void onDataListenerError(int errorNum) {
LOGGER.error("Data listener notified an error: {}", errorNum);
if (isConnected()) {
LOGGER.info("Close the port.");
setConnected(false);
if (dataListener != null) {
try {
LOGGER.info("Unregister data listener.");
scm.unregisterDataListener(handle, dataListener);
dataListener = null;
}
catch (Exception ex) {
LOGGER.warn("Unregister data listener after error detection failed.", ex);
}
}
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("Error detected. Close the port.");
if (dataListener != null) {
try {
scm.unregisterDataListener(handle, dataListener);
dataListener = null;
}
catch (Exception ex) {
LOGGER.warn("Unregister data listener after error detection failed.", ex);
}
}
if (eventListener != null) {
try {
scm.unregisterLineEventListener(handle, eventListener);
eventListener = null;
}
catch (Exception ex) {
LOGGER.warn("Unregister event listener after error detection failed.", ex);
}
}
try {
close();
}
catch (Exception ex) {
LOGGER.warn("Close scm port failed.", ex);
}
}
});
t1.start();
}
else {
LOGGER.info("Port is closed.");
}
}
};
LOGGER.info("Registering data listener for handle: {}.", handle);
// register data listener for this port
try {
scm.registerDataListener(handle, dataListener);
}
catch (SerialComException ex) {
LOGGER.warn("Register data listener to SCM com port failed.", ex);
throw new InvalidConfigurationException("Register data listener to SCM com port failed.");
}
LOGGER.info("Registered data listener.");
if (useHardwareFlowControl) {
// Activate DTR
// try {
// LOGGER.info("Activate DTR.");
//
// scm.setDTR(handle, true); // pin 1 in DIN8; on main connector, this is DTR
// }
// catch (Exception e) {
// LOGGER.warn("Set DTR true failed.", e);
// }
try {
LOGGER.info("Activate RTS.");
scm.setRTS(handle, true);
}
catch (Exception e) {
LOGGER.warn("Set RTS true failed.", e);
}
}
dumpLineStatus(handle);
setConnected(true);
}
@Override
public boolean close() {
// close the port if available
if (scm != null) {
LOGGER.info("Close the port, handle: {}", handle);
long start = System.currentTimeMillis();
// unregister data listener
LOGGER.info("Unregister data listener: {}", dataListener);
if (dataListener != null && handle > 0) {
try {
scm.unregisterDataListener(handle, dataListener);
}
catch (SerialComException ex) {
LOGGER.warn("Unregister dataListener failed.", ex);
}
try {
Thread.sleep(200);
}
catch (InterruptedException ex) {
LOGGER.warn("Sleep after unregister data listener failed.", ex);
}
}
dataListener = null;
// unregister line event listener
if (eventListener != null && handle > 0) {
LOGGER.info("Unregister line event listener.");
try {
scm.unregisterLineEventListener(handle, eventListener);
}
catch (SerialComException ex) {
LOGGER.warn("Unregister lineEventListener failed.", ex);
}
try {
Thread.sleep(200);
}
catch (InterruptedException ex) {
LOGGER.warn("Sleep after unregister line event listener failed.", ex);
}
}
eventListener = null;
final MessageReceiver serialMessageReceiver = getMessageReceiver();
stopReceiverAndQueues(serialMessageReceiver);
if (handle > 0) {
try {
LOGGER.info("Close the COM port: {}", handle);
// port.close();
scm.closeComPort(handle);
}
catch (Exception e) {
LOGGER.warn("Close port failed.", e);
}
}
else {
LOGGER.info("Don't close port because handle is not valid.");
}
long end = System.currentTimeMillis();
LOGGER.info("Closed the port. duration: {}", end - start);
fireCtsChanged(false);
setConnected(false);
scm = null;
handle = -1;
// cleanupAfterClose(serialMessageReceiver);
return true;
}
else {
LOGGER.info("No port to close available.");
}
return false;
}
@Override
protected void sendData(final ByteArrayOutputStream data, final RawMessageListener rawMessageListener) {
if (handle > 0 && data != null) {
// byte[] bytes = data.toByteArray();
//
// if (bytes.length < 1) {
// LOGGER.warn("No data in provided bytearray!!!!!");
// }
try {
if (!firstPacketSent) {
LOGGER.info("Send initial sequence.");
try {
byte[] initialSequence = new byte[] { (byte) BidibLibrary.BIDIB_PKT_MAGIC };
if (MSG_RAW_LOGGER.isInfoEnabled()) {
MSG_RAW_LOGGER
.info(">> [{}] - {}", initialSequence.length, ByteUtils.bytesToHex(initialSequence));
}
if (rawMessageListener != null) {
rawMessageListener.notifySend(initialSequence);
}
scm.writeBytes(handle, initialSequence);
Thread.sleep(10);
if (MSG_RAW_LOGGER.isInfoEnabled()) {
MSG_RAW_LOGGER
.info(">> [{}] - {}", initialSequence.length, ByteUtils.bytesToHex(initialSequence));
}
if (rawMessageListener != null) {
rawMessageListener.notifySend(initialSequence);
}
scm.writeBytes(handle, initialSequence);
firstPacketSent = true;
LOGGER.info("Send initial sequence passed.");
}
catch (Exception ex) {
LOGGER.warn("Send initial sequence failed.", ex);
}
}
// LOGGER.info("Reset the send buffer.");
sendBuffer.reset();
// encode the data for serial transfer
SerialMessageEncoder.encodeMessage(data, sendBuffer);
byte[] refContent = sendBuffer.toByteArray();
if (MSG_RAW_LOGGER.isInfoEnabled()) {
MSG_RAW_LOGGER.info(">> [{}] - {}", refContent.length, ByteUtils.bytesToHex(refContent));
}
if (rawMessageListener != null) {
rawMessageListener.notifySend(refContent);
}
int sent = scm.writeBytes(handle, refContent);
if (sent == 0) {
MSG_RAW_LOGGER.warn(">> sent bytes: {}", sent);
LOGGER
.error("The message has not been sent to handle: {}, message: {}", handle,
ByteUtils.bytesToHex(refContent));
// TODO check if the port is still open
int[] lineStatus = dumpLineStatus(handle);
if (lineStatus[0] == 0 /* CTS */) {
throw new PortNotReadyForSendException(scm.getPortName(handle));
}
throw new RuntimeException("Write message to output failed: " + ByteUtils.bytesToHex(refContent));
}
else {
MSG_RAW_LOGGER.info(">> sent bytes: {}", sent);
}
}
catch (Exception ex) {
byte[] bytes = data.toByteArray();
LOGGER
.warn("Send message to output stream failed: [{}] - {}", bytes.length, ByteUtils.bytesToHex(bytes),
ex);
throw new RuntimeException("Send message to output stream failed: " + ByteUtils.bytesToHex(bytes), ex);
}
finally {
sendBuffer.reset();
}
}
else {
LOGGER.warn("No port handle available. Data is not sent!");
}
}
public List getPortIdentifiers() {
List portIdentifiers = new ArrayList();
try {
String tempDir = System.getProperty("java.io.tmpdir");
File temp = new File(tempDir, "jbidibc");
// temp.mkdirs();
if (scm == null) {
LOGGER.info("Create the scm instance.");
scm = new SerialComManager("scm", temp.getAbsolutePath(), true, false);
}
String[] ports = scm.listAvailableComPorts();
for (String portIdentifier : ports) {
portIdentifiers.add(portIdentifier);
}
}
catch (UnsatisfiedLinkError ule) {
LOGGER.warn("Get comm port identifiers failed.", ule);
throw new InvalidLibraryException(ule.getMessage(), ule.getCause());
}
catch (Error error) {
LOGGER.warn("Get comm port identifiers failed.", error);
throw new RuntimeException(error.getMessage(), error.getCause());
}
catch (IOException ex) {
LOGGER.warn("Get comm port identifiers failed.", ex);
throw new InvalidLibraryException(ex.getMessage(), ex.getCause());
}
return portIdentifiers;
}
private int[] dumpLineStatus(long handle) {
// Linux OS : CTS, DSR, DCD, RI, LOOP, RTS, DTR respectively.
// MAC OS X : CTS, DSR, DCD, RI, 0, RTS, DTR respectively.
// Windows OS : CTS, DSR, DCD, RI, 0, 0, 0 respectively.
int[] lineStatus = null;
try {
lineStatus = scm.getLinesStatus(handle);
LOGGER
.info(">>> Fetched current line status, CTS: {}, DSR: {}, DCD: {}", lineStatus[0], lineStatus[1],
lineStatus[2]);
fireCtsChanged(lineStatus[0] > 0 ? true : false);
}
catch (SerialComException ex) {
LOGGER.warn("Get the line status failed.", ex);
}
return lineStatus;
}
protected void fireCtsChanged(boolean ready) {
LOGGER.info("CTS has changed, ready: {}", ready);
// signal changed line status to the bidib implementation
if (lineStatusListener != null) {
lineStatusListener.notifyLineStatusChanged(ready);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy