Fork me on GitEE

使用RXTXcomm操作串口扫码枪工具类并动态加载linux,win的动态链接库

package com.xiyang.demo.entity;

import com.xiyang.demo.enums.BaudRate;
import com.xiyang.demo.enums.SerialNumber;
import gnu.io.SerialPort;
import lombok.Data;
import org.hibernate.validator.internal.util.privilegedactions.NewInstance;

/**
* @Description:
* @Author xiyang
* @Date 2019/10/8
* @Version V1.0
**/

@Data
public class SerialParam {
private SerialNumber serialNumber;
private BaudRate baudRate;
private int checkoutBit;
private int dataBit;
private int stopBit;

public SerialParam() {
}

/**
* @param serialNumber 串口号
* @param baudRate 波特率
*/
public SerialParam(SerialNumber serialNumber, BaudRate baudRate) {
this.serialNumber = serialNumber;
this.baudRate = baudRate;
this.checkoutBit = SerialPort.PARITY_NONE;
this.dataBit = SerialPort.DATABITS_8;
this.stopBit = SerialPort.STOPBITS_1;
}
}
package com.xiyang.demo.enums;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
* @description: 波特率
* @Author: xiyang
* @Date: 2019/10/9 14:51
*/
public enum BaudRate {
/**
* @description: 波特率9600
*/
Baud9600(9600),
/**
* @description: 波特率115200
*/
Baud115200(115200);
int nabaudRate;

private BaudRate(int nabaudRate) {
this.nabaudRate = nabaudRate;
try {
Field fieldName1 = getClass().getSuperclass().getDeclaredField("name");
fieldName1.setAccessible(true);
fieldName1.set(this, String.valueOf(nabaudRate));
fieldName1.setAccessible(false);
} catch (Exception e) {

}
}

}
package com.xiyang.demo.enums;

import java.lang.reflect.Field;

/**
* @description: 串口
* @Author: xiyang
* @Date: 2019/10/9 14:51
*/
public enum SerialNumber {
/**
* @description: COM1口
*/
COM1("COM1"),
/**
* @description: COM2口
*/
COM2("COM2"),
/**
* @description: COM3口
*/
COM3("COM3"),
/**
* @description: COM4口
*/
COM4("COM4"),
/**
* @description: COM5口
*/
COM5("COM5"),
/**
* @description: COM6口
*/
COM6("COM6"),
/**
* @description: COM7口
*/
COM7("COM7"),
/**
* @description: COM8口
*/
COM8("COM8"),
/**
* @description: COM9口
*/
COM9("COM9"),
/**
* @description: COM10口
*/
COM10("COM10"),
/**
* @description: COM11口
*/
COM11("COM11"),
/**
* @description: COM12口
*/
COM12("COM12"),
/**
* @description: COM13口
*/
COM13("COM13"),
/**
* @description: COM14口
*/
COM14("COM14"),
/**
* @description: COM15口
*/
COM15("COM15"),
/**
* @description: COM16口
*/
COM16("COM16");

String serialNumber;

SerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
try {
Field fieldName1 = getClass().getSuperclass().getDeclaredField("name");
fieldName1.setAccessible(true);
fieldName1.set(this, String.valueOf(serialNumber));
fieldName1.setAccessible(false);
} catch (Exception e) {
}
}
}
package com.xiyang.demo.exception;

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.ArrayList;

/**
* @Description:
* @Author xiyang
* @Date 2019/10/8
* @Version V1.0
**/


public class SerialCustomException extends Exception {
public SerialCustomException() {
}

public SerialCustomException(String message) {
super(message);
}
}
package com.xiyang.demo.scanner;

import java.io.*;
import java.util.Properties;

/**
* @Description:
* @Author xiyang
* @Date 2019/10/11
* @Version V1.0
**/


