当前位置: 首页 > article >正文

SpringBoot项目串口通讯之jSerialComm

目录

  • 1.pom坐标
  • 2.控制层
  • 3.接口
  • 4.实现类-通过串口向设备发数据
  • 5.监听设备通过串口返回数据
  • 6.创建响应结果类ResponseResult

1.pom坐标

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> 
    </parent>
    <groupId>com.example</groupId>
    <artifactId>rxtxcommon</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rxtxcommon</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
         <!--websocket-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>provided</scope>
        </dependency>
        <!--jSerialComm库串口通讯-->
        <dependency>
            <groupId>com.fazecast</groupId>
            <artifactId>jSerialComm</artifactId>
            <version>2.6.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.控制层

import com.fazecast.jSerialComm.SerialPort;
import com.example.rxtxcommon.entity.ResponseResult;
import com.example.rxtxcommon.service.SerialPortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/serial")
public class SerialController {

    @Autowired
    private SerialPortService serialPortService;
    public List<SerialPort> serialPortList;
    public int countsend;
    public int countreceive;

    @GetMapping("/discover")
    public ResponseResult<List<String>> discoverSerialPort() {
        List<SerialPort> list1 = serialPortService.discoverSerialPort();
        List<String> list = new ArrayList<>();
        serialPortList = list1;
        list1.forEach(item -> {
            list.add(item.getSystemPortName());
        });
        ResponseResult<List<String>> response = new ResponseResult<>(list.size() == 0 ? 500 : 1, "", list);
        return response;
    }

    @GetMapping("/open")
    public ResponseResult<Boolean> openSerialPort(SerialPort port1) {
        WebSocketSession session = null;
        for (SerialPort port : serialPortList) {
            if (port.getSystemPortName().equals("COM10")) {
                return serialPortService.openSerialPort(port, session);
            }
        }
        return ResponseResult.getErrorResult("Failed to find port ");
    }

    @GetMapping("/send")
    public String sendData(SerialPort port1, String data) throws IOException {
    //发送数据注意,提前与接收设备沟通好协议,发送什么样类型的数据设备才可以进行响应,否则设备无响应
        for (SerialPort port : serialPortList) {
            if (port.getSystemPortName().equals("COM10")) {
                serialPortService.sendData(port, data);
            }
        }
        return "Data sent>>>" + (countsend++);
    }

    @GetMapping("/close")
    public String closeSerialPort(SerialPort port1) {
        for (SerialPort port : serialPortList) {
            // 遍历串口列表并为每个串口设置参数
            serialPortService.closeSerialPort(port);
        }
        return "Serial port closed";
    }

}

3.接口

import com.fazecast.jSerialComm.SerialPort;
import com.example.rxtxcommon.entity.ResponseResult;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

public interface SerialPortService {
    List<SerialPort> discoverSerialPort();

    boolean closeSerialPort(SerialPort port);

    void sendData(SerialPort port, String data) throws IOException;

    ResponseResult<Boolean> openSerialPort(SerialPort port, WebSocketSession session);
}

4.实现类-通过串口向设备发数据

import com.fazecast.jSerialComm.SerialPort;
import com.example.rxtxcommon.config.DataListener;
import com.example.rxtxcommon.entity.ResponseResult;
import com.example.rxtxcommon.service.SerialPortService;
import com.example.rxtxcommon.utils.ByteUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;


@Service
public class SerialPortServiceImp implements SerialPortService {

    public List<SerialPort> serialPortList;

    @Override
    public List<SerialPort> discoverSerialPort() {
        serialPortList = Arrays.asList(SerialPort.getCommPorts());
        // 遍历串口列表并打印每个串口的名称
        for (SerialPort port : serialPortList) {
            System.out.println("获取串口: " + port.getSystemPortName());
        }
        return serialPortList;
    }

    //关闭串口
    @Override
    public boolean closeSerialPort(SerialPort port) {
        for (SerialPort portItem : serialPortList) {
            if (portItem.getSystemPortName().equals("COM10")) {
                if (portItem != null) {
                    System.out.println("断开端口" + portItem.getSystemPortName() + "连接");
                    return portItem.closePort();
                }
            }
        }
        return false;
    }


