62,614
社区成员
发帖
与我相关
我的任务
分享
//发送取数命令的类
String tempmess = "7E44454E0D"; //向前置机取数报文
byte[] bt = Util.hexStringToBytes(tempmess);// 将字符串转换成byte数组
outputStream = CommServer.serialPort.getOutputStream();
outputStream.write(bt);
outputStream.flush();
outputStream.close();
Thread.sleep(800);
String temp = "7E4441430D";//继续取数的报文
byte[] a = Util.hexStringToBytes(tempmess);// 将字符串转换成byte数组
outputStream = CommServer.serialPort.getOutputStream();
outputStream.write(a);
outputStream.flush();
outputStream.close();
//读取数据的类
public void init(String com,int baudrate,int databits,int stopbits,int parity_none) {
try {
System.out.println("进入串口通讯");
portId = CommPortIdentifier.getPortIdentifier(com);
//打开通讯
serialPort = (SerialPort) portId.open("ReadCommApp", 2000);
serialPort.setRTS(false);
//设置各种参数 波特率 数据位 停止位 校验位
//serialPort.setSerialPortParams(baudrate, databits, stopbits, parity_none);
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.setRTS(true);
inputStream = serialPort.getInputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 监听串口
* @param event
*/
public void serialEvent(SerialPortEvent event) {
try{
if (event.getEventType() == event.DATA_AVAILABLE){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StringBuffer str = new StringBuffer();
List data = new ArrayList();
int i;
//读取报文
while((i=inputStream.read()) != -1){
//将报文中的数据字节不足2位的前面补0
if (Integer.toHexString(i).length() < 2) {
System.out.print("0"+Integer.toHexString(i)+" ");
data.add("0" + Integer.toHexString(i));
} else {
System.out.print(Integer.toHexString(i)+" ");
data.add(Integer.toHexString(i));
}
}
}