作者 钟来

修改串口读取方法

... ... @@ -10,6 +10,8 @@ import com.zhonglai.luhui.smart.feeder.dto.commd.FeederCommdDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
... ... @@ -69,16 +71,31 @@ public class SerialPortService implements com.fazecast.jSerialComm.SerialPortDat
@Override
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
try {
// 读取串口数据
byte[] newData = new byte[serialPort.bytesAvailable()];
int numRead = serialPort.readBytes(newData, newData.length);
// try {
// // 读取串口数据
// byte[] newData = new byte[serialPort.bytesAvailable()];
// int numRead = serialPort.readBytes(newData, newData.length);
//
// logger.info("串口返回{}字节数据:{}",numRead, ByteUtil.toHexString(newData));
// FeederCommdDto commdDto = new FeederCommdDto(newData);
// dataQueue.offer(commdDto); // 将数据添加到队列中// 处理串口返回的数据
// } catch (Exception e) {
// logger.error("读取串口数据时出错: " , e);
// }
String data = "";
if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE){
return;//判断事件的类型
}
SerialPort port = event.getSerialPort();
logger.info("串口返回{}字节数据:{}",numRead, ByteUtil.toHexString(newData));
FeederCommdDto commdDto = new FeederCommdDto(newData);
try {
Thread.sleep(500);
byte[] bytes = readFromPort(port);
logger.info("串口返回数据:"+ByteUtil.toHexString(bytes));
FeederCommdDto commdDto = new FeederCommdDto(bytes);
dataQueue.offer(commdDto); // 将数据添加到队列中// 处理串口返回的数据
} catch (Exception e) {
logger.error("读取串口数据时出错: " , e);
logger.error("返回数据处理异常",e);
}
}
}
... ... @@ -159,4 +176,38 @@ public class SerialPortService implements com.fazecast.jSerialComm.SerialPortDat
byte[] bytes = ByteUtil.hexStringToByte(hexStr.replace(" ","").trim().toUpperCase());
return sendByte(bytes);
}
private static byte[] readFromPort(SerialPort serialPort) throws Exception {
InputStream in = null;
byte[] bytes = null;
try {
if (serialPort != null) {
in = serialPort.getInputStream();
} else {
return null;
}
int bufflenth = in.available(); // 获取buffer里的数据长度
while (bufflenth > 0) {
bytes = new byte[bufflenth]; // 初始化byte数组为buffer中数据的长度
in.read(bytes);
bufflenth = in.available();
}
} catch (Exception e) {
throw e;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
throw e;
}
}
return bytes;
}
}
... ...