@Async("asyncServiceExecutor")
public void executeAsync(SerialPort globalSerialPort,byte[] msg) {
//logger.info("开始异步发送数据");
if(globalSerialPort == null || !globalSerialPort.isOpen()) {
logger.info("串口异步发送数据失败");
return;
}
try{
globalSerialPort.writeBytes(msg,msg.length);//发送数据
}catch(Exception e){
logger.debug(e.toString());
}
logger.info("串口异步发送数据结束");
}
public static SerialPort LiqSerialPort = null;
//串口初始化
public void openAndListenerLiqCOM(StringLiquidCoolCOM) {
if(LiqSerialPort != null && LiqSerialPort.isOpen()) {
logger.info("串口{}[isOpen:{}]已开启",LiquidCoolCOM,LiqSerialPort.isOpen());
return;
}
if(LiqSerialPort == null) {
LiqSerialPort = SerialPort.getCommPort(LiquidCoolCOM);
LiqSerialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING,0, 0);
LiqSerialPort.setBaudRate(9600);
LiqSerialPort.setNumDataBits(8);
LiqSerialPort.setNumStopBits(1);
LiqSerialPort.openPort();
logger.info("串口{}[isOpen:{}]",LiquidCoolCOM,LiqSerialPort.isOpen());
}
if(!LiqSerialPort.isOpen()) {
return;
}
logger.info("串口{}监听开始",LiquidCoolCOM);
LiqSerialPort.addDataListener(new SerialPortDataListener() {
@Override
publicint getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
}
@Override
publicvoid serialEvent(SerialPortEvent serialPortEvent) {
if(serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE){
//System.out.println(" event_type="+serialPortEvent.getEventType());
logger.info("事件类型:"+serialPortEvent.getEventType());
return;
}
try{
int len = serialPortEvent.getSerialPort().bytesAvailable();
byte bytes[] = new byte[len];
serialPortEvent.getSerialPort().readBytes(bytes, len);
logger.info("串口接收数据回报[{}]={}",len,bytes);
} catch (Exception exp) {
logger.debug("串口异常:"+exp.toString());
}
}
});
}
//串口关闭
public void closeLiqSerialPort() {
if(LiqSerialPort != null && LiqSerialPort.isOpen()) {
LiqSerialPort.removeDataListener();
LiqSerialPort.closePort();
LiqSerialPort = null;
logger.info("串口关闭");
}
}
网友评论