Netty串口通信RxtxChannel

阅读数:57 评论数:0

跳转到新版页面

分类

python/Java

正文

一、概述

我们常常使用netty的RxtxChannel来实现串口通信,但是netty的作者认为这个Rxtx协议是个老掉牙的东西,没人维护,他们也不知道怎么测试,然后就废弃了这个类,但是并不影响使用。

二、使用示例

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
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 io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;

/**
 * 类功能说明:netty链接串口工具类 <br/>
 */
@Slf4j
public class NettyRxtxClientUtil {
	
	public static RxtxChannel channel;

	public static void createRxtx(String portName, Integer baudrate, Integer thread) throws Exception {
		RxtxChannel rxtxChannel = new RxtxChannel();
        //串口使用阻塞io
        EventLoopGroup group = new OioEventLoopGroup(thread);
        try {
            Bootstrap bootstrap  = new Bootstrap();
            bootstrap.group(group)
                    .channelFactory(() -> {
                        rxtxChannel.config()
                                .setBaudrate(baudrate)
                                .setDatabits(RxtxChannelConfig.Databits.DATABITS_8)
                                .setParitybit(RxtxChannelConfig.Paritybit.NONE)
                                .setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1);
                        return rxtxChannel ;
                    })
                    .handler(new ChannelInitializer<RxtxChannel>() {
                        @Override
                        protected void initChannel(RxtxChannel rxtxChannel) {
                            rxtxChannel.pipeline().addLast(
                            		new NettyRxtxFrameDecoder(),
                                    new StringEncoder(StandardCharsets.UTF_8),
                                    new NettyRxtxDecoderHandler(new SerialportDataReceiveFactory())
                            );
                        }
                    });
            channel = rxtxChannel;
            ChannelFuture f = bootstrap.connect(new RxtxDeviceAddress(portName)).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void start(String portName, Integer baudrate, Integer thread){
        CompletableFuture.runAsync(()->{
            try {
                //阻塞的函数
            	createRxtx(portName, baudrate, thread);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, Executors.newSingleThreadExecutor());//不传默认使用ForkJoinPool,都是守护线程
    }

    /**
     * 发送数据
     * @param bytes
     */
    public static void writeAndFlush(byte[] bytes) {
        if(!channel.isActive()
                || !channel.isOpen()
                || !channel.isWritable()){
            return;
        }
        ByteBuf buffer = channel.alloc().buffer();
        ByteBuf byteBuf = buffer.writeBytes(bytes);
        channel.writeAndFlush(byteBuf).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                log.info("指令下发成功:" + Hex.toHexString(bytes));
            } else {
                log.error("指令下发失败:" + Hex.toHexString(bytes));
            }
        });
    }
}



相关推荐

Java NIO根据操作系统不同,比如macosx是KQueueSelectorProvider、windows有WindowsSelectorProvider、Linux有EPollSelec

Netty提供了丰富的解码器抽象基类:主要分为两类: (1)解码字节到消息(ByteToMessageDecoder和ReplayingDecoder) (2)解码消

一、概述 Netty的强大的地方,是他能方便的实现自定义协议的网络传输。Netty基于Reactor模式:http://1024s.top/mbstudy/mbBlog/blogDetail?blog

netty提供了6种不同的websocket类型: (1)BinaryWebsocketFrame,二进制数据类型 (2)TextWebSocketFrame,文本数

一、概述 在计算机中,我们以字节为单位,一个字节为8bit。 而数据存储中的字节顺序多取决于硬件设计,即所谓的大端存储和小端存储。Intel处理器使用小端存储,PowerPc的处理器采用大端存储。 当

一、Channel的四大类型 1、FileChannel FileChannel是操作文件的Channel,可以通过FileChannel从一个文件中读取数据,也

ByteBuf是对字节的封装,有基于堆内存和直接内存。若是堆内存,应用程序无需考虑什么时候释放,因为GC是帮助做,如果是直接内存,那么需要主动释放。 每个ByteBuf对象都有一个引用计数,当这个数值

Netty中的HashedWheelTimer可以用于提交延迟任务,Java里的Time组件也具备相同的功能,不过Time是基于执行是基于优先队列实现的,相当于需要对所有的任务基于执行的时间排个

一、netty客户端流控 1、这几种情况下,如果客户端没有流控保护,很容易发生内存泄露。 (1)网络瓶颈,当客户端发送速度超过网络链路处理能力,会导致客户端发送队列积压。 (2)当对端读取速度小于已方

LineBasedFrameDecoder以换行符\n或\r\n作为依据,遇到\r\n都认为是一条完整的消息。 而DelimiterBasedFrameDecoder允许我们指定任