springboot 與 netty操作串口使用

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() + "回寫失敗");

                }
            }
        });
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章