Java 读取串口数据

注意!注意!注意!开箱即用,无需过度的配置,开箱即用,此处用接口调用的方式获取,需要处理为推送的请自行进行数据推送

xml引入依赖包  jSerialComm

<dependency>
    <groupId>com.fazecast</groupId>
    <artifactId>jSerialComm</artifactId>
    <version>2.10.4</version>
</dependency>

创建  SerialPortListener  工具类

package org.example;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 串口监听
 */
@Slf4j
public class SerialPortListener implements SerialPortDataListener {

    private DataAvailableListener mDataAvailableListener;

    public SerialPortListener(DataAvailableListener mDataAvailableListener) {
        this.mDataAvailableListener = mDataAvailableListener;
    }

    @Override
    public int getListeningEvents() {//必须是return这个才会开启串口工具的监听
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
    }

    public void serialEvent(SerialPortEvent serialPortEvent) {
        if (mDataAvailableListener != null) {
            mDataAvailableListener.dataAvailable();
        }
    }
}
创建 SerialPortManager 工具类
package org.example;

import com.fazecast.jSerialComm.SerialPort;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class SerialPortManager {
    //查找所有可用端口
    public static List<String> findPorts() {
        // 获得当前所有可用串口
        SerialPort[] serialPorts = SerialPort.getCommPorts();
        List<String> portNameList = new ArrayList<String>();
        // 将可用串口名添加到List并返回该List
        for (SerialPort serialPort : serialPorts) {
            portNameList.add(serialPort.getSystemPortName());
        }
        //去重
        portNameList = portNameList.stream().distinct().collect(Collectors.toList());
        return portNameList;
    }

    /**
     * 打开串口
     *
     * @param portName 端口名称
     * @param baudRate 波特率
     * @return 串口对象
     */
    public static SerialPort openPort(String portName, Integer baudRate) {
        SerialPort serialPort = SerialPort.getCommPort(portName);
        if (baudRate != null) {
            serialPort.setBaudRate(baudRate);
        }
        //开启串口
        if (!serialPort.isOpen()) {
            serialPort.openPort(1000);
        } else {
            return serialPort;
        }
        // 设置一下串口的波特率等参数
        // 数据位:8
        // 停止位:1
        // 校验位:None
        serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        serialPort.setComPortParameters(baudRate, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);
        return serialPort;
    }


    /**
     * 关闭串口
     *
     * @param serialPort 待关闭的串口对象
     */
    public static void closePort(SerialPort serialPort) {
        if (serialPort != null && serialPort.isOpen()) {
            serialPort.closePort();
        }
    }

    /**
     * 往串口发送数据
     *
     * @param serialPort 串口对象
     * @param content    待发送数据
     */
    public static void sendToPort(SerialPort serialPort, byte[] content) {
        if (!serialPort.isOpen()) {
            return;
        }
        serialPort.writeBytes(content, content.length);
    }

    /**
     * 从串口读取数据
     *
     * @param serialPort 当前已建立连接的SerialPort对象
     * @return 读取到的数据
     */
    public static byte[] readFromPort(SerialPort serialPort) {
        byte[] reslutData = null;
        try {
            if (!serialPort.isOpen()) {
                return null;
            }
            ;
            int i = 0;
            while (serialPort.bytesAvailable() > 0 && i++ < 5) Thread.sleep(20);
            byte[] readBuffer = new byte[serialPort.bytesAvailable()];
            int numRead = serialPort.readBytes(readBuffer, readBuffer.length);
            if (numRead > 0) {
                reslutData = readBuffer;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return reslutData;
    }

    /**
     * 添加监听器
     *
     * @param serialPort 串口对象
     * @param listener   串口存在有效数据监听
     */
    public static void addListener(SerialPort serialPort, DataAvailableListener listener) {
        try {
            // 给串口添加监听器
            serialPort.addDataListener(new SerialPortListener(listener));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

接口 interface  DataAvailableListener 

package org.example;

/**
 * 串口存在有效数据监听
 */
public interface DataAvailableListener {
    /**
     * 串口存在有效数据
     */
    void dataAvailable();
}

 注意最最最重要的一点来了,调用实现

package org.example.controller;

import com.fazecast.jSerialComm.SerialPort;
import org.example.DataAvailableListener;
import org.example.SerialPortManager;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;


@RestController
@RequestMapping("/weight")
@CrossOrigin(origins = "*")
public class WeightController {
    private Integer integerValue = -1;

    /**
     * 获取重量
     */
    @GetMapping("/getWeight")
    public Integer getWeight() {
        return integerValue;
    }

    @PostConstruct
    public void start() {
        SerialPort serialPort = SerialPortManager.openPort("COM1", 9600);
        //给当前串口对象设置监听器
        SerialPortManager.addListener(serialPort, new DataAvailableListener() {
            @Override
            public void dataAvailable() {
                // 当前监听器监听到的串口返回数据 back
                byte[] back = SerialPortManager.readFromPort(serialPort);

                // Convert byte array to string
                String receivedData = new String(back);

                // 使用正则表达式提取数字部分
                java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\+(\\d{6})");
                java.util.regex.Matcher matcher = pattern.matcher(receivedData);
                // 查找匹配项
                if (matcher.find()) {
                    // 提取匹配的数字部分
                    String numericPart = matcher.group(1);

                    // 转换为整数
                    integerValue = Integer.parseInt(numericPart);

                    // 打印整数值
                    System.out.println("Received integer value: " + integerValue);
                } else {
                    System.out.println("No match found in the received data.");
                }
            }
        });
        //当前向串口发送的数据(模拟假数据)
//        byte[] content = new byte[10];
        //向当前串口发送数据
//        SerialPortManager.sendToPort(serialPort,content);
    }

}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java读取串口字符串数据,需要使用Java串口通信API。以下是一个简单的示例代码,演示如何使用Java串口通信API读取串口字符串数据: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Enumeration; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; public class SerialTest { public static void main(String[] args) { // 获所有可用串口 Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { System.out.println("发现可用串口:" + portId.getName()); } } // 打开串口 try { String portName = "/dev/ttyUSB0"; // 更改为你的串口名称 CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); SerialPort serialPort = (SerialPort) portIdentifier.open("SerialTest", 2000); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // 获输入输出流 BufferedReader input = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); OutputStream output = serialPort.getOutputStream(); // 读取串口数据 while (true) { String inputLine = input.readLine(); System.out.println("收到数据:" + inputLine); } } catch (Exception e) { System.err.println(e.toString()); } } } ``` 在以上代码中,我们使用了Java串口通信API中的`CommPortIdentifier`、`SerialPort`、`BufferedReader`和`OutputStream`等类。我们首先获所有可用的串口,然后打开指定的串口,并设置串口参数。接着,我们获输入输出流,使用`BufferedReader`读取串口数据。在读取数据时,我们将其打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值