SpringBoot实现通过串口互传数据

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() {
   
        //1、查询可用串口
        List<String> portList = SerialPortManager.getSerialPortList();
        if(!CollectionUtils.isEmpty(portList)){
   
            for (String port : portList) {
   
                //2、自动连接串口
                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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值