pom
<!-- 串口连接需要的依赖 -->
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>2.9.2</version>
</dependency>
Controller
import com.example.tcpclient.seralport.SerialPortInstructions;
import com.example.tcpclient.seralport.SerialPortManager;
import com.example.tcpclient.seralport.SerialPortResult;
import com.example.tcpclient.utils.ConvertHexStrAndStrUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/serialPort")
public class SerialPortController {
@GetMapping("/connect")
@ResponseBody
public Boolean connectPorts() {
List<String> portList = SerialPortManager.getSerialPortList();
if(!CollectionUtils.isEmpty(portList)){
for (String port : portList) {
SerialPortManager.connectSerialPort(port);
if(SerialPortResult.SERIAL_PORT_STATE){
return true;
}
}
}
return false;
}
@GetMapping("/disconnect")
@ResponseBody
public Boolean disconnectPorts() {
SerialPortManager.closeSerialPort();
return !SerialPortResult.SERIAL_PORT_STATE;
}
@GetMapping("/sendPortsByLength")
@ResponseBody
public String sendPortsByLength() {
if (SerialPortResult.SERIAL_PORT_STATE){
SerialPortManager.sendSerialPortData(ConvertHexStrAndStrUtils.hexStrToBytes(SerialPortInstructions.READ_NUMBER_ABOVE));
return SerialPortResult.SERIAL_PORT_LENGTH;
}
return "fail";
}
@GetMapping("/sendPortsByOther")
@ResponseBody
public String sendPortsByOther(@RequestParam("hexData") String hexData) {
if (SerialPortResult.SERIAL_PORT_STATE){
SerialPortManager.sendSerialPortData(ConvertHexStrAndStrUtils.hexStrToBytes(hexData));
return SerialPortResult.SERIAL_PORT_RESULT;
}
return "fail";
}
}
SerialPortManager
import com.fazecast.jSerialComm.SerialPort;
import java.util.ArrayList;
import java.util.List;
import java.util.co