springboot + mina 实现串口通讯

记一次串口开发,以下代码只能调用本机的串口发送指令。

下载mfz-rxtx-2.2-20081207-win-x64压缩包,将以下三个文件放入指定文件夹内。

Copy RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext
Copy rxtxSerial.dll ---> <JAVA_HOME>\jre\bin
Copy rxtxParallel.dll ---> <JAVA_HOME>\jre\bin

项目中加入依赖

		<!--RXTX实现串口通讯-->
        <dependency>
            <groupId>org.apache.mina</groupId>
            <artifactId>mina-core</artifactId>
            <version>2.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.mina</groupId>
            <artifactId>mina-transport-apr</artifactId>
            <version>2.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.mina</groupId>
            <artifactId>mina-transport-serial</artifactId>
            <version>2.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.bidib.jbidib.org.qbang.rxtx</groupId>
            <artifactId>rxtxcomm</artifactId>
            <version>2.2</version>
        </dependency>

功能实现

    /**
     * 发送指令至串口
     * @param command
     */
    private void sendCommand(String command) {
        if (StringUtils.isNotBlank(command)) {
            IoBuffer buffer = IoBuffer.wrap(command.getBytes());
            IoSession session = null;
            try {
                //创建串口连接
                SerialConnector connector = new SerialConnector();
                //绑定处理handler
                connector.setHandler(new IoHandlerAdapter());
                //设置过滤器
                connector.getFilterChain().addLast("logger", new LoggingFilter());
                //配置串口连接
                SerialAddress address = new SerialAddress(BasicConstants.SERIAL_PORT, BasicConstants.BAUD_RATE, SerialAddress.DataBits.DATABITS_8, SerialAddress.StopBits.BITS_1 , SerialAddress.Parity.NONE, SerialAddress.FlowControl.NONE);
                ConnectFuture future = connector.connect(address);
                future.await();
                session = future.getSession();
                session.write(buffer);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (session != null) {
                    session.close(true);
                }
            }
        }
    }

附:串口调试工具

你可能感兴趣的:(SpringBoot)