具体功能:
执行方式
- 打包jar后执行
- 命令: java -jar ***.jar 串口名 波特率
- 示例: java -jar App.jar COM3 115200
maven依赖
<dependency>
<groupId>com.neuronrobotics</groupId>
<artifactId>nrjavaserial</artifactId>
<version>5.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>3.4.1</version>
</dependency>
程序入口RxtxNRSerialPortApp
public class RxtxNRSerialPortApp {
public static void main(String[] args) {
for (String s : NRSerialPort.getAvailableSerialPorts()) {
System.out.println("Availible port: " + s);
}
if (args.length < 1 || args[0] == null || "".equals(args[0])) {
System.out.println("请输入串口名称!");
System.exit(-101);
}
String port = args[0];
int baudRate = 115200;
if (args.length >= 2 && args[1] != null && !"".equals(args[1])) {
String baudRateStr = args[1];
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(baudRateStr);
if (!isNum.matches()) {
System.out.println("波特率应为整数!");
System.exit(-102);
}
baudRate = Integer.parseInt(baudRateStr);
if (baudRate % 1200 != 0) {
System.out.println("波特率应为1200整倍数!");
System.exit(-102);
}
}
KafkaProducer producer = null;
try {
producer = getProducer();
} catch (Exception e) {
System.out.println("MQ连接失败!");
e.printStackTrace();
System.exit(-202);
}
if (producer == null) {
System.out.println("MQ连接失败!");
System.exit(-202);
}
System.out.println("MQ连接成功....");
RxtxClient rxtxClient = new RxtxClient(port, baudRate, producer);
try {
rxtxClient.start();
} catch (Exception e) {
System.out.println("串口连接失败!");
e.printStackTrace();
rxtxClient.stop();
System.exit(-201);
}
System.out.println("串口"+port+"连接成功....");
rxtxClient.sendMsg("0000");
try {
Thread.sleep(1024);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(rxtxClient.getId() + "设备连接成功");
System.out.print("请输入发送设备" + rxtxClient.getId() + "命令报文:");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String command = scanner.nextLine();
if (command == null || command.isEmpty()) continue;
if ("0".equals(command)) {
rxtxClient.stop();
System.exit(0);
}
rxtxClient.sendMsg(command);
}
}
private static KafkaProducer getProducer() throws Exception {
Properties properties = new Properties();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
properties.put(ProducerConfig.CLIENT_ID_CONFIG, "reflectivity-producer");
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
return producer;
}
}
串口连接程序
public class RxtxClient {
private NRSerialPort serialPort;
private String portName;
private Integer baudRate;
private EquipmentMsgHandler handler;
private KafkaProducer producer;
public RxtxClient(String portName, Integer baudRate, KafkaProducer producer) {
this.portName = portName;
this.baudRate = baudRate;
this.producer = producer;
}
public void start() {
System.out.println("开始启动串口通信:\t" + portName + "\t" + baudRate);
try {
serialPort = new NRSerialPort(portName, baudRate);
boolean isConnected = serialPort.connect();
if (!isConnected) {
System.out.println("串口连接失败!");
System.exit(-201);
}
this.handler = new EquipmentMsgHandler(serialPort.getInputStream(), producer);
this.handler.start();
} catch (Exception e) {
System.out.println("串口连接失败!");
e.printStackTrace();
System.exit(-201);
}
}
public void stop() {
serialPort.disconnect();
producer.close();
}
public void sendMsg(String msg) {
try (DataOutputStream outs = new DataOutputStream(serialPort.getOutputStream())) {
byte[] bytes = new byte[]{};
try {
bytes = hexString2Bytes(msg.trim());
} catch (Exception e) {
System.out.println("请输入16进制命令!");
}
outs.write(bytes);
outs.flush();
} catch (IOException e) {
e.printStackTrace();
serialPort.disconnect();
}
}
public static byte[] hexString2Bytes(String src) {
int l = src.length() / 2;
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
ret[i] = (byte) Integer
.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
}
return ret;
}
public String getId() {
return handler.getId();
}
}
消息处理模块
public class EquipmentMsgHandler extends Thread {
public static final String TOPIC_NAME = "REFLECTIVITY";
public static String HEXE = "0123456789ABCDEF";
private String id;
private InputStream inputStream;
private KafkaProducer producer;
public EquipmentMsgHandler(InputStream inputStream, KafkaProducer producer) {
this.inputStream = inputStream;
this.producer = producer;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public void run() {
try (DataInputStream ins = new DataInputStream(this.inputStream)) {
StringBuffer lsb_tmp = new StringBuffer();
byte[] tmpByte;
while (!Thread.interrupted()) {
if (ins.available() > 0) {
tmpByte = new byte[ins.available()];
ins.read(tmpByte);
for (int i = 0; i < tmpByte.length; i++) {
lsb_tmp.append(HEXE.charAt((tmpByte[i] & 0xF0) >> 4))
.append(HEXE.charAt((tmpByte[i] & 0x0F)));
}
String msg = lsb_tmp.toString();
lsb_tmp.setLength(0);
System.out.println("确认设备报文:" + msg);
if ("00".equals(msg.substring(8, 10))) {
this.id = msg.substring(10, 18);
}
producer.send(new ProducerRecord<String, String>(TOPIC_NAME,msg));
System.out.print("请输入发送设备" + getId() + "命令报文:");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}