Java使用Netty实现Modbus-RTU通信协议

Modbus

Modbus是一种串行通信协议。Modbus 一个工业上常用的通讯协议、一种通讯约定。Modbus协议包括RTU、ASCII、TCP。其中MODBUS-RTU最常用,比较简单,在单片机上很容易实现。

简单分析Modbus-RTU报文

37 10 00 14 00 0a 14 00 00 00 00 00 00 00 00 00 00 00 00 3f 80 00 00 3f 80 00 00 00 a0(十六进制)
37:从站地址 ,10:功能码,00 14:MODBUS起始地址40021,对应20,14:写入数据字节数,20个,00 a0:crc校验码。其它就是传送的数据。

37 10 00 14 00 0a 14 … 00 a0,中间的数据为功能数据,上面的报文按照两个字节拼接为一个实数,也就是对应float基本数据类型,其中00 00 00 00为一个实数,依次类推,上面的报文有5个实数。解析出来就是0.0、0.0、0.0、1.0、1.0。

4G DTU(ZHC4013)

ZHC4012是一款全网通七模4G DTU,支持2G/3G/4G信号透明传输。支持工业RS232/485等接口,直接连接设备传输。这个硬件是我项目中实践过的,该设备可以通过4G运营商网络与远程服务器进行数据通信。具体操作可以到官网联系客服。设备官网4G DTU(ZHC4013)

项目支持多个4G DTU设备数据上传,支持控制指定4G DTU设备。

Netty的优点

Netty基于epoll的NIO线程模型。NIO整个调用流程就是Java调用了操作系统的内核函数来创建Socket,获取到Socket的文件描述符,创建一个Selector对象,对应操作系统的Epoll描述符,将获取到的Socket连接的文件描述符的事件绑定Selector对应的Epoll文件描述符上,进行事件的异步通知,这样就实现了使用一条线程,并且不需要多的无效的遍历,将事件处理交给了操作系统内核(操作系统中断程序实现),大大提高了效率。

2021年分享过用原生Socket技术实现的服务端代码,其中服务端还是存在一些问题。当时项目运行在生产上,经过几个月的运行,发现服务端监听端口线程不稳定,运行一段时间后,新的客户端就连接不上服务端了。

数据解析相关代码在下面分享的博客中,Netty相关代码是技术上面的实现。

Socket实现的代码:java利用socket通信实现Modbus-RTU通信协议

导入依赖

<dependency>
	<groupId>io.netty</groupId>
	<artifactId>netty-all</artifactId>
	<version>4.1.72.Final</version>
</dependency>

Netty服务端代码

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author linfeng
 * @date 2022/12/26 15:57
 */
public class DtuServer implements Runnable {
    
    

    public static void main(String[] args) {
    
    
        new Thread(new DtuServer()).start();
    }

    @Override
    public void run() {
    
    
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        EventLoopGroup workGroup = new NioEventLoopGroup(10);
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
    
    

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
    
    
                        ch.pipeline().addLast(new IdleStateHandler(15, 0, 0, TimeUnit.MINUTES));
                        ch.pipeline().addLast(new DtuServiceHandler());
                    }

                });
        try {
    
    
            ChannelFuture channelFuture = serverBootstrap.bind(9005).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}

import com.ruoyi.socket.ModBusUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * TODO
 *
 * @author linfeng
 * @date 2022/12/26 15:58
 */
public class DtuServiceHandler extends ChannelInboundHandlerAdapter {
    
    

	// 保存
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	// 保存客户端channelId与注册包信息
    private static Map<String,String> channelIdMap = new ConcurrentHashMap<>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    
    
        Channel channel = ctx.channel();
        ChannelId channelId = channel.id();
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String str = ModBusUtils.bytes2HexString(bytes);
        System.out.println(bytes.length);
        if(bytes.length == 16){
    
    
        	// 注册包长度为16(我这边用到4G DTU(ZHC4013)注册包长度为16,如果有变化需要修改)
        	// 注册包为设备编号,设备编号是唯一的。
            String registerPackage = "";
            for(int i=0;i<bytes.length;i++) {
    
    
                registerPackage=registerPackage+ModBusUtils.byteToASCLL(bytes[i]);
            }
            // channelId.asLongText()获取的是客户端全局唯一ID,根据channelId获取注册包信息,可以判断出数据是哪个节点上传的
            channelIdMap.put(channelId.asLongText(),registerPackage);
            System.out.println("注册包:"+registerPackage);
        }else {
    
    
        	// 从channelIdMap获取注册包(设备编号)
        	String registerPackage = channelIdMap.get(channelId.asLongText());
        	// 获取到客户端注册包,可以根据注册包(设备编号)查询数据库唯一的设备信息。
        	// 数据就不做解析了,数据解析相关代码在上面分享的博客地址中。
        	// 后面就是业务逻辑和数据解析了。
        	/** 如果要服务端向客户端发送信息,可以利用客户端心跳机制发送数据(也可以写发送数据的线程),其中具体业务逻辑就需要利用数据库了。
        		具体思想:首先数据库保存发送状态和发送数据,利用channelIdMap查询注册包,可以通过注册包在数据库中查询相关数据,
        		根据发送状态判断是否需要发送数据。
        		Netty发送数据需要转ByteBuf,具体代码:channel.writeAndFlush(Unpooled.copiedBuffer(new byte[]{1, 2, 3})),
			*/ 
		}
        
        System.out.println("收到的数据:"+str);
        System.out.println("链接数:"+channelGroup.size());
        System.out.println("注册包数:"+channelIdMap.size());
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    
    
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    
    
        Channel channel = ctx.channel();
        ChannelId channelId = channel.id();
        channelIdMap.remove(channelId.asLongText());
        System.out.println(channelId.asLongText()+" channelInactive客户端关闭连接");
        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    
    
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    
    
        // 连接建立
        Channel channel = ctx.channel();
        channelGroup.add(channel);
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    
    
        Channel channel = ctx.channel();
        ChannelId channelId = channel.id();
        channelIdMap.remove(channelId.asLongText());
        System.out.println(channelId.asLongText()+" ChannelHandlerContext客户端关闭连接");
        super.handlerRemoved(ctx);
    }
}
package com.ruoyi.socket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * TODO
 *
 * @author linfeng
 * @date 2022/12/8 16:04
 */
public class ModBusUtils {
    
    

    public static char byteToASCLL(byte b){
    
    
        return (char) b;
    }


    /*
     * 字节数组转16进制字符串
     */
    public static String bytes2HexString(byte[] b) {
    
    
        String r = "";
        for (int i = 0; i < b.length; i++) {
    
    
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
    
    
                hex = '0' + hex;
            }
            r += hex.toUpperCase()+" ";
        }
        return r;
    }

猜你喜欢

转载自blog.csdn.net/qq_40042416/article/details/128457288