springboot 与 netty操作串口使用

导读:本篇文章讲解 springboot 与 netty操作串口使用,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

springboot 与 netty操作串口使用


1.pom添加依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
    
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.36.Final</version>
        </dependency>

没有使用5.*版本,因为它好像弃用了

核心代码

package cn.ljobin.ms.core.util.com.netty.client;

import cn.ljobin.ms.core.util.com.netty.decoder.PacketDecoder;
import cn.ljobin.ms.core.util.com.netty.handler.RxtxHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.rxtx.RxtxChannel;
import io.netty.channel.rxtx.RxtxChannelConfig;
import io.netty.channel.rxtx.RxtxDeviceAddress;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Scanner;

public class Slave {
    public static final String SLAVE_NAME = "comChannel";
    private static final Logger logger = LoggerFactory.getLogger(Slave.class);
    private String portName;
    private int baudrate;
    RxtxChannel channel;
    public List<String> data;
    private ChannelFuture future;
    private OioEventLoopGroup group;
    private Bootstrap b;
    private String uid;

    public RxtxChannel getChannel() {
        return channel;
    }

    public Slave(String portName, int baudrate, List<String> data, String uid) {
        this.portName = portName;
        this.baudrate = baudrate;
        this.data = data;
        this.uid = uid;
    }

    public Slave(String portName, int baudrate, List<String> data) {
        this.data=data;
        this.portName = portName;
        this.baudrate = baudrate;
    }

    public void run(){

        try {
            group = new OioEventLoopGroup();
            b = new Bootstrap();
            b.group(group)
                    .channelFactory(new ChannelFactory<RxtxChannel>() {
                        @Override
                        public RxtxChannel newChannel() {
                            return channel;
                        }
                    })
                    .handler(new ChannelInitializer<RxtxChannel>() {
                        @Override
                        public void initChannel(RxtxChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //固定的长度就是如: A5 5A 01 06 01 03 03 03 00 32 36 C3
                                    //new FixedLengthFrameDecoder(12),
                                    //解码器,自己写的
                                    new PacketDecoder(),
                                    //handler类,处理逻辑
                                    new RxtxHandler(data,uid)
                            );
                        }
                    });

			//就是该类用于串口通讯
            channel = new RxtxChannel();
            //设置波特率
            channel.config().setBaudrate(baudrate);
            //设置数据位
            channel.config().setDatabits(RxtxChannelConfig.Databits.DATABITS_8);
            //设置校验位
            channel.config().setParitybit(RxtxChannelConfig.Paritybit.NONE);
            //设置停止位
            channel.config().setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1);
            //绑定COM口
            future = b.connect(new RxtxDeviceAddress(portName)).sync();
        } catch (InterruptedException e) {
            logger.error("com Run Error:{}",e.getMessage());
            group.shutdownGracefully();
            logger.info("closed com application");
        }
    }

    public void writeAndFlush(String hexString) {
        if(!channel.isActive() || !channel.isOpen()|| !channel.isWritable()){
            return;
        }
        String s = "A55A01C3";
        byte[] bytes = ByteUtil.hexStringToBytes(s);
        ByteBuf buffer = this.channel.alloc().buffer();
        ByteBuf byteBuf = buffer.writeBytes(bytes);
        this.channel.writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                StringBuilder sb = new StringBuilder("");
                if (future.isSuccess()) {
                    System.out.println(sb.toString() + "回写成功");
                } else {
                    System.out.println(sb.toString() + "回写失败");

                }
            }
        });
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/64715.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!