基于Netty实现串口通讯

这个其实在官方示例里面有,我在官方示例的基础上改写了一下,当时本来是Java,被转换成Kotlin搞忘改回来了,大家凑合着看,Kotlin也不难理解:

object RxtxClient {
    // 在外部定义的channel
    lateinit var channel: RxtxChannel

    @Throws(Exception::class)
    @JvmStatic
    fun main(args: Array<String>) {
    	// 这里EventLoopGroup只能用阻塞式的,串口不支持非阻塞的EventLoopGroup
        val group: EventLoopGroup = OioEventLoopGroup()
        try {
            val b = Bootstrap()
            b.group(group)
		            //需要通过Channel工厂来指定返回的channel
                    .channelFactory(object : ChannelFactory<RxtxChannel> {
                        override fun newChannel(): RxtxChannel = channel
                    })
                    .handler(object : ChannelInitializer<RxtxChannel>() {
                        @Throws(Exception::class)
                        public override fun initChannel(ch: RxtxChannel) {
                            ch.pipeline().addLast(
                            		// 以换行符作为切分符
                                    LineBasedFrameDecoder(32768),
                                    StringEncoder(), // 串口发送String
                                    StringDecoder(),
                                    RxtxClientHandler()
                            )
                        }
                    })
            //在这里实现对channel的初始化
            channel = RxtxChannel()
            // 设置channel的基本属性,波特率,数据位,停止位这些
            //with 函数相当于 写了几个channel.config().setBaudrate(9600) .... ,只是不用写前面的channelconfig()
            with(channel.config()) {
                baudrate = 9600 //波特率
                databits = RxtxChannelConfig.Databits.DATABITS_8 //数据位
                paritybit = RxtxChannelConfig.Paritybit.NONE // 校验位
                setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1) // 停止位
            }
            //这里连接串口的名字,一般是“COM1” “COM2”这些
            val future = b.connect(RxtxDeviceAddress("COM1")).sync()

            future.channel().closeFuture().sync()
        } finally {
            group.shutdownGracefully()
        }
    }
}

对应的handler如下

class RxtxClientHandler : SimpleChannelInboundHandler<String>() {
    override fun channelActive(ctx: ChannelHandlerContext) {
        ctx.writeAndFlush("AT\n")
    }
	
    @Throws(Exception::class)
    public override fun channelRead0(ctx: ChannelHandlerContext, msg: String) {
        println(msg)
        ctx.writeAndFlush("AT\n")
    }
}

在网上下载虚拟串口工具,搜索vspd。
image-20200514170211235

添加一个成对的串口,再打开串口调试助手,这里我们选择打开COM2,因为从COM1发送的数据将会由COM2接收

image-20200514185703297

打开程序,会向串口中发送AT,由COM2收到

image-20200514185722346

点击发送下方的发送OK,注意,一定要在对话框中按一下回车再发送,因为我们接收的数据的切分符是\n或者\r\n,所以要换行,netty才能接收到

image-20200514185807592

在Netty的输入框中接收到如下的讯息。成功实现串口数据的采集。有关串口的配置可以参考这篇文档

https://blog.csdn.net/concisefreedom/article/details/67085946

注意安装的版本要选对。x64的windows应该选择rxtx-2.2pre1-bins.zip。下载地址:

http://rxtx.qbang.org/pub/rxtx/

image-20200514185816827

然后选择对应64位的dll文件,放在jdk的bin中,RXTXcomm作为jar包导入到项目文件.

猜你喜欢

转载自blog.csdn.net/qq_41989109/article/details/106123048