這個其實在官方示例裏面有,我在官方示例的基礎上改寫了一下,當時本來是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。
添加一個成對的串口,再打開串口調試助手,這裏我們選擇打開COM2,因爲從COM1發送的數據將會由COM2接收
打開程序,會向串口中發送AT,由COM2收到
點擊發送下方的發送OK,注意,一定要在對話框中按一下回車再發送,因爲我們接收的數據的切分符是\n或者\r\n,所以要換行,netty才能接收到
在Netty的輸入框中接收到如下的訊息。成功實現串口數據的採集。有關串口的配置可以參考這篇文檔
https://blog.csdn.net/concisefreedom/article/details/67085946
注意安裝的版本要選對。x64的windows應該選擇rxtx-2.2pre1-bins.zip。下載地址:
http://rxtx.qbang.org/pub/rxtx/
然後選擇對應64位的dll文件,放在jdk的bin中,RXTXcomm作爲jar包導入到項目文件.