    //发送数据到串口
    @Override
    public void sendData(SerialPort port, String data) throws IOException {
        byte[] buffer2 = ByteUtils.hexStr2Byte(data);
        port.writeBytes(buffer2, buffer2.length);
    }

   
    @Override
    public ResponseResult<Boolean> openSerialPort(SerialPort port, WebSocketSession session) {
        if (port.getSystemPortName().equals("COM10")) {
            int baudRate = 2400; // 波特率
            int parity = SerialPort.EVEN_PARITY; // 校验位
            int dataBits = 8; // 数据位
            int stopBits = SerialPort.ONE_STOP_BIT; // 停止位
            if (port.openPort()) {
                try {
                    boolean setComResult = port.setComPortParameters(baudRate, dataBits, stopBits, parity); // 设置参数
                    boolean setComTimes = port.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 20000, 0); // 设置超时
                    if (setComResult && setComTimes) {
                        port.addDataListener(new DataListener(port.getSystemPortName(), session));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ResponseResult.getErrorResult("Failed to open port " + port.getSystemPortName() + e.getMessage().toString());
                }
                System.out.println("COM10 Serial port open 打开");
                return ResponseResult.getSuccessResult("COM10 Serial port open");
            } else {
                return ResponseResult.getErrorResult("Failed to open port " + port.getSystemPortName());
            }
        }
        return ResponseResult.getErrorResult("Failed to find port " + port.getSystemPortName());
    }

}

5.监听设备通过串口返回数据

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.example.rxtxcommon.utils.ByteUtils;
import lombok.SneakyThrows;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

public class DataListener implements SerialPortDataListener {
    private WebSocketSession session;
    private String portName;
	
	//通过websocket打开监听设备的时候绑定session返回给前端数据
    public DataListener(String portName, WebSocketSession session) {
        this.portName = portName;
        this.session = session;
    }

    @Override
    public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_WRITTEN;
    }

    @SneakyThrows
    @Override
    public void serialEvent(SerialPortEvent event) {
        String hexString = "";
        if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_WRITTEN) {
            byte[] newData = new byte[event.getSerialPort().bytesAvailable()];
            int numRead = event.getSerialPort().readBytes(newData, newData.length);
            hexString = ByteUtils.byteArrayToHexString(newData);
        }
        System.out.println("监听接收串口" + portName + ";数据:" + hexString);
        session.sendMessage(new TextMessage(hexString));
    }
}

6.创建响应结果类ResponseResult

import lombok.Data;
import java.io.Serializable;

@Data
public class ResponseResult<T> implements Serializable {
    /**
     * responseCode : 成功默认为1
     */
    public static final int CODE_SUCCESS = 1;

    /**
     * responseCode : 失败默认为500
     */
    public static final int CODE_ERROR = 500;
    private Integer code;
    private String message;
    private T data;
    
    public ResponseResult(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
    public ResponseResult(Integer code, String message) {
        this.code = code;
        this.message = message;
        this.data = data;
   }
    public static <T> ResponseResult<T> getSuccessResult(String message, T data) {
        return new ResponseResult<>(CODE_SUCCESS, message, data);
    }
    public static <T> ResponseResult<T> getSuccessResult(String message) {
        return new ResponseResult<>(CODE_SUCCESS, message);
    }
    public static <T> ResponseResult<T> getErrorResult(String message) {
        return new ResponseResult<>(CODE_ERROR, message);
    }
}

http://www.kler.cn/a/274280.html

相关文章:

  • leetcode之hot100---240搜索二维矩阵II(C++)
  • java全栈day20--Web后端实战(Mybatis基础2)
  • 解决Apache/2.4.39 (Win64) PHP/7.2.18 Server at localhost Port 80问题
  • CCF-GESP 等级考试 2023年9月认证C++一级真题解析
  • 京准电钟:电厂自控NTP时间同步服务器技术方案
  • 常用的缓存技术都有哪些
  • 什么是多模态学习?
  • 代码随想录|Day21|回溯01|77.组合
  • 面试算法-47-有效的括号
  • 基于”Python+”多技术融合在蒸散发与植被总初级生产力估算中的应用教程
  • Unity类银河恶魔城学习记录11-2 p104 Inventoty源代码
  • C++ Qt开发:QUdpSocket网络通信组件
  • Java安全 反序列化(1) URLDNS链原理分析
  • 基于51单片机PT100温度检测LCD1602显示(程序+原理图+PCB+仿真+全套资料)
  • ModbusTCP转Profinet网关高低字节交换切换
  • 接口和抽象类的区别
  • 深入探讨Python中的文件操作与文件IO操作【第141篇—Python实现】
  • 【Swing】Java Swing实现省市区选择编辑器
  • 第四百一十一回
  • Java基础-IO流
  • 详细了解CSS
  • 全国农产品价格分析预测可视化系统设计与实现
  • python Jira库如何修改一个issue的status
  • 差分【Java】
  • 富格林:曝光暗箱细节确保安全
  • PostgreSQL教程(四十四):参考命令(三)之服务器应用