public class loadDLL {
public static void freedDll(String oldfilepath, String newfilepath) {
FileOutputStream FW = null;
FileInputStream FR = null;
try {
FR = new FileInputStream(oldfilepath);
FW = new FileOutputStream(newfilepath);
File file = new File(newfilepath);
byte[] buf = new byte[1024];
int len = -1;
while ((len = FR.read(buf)) != -1) {
FW.write(buf, 0, len);
FW.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (FW != null) {
try {
FW.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (FR != null) {
try {
FW.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

package com.xiyang.demo.scanner;

import com.xiyang.demo.entity.SerialParam;
import com.xiyang.demo.enums.BaudRate;
import com.xiyang.demo.enums.SerialNumber;
import com.xiyang.demo.exception.SerialCustomException;
import gnu.io.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.TooManyListenersException;

/**
* @description:串口参数工具类
* @Author: xiyang
* @Date: 2019/10/8 15:00
*/
public class SerialPortUtil implements SerialPortEventListener {
private CommPortIdentifier commPortId;
private Enumeration<CommPortIdentifier> portList;
private InputStream inputStream;
private OutputStream outputStream;

static {
System.out.println("静态代码块");
Properties props = System.getProperties();
String NewFilePath = System.getProperty("java.io.tmpdir");
String osArch = props.getProperty("os.arch");
String osName = props.getProperty("os.name");
osArch = osArch.replaceAll("\\D", "").trim();
osName = osName.replaceAll("\\d", "").trim();
if ("Windows".equals(osName)) {
if ("64".equals(osArch)) {
loadDLL.freedDll(Class.class.getResource("/rxtx/win-x64/rxtxSerial.dll").getPath(), NewFilePath.concat("\\rxtxSerial.dll"));
System.load(NewFilePath.concat("\\rxtxSerial.dll"));
} else {
loadDLL.freedDll(Class.class.getResource("/rxtx/win-x86/rxtxSerial.dll").getPath(), NewFilePath.concat("\\rxtxSerial.dll"));
System.load(NewFilePath.concat("\\rxtxSerial.dll"));
}
} else {
if ("64".equals(osArch)) {
loadDLL.freedDll(Class.class.getResource("/rxtx/linux-x86_64/librxtxSerial.so").getPath(), NewFilePath.concat("\\librxtxSerial.so"));
loadDLL.freedDll(Class.class.getResource("/rxtx/linux-x86_64/librxtxParallel.so").getPath(), NewFilePath.concat("\\librxtxParallel.so"));
System.load(NewFilePath.concat("\\librxtxSerial.so"));
System.load(NewFilePath.concat("\\librxtxParallel.so"));
} else {
loadDLL.freedDll(Class.class.getResource("/rxtx/linux-i386/librxtxSerial.so").getPath(), NewFilePath.concat("\\librxtxSerial.so"));
loadDLL.freedDll(Class.class.getResource("/rxtx/linux-i386/librxtxParallel.so").getPath(), NewFilePath.concat("\\librxtxParallel.so"));
System.load(NewFilePath);
}

}
}

/**
* @description: 获取串口
* @Author: xiyang
* @Date: 2019/10/8 15:00
*/
public SerialPort getSerialPort(SerialNumber serialNumber, BaudRate baudRate) throws Exception {
SerialParam serialParam = new SerialParam(serialNumber, baudRate);
portList = CommPortIdentifier.getPortIdentifiers();
commPortId = portList.nextElement();
SerialPort serialPort = (SerialPort) commPortId.open(serialParam.getSerialNumber().toString(), 2000);
serialPort.setSerialPortParams(Integer.parseInt(serialParam.getBaudRate().toString()), serialParam.getDataBit(),
serialParam.getStopBit(), serialParam.getCheckoutBit());
return serialPort;
}

/**
* 实现接口SerialPortEventListener中的方法 读取从串口中接收的数据
*/
@Override
public void serialEvent(SerialPortEvent event) {
}

/**
* @description:获取数据
* @Author: xiyang
* @Date: 2019/10/10 16:12
*/
public byte[] getSerialData(SerialPort serialPort) {
String serialData = null;
try {
inputStream = serialPort.getInputStream();
byte[] readBuffer = new byte[inputStream.available()];
int len = 0;
while ((len = inputStream.read(readBuffer)) != -1) {
serialData = new String(readBuffer, 0, len).trim();
inputStream.close();
inputStream = null;
break;
}
} catch (IOException e) {
try {
throw new SerialCustomException("读取串口数据时发生IO异常");
} catch (SerialCustomException ex) {
ex.printStackTrace();
}
}
return serialData.getBytes();
}

/**
* @description:关闭串口
* @Author: xiyang
* @Date: 2019/10/8 15:01
*/
public void closeSerialPort(SerialPort serialPort) throws SerialCustomException {
if (serialPort != null) {
serialPort.notifyOnDataAvailable(false);
serialPort.removeEventListener();
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
throw new SerialCustomException("关闭输入流时发生IO异常");
}
}
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
} catch (IOException e) {
throw new SerialCustomException("关闭输出流时发生IO异常");
}
}
serialPort.close();
serialPort = null;
}
}

/**
* @description: 开启监控
* @Author: xiyang
* @Date: 2019/10/10 16:14
*/
public static void setListenerToSerialPort(SerialPort serialPort, SerialPortEventListener listener) throws SerialCustomException {
try {
serialPort.addEventListener(listener);
//串口有数据监听
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnBreakInterrupt(true);
} catch (TooManyListenersException e) {
throw new SerialCustomException("监听器过多");
}
}

/**
* @description: 发送数据
* @Author: xiyang
* @Date: 2019/10/10 9:25
*/
public void sendData(byte[] data, SerialPort serialPort) {
OutputStream os = null;
try {
//获得串口的输出流
os = serialPort.getOutputStream();
os.write(data);
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.xiyang.demo.scanner;

import com.xiyang.demo.entity.SerialParam;
import com.xiyang.demo.enums.BaudRate;
import com.xiyang.demo.enums.SerialNumber;
import gnu.io.*;

/**
* @Description:
* @Author xiyang
* @Date 2019/10/8
* @Version V1.0
**/
public class ClientExample {
/**
* @description: 串口接受数据示例
* @Author: xiyang
* @Date: 2019/10/12 11:21
*/
public static void main(String[] args) throws Exception {
SerialPortUtil testRxtxUtil = new SerialPortUtil();
//创建串口必要参数接收类并赋值,赋值串口号,波特率初,始化设置,打开串口,开始监听读取串口数据
SerialPort serialPort = testRxtxUtil.getSerialPort(SerialNumber.COM3, BaudRate.Baud115200);
SerialPortUtil.setListenerToSerialPort(serialPort, event -> {
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
byte[] bytes = testRxtxUtil.getSerialData(serialPort);
System.out.println("收到的数据长度:" + bytes.length);
System.out.println("收到的数据:" + new String(bytes));
}
});
//send();
}

/**
* @description: 发送数据示例
* @Author: xiyang
* @Date: 2019/10/12 11:21
*/
public static void send() throws Exception {
SerialPortUtil testRxtxUtil = new SerialPortUtil();
SerialPort serialPort = testRxtxUtil.getSerialPort(SerialNumber.COM3, BaudRate.Baud115200);
for (int i = 0; i < 10; i++) {
Thread.sleep(2000);
testRxtxUtil.sendData("Server".getBytes(), serialPort);
}

}
}
 dll存放在项目下 使用工具类时根据系统动态加载
 

 


 


 
 
 
posted @ 2021-03-26 01:00  问道于盲  阅读(99)  评论(0编辑  收藏  举报