springboot 与 netty操作串口使用

3 篇文章 0 订阅
1 篇文章 0 订阅

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() + "回写失败");

                }
            }
        });
    }
}

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值