|
|
@ -0,0 +1,72 @@ |
|
|
|
package com.my.graphiteDigesterBg.diframe.connection; |
|
|
|
import com.fazecast.jSerialComm.SerialPort; |
|
|
|
import com.fazecast.jSerialComm.SerialPortDataListener; |
|
|
|
import com.fazecast.jSerialComm.SerialPortEvent; |
|
|
|
import com.my.graphiteDigesterBg.diframe.DiDevice; |
|
|
|
import com.my.graphiteDigesterBg.diframe.DiDeviceConnection; |
|
|
|
import org.slf4j.Logger; |
|
|
|
import org.slf4j.LoggerFactory; |
|
|
|
import org.springframework.core.env.Environment; |
|
|
|
import java.nio.ByteBuffer; |
|
|
|
public class DiConSerialPort implements DiDeviceConnection { |
|
|
|
// logger |
|
|
|
public static final Logger LOG = LoggerFactory.getLogger(DiConSerialPort.class); |
|
|
|
// device |
|
|
|
private DiDevice device; |
|
|
|
// serial port connection |
|
|
|
private SerialPort connection; |
|
|
|
|
|
|
|
@Override |
|
|
|
public void setDevice(DiDevice device) { |
|
|
|
this.device = device; |
|
|
|
} |
|
|
|
|
|
|
|
@Override |
|
|
|
public void connect() { |
|
|
|
Environment env = this.device.getEnv(); |
|
|
|
String path = env.getProperty("device.connection.path"); |
|
|
|
if ( null == path ) { |
|
|
|
throw new RuntimeException("device option 'device.connection.path' is required."); |
|
|
|
} |
|
|
|
Integer baudRate = env.getProperty("device.connection.baudRate", Integer.class); |
|
|
|
if ( null == baudRate ) { |
|
|
|
throw new RuntimeException("device option 'device.connection.baudRate' is required."); |
|
|
|
} |
|
|
|
|
|
|
|
this.connection = SerialPort.getCommPort(path); |
|
|
|
this.connection.openPort(); |
|
|
|
if ( !this.connection.isOpen() ) { |
|
|
|
throw new RuntimeException("Failed to open serial port"); |
|
|
|
} |
|
|
|
|
|
|
|
this.connection.setBaudRate(baudRate); |
|
|
|
this.connection.addDataListener(new SerialPortDataListener() { |
|
|
|
@Override |
|
|
|
public int getListeningEvents() { |
|
|
|
return SerialPort.LISTENING_EVENT_DATA_RECEIVED; |
|
|
|
} |
|
|
|
@Override |
|
|
|
public void serialEvent(SerialPortEvent serialPortEvent) { |
|
|
|
DiConSerialPort.this.handleOnData(serialPortEvent); |
|
|
|
} |
|
|
|
}); |
|
|
|
LOG.info("Connecting to device: {}@{}", path, baudRate); |
|
|
|
} |
|
|
|
|
|
|
|
// handle on data |
|
|
|
private void handleOnData(SerialPortEvent serialPortEvent) { |
|
|
|
byte[] data = serialPortEvent.getReceivedData(); |
|
|
|
System.out.println("Received data of size: " + data.length); |
|
|
|
for (byte b : data) { |
|
|
|
System.out.print((char)b); |
|
|
|
} |
|
|
|
System.out.println("\n"); |
|
|
|
} |
|
|
|
|
|
|
|
@Override |
|
|
|
public ByteBuffer call(ByteBuffer parameter) { |
|
|
|
byte[] data = parameter.array(); |
|
|
|
this.connection.writeBytes(data, data.length); |
|
|
|
return null; |
|
|
|
} |
|
|
|
} |