串口资料
链接:https://pan.baidu.com/s/1jVO47WF7pCO6kDLezsBZ0g
提取码:hgwn
这段时间遇到了读取串口数据的需求,吭哧吭哧搞了两三天才搞出来,惭愧,所以希望后来的人不要犯我犯过得错误,环境一定要先搭建好,先用串口调试工具去测试,好了再用代码实现。
package com.serial_test.controller;
import com.serial_test.SerialComm;
import com.serial_test.port.BladeWeightUtil;
import com.serial_test.port.EWeightConstant;
import com.serial_test.service.RedisService;
import gnu.io.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;
@RestController
@RequestMapping("/test")
public class TestRedisController {
@Autowired
private RedisService redisService;
private SerialPort serialPort=null;
@RequestMapping(value = "/getBladeWeightRedis", method = RequestMethod.GET)
@ResponseBody
public Integer getBladeWeight(HttpServletRequest request) {
//开启端口
if(serialPort==null){
serialPort = openSerialPort("COM3", 9600);
setListenerToSerialPort(serialPort, new SerialPortEventListener() {
@Override
public void serialEvent(SerialPortEvent serialPortEvent) {
if (serialPortEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { //数据通知
// try {
// Thread.sleep(500);
// } catch (Exception e) {
// e.printStackTrace();
// }
byte[] bytes = SerialComm.readData(serialPort);
System.out.println("收到的数据长度: " + bytes.length);
System.out.println("收到的数据:" + new String(bytes));
redisService.set("COM3", new String(bytes));
}
}
});
}
byte[] bytes = new byte[]{82,78,13,10};
sendData(serialPort, bytes);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
String result = "";
//设置串口的listener
String value = redisService.get("COM3");
System.out.println("=================" + value);
//closeSerialPort(serialPort);
if(!StringUtils.isEmpty(value)){
return Integer.parseInt(value);
}
return 1;
}
/**
* 获得系统可用端口的列表
*
* @return 可用的端口名称列表