草庐IT

IOT云平台 simple(5)springboot netty实现modbus TCP Master

令狐飞侠 2023-07-17 原文

本系列教程包括:
IOT云平台 simple(0)IOT云平台简介
IOT云平台 simple(1)netty入门
IOT云平台 simple(2)springboot入门
IOT云平台 simple(3)springboot netty实现TCP Server
IOT云平台 simple(4)springboot netty实现简单的mqtt broker
IOT云平台 simple(5)springboot netty实现modbus TCP Master
IOT云平台 simple(6)springboot netty实现IOT云平台基本的架构(mqtt、Rabbitmq)

本章首先简单的介绍了modbus,然后利用springboot netty实现了简单的modbus TCP Master。

由于modbus是应答式的交互,这里通过HTTP请求触发springboot netty发送modbus TCP请求,网络调试工具收到请求后发送响应message。

这里:
modbus TCP Master:springboot netty
modbus TCP Slave:网络调试工具
postman:http触发springboot netty主动发送请求;

1 Modbus入门

Modbus在串行链路上分为Slave和Master、
Modbus协议使用的是主从通讯技术,即由主设备主动查询和操作设备。
Modbus Master:主控设备方;
Modbus Slave:从设备方。

Modbus协议有3种模式:
1)RTU
2)ASCII
3)TCP

1.1 Modbus-RTU

基于串口的Modbus-RTU 数据按照标准串口协议进行编码,是使用最广泛的一种Modbus协议,采用CRC-16_Modbus校验算法。

具体协议:

1.2 Modbus-ASCII

基于串口的Modbus-ASCII 所有数据都是ASCII格式,一个字节的原始数据需要两个字符来表示,效率低,采用LRC校验算法。

具体协议:

1.3 Modbus-TCP

基于网口的Modbus-TCP Modbus-TCP基于TCP/IP协议,占用502端口,数据帧主要包括两部分:MBAP(报文头)+PDU(帧结构),数据块与串行链路是一致的。

具体协议:

2 Modbus TCP master集成开发

Modbus TCP是运行在TCP/IP之上的应用层,所以master基本就是个TCP Server。
创建主要的类:
1) TCPServer
server类。
2 )TCPServerChannelInitializer
server channel初始化的类
3)TCPServerStartListener:监听到springboot启动后,启动TCPServer。

TCPServerChannelInitializer中增加了编码解码器。

        socketChannel.pipeline().addLast("decoder", new TCPModbusResDecoder());
        socketChannel.pipeline().addLast("encoder", new TCPModbusReqEncoder());
        socketChannel.pipeline().addLast("tcpModbus", new TCPModbusResHandler());

2.1 定义message

定义message:

public class TCPModbusMessage {
    public MBAPHeader mbapHeader;
    public PduPayload pduPayload;
}

其中header:

public class MBAPHeader {
    //事务处理标识符 递增
    private short transactionId;
    //协议标识符 0x00 标识modbus协议
    private short protocolId;
    //长度,unitId + pdu长度
    private short length;
    //单元标识符,从机地址
    private byte unitId;

    public MBAPHeader(short transactionId, short protocolId, short length, byte unitId) {
        this.transactionId = transactionId;
    }

    public MBAPHeader() {

    }

    public int getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(short transactionId) {
        this.transactionId = transactionId;
    }

    public int getProtocolId() {
        return protocolId;
    }

    public void setProtocolId(short protocolId) {
        this.protocolId = protocolId;
    }

    public int getLength() {
        return length;
    }

    public void setLength(short length) {
        this.length = length;
    }

    public short getUnitId() {
        return unitId;
    }

    public void setUnitId(byte unitId) {
        this.unitId = unitId;
    }

    public String toString() {
        return "transactionId:" + transactionId
                + ",protocolId:" + protocolId
                + ",length:" + length
                + ",unitId:" + unitId;

    }
}

其中pdu消息主体:

public class PduPayload {
    private short functionCode;
    private short dataLength;//数据字节的长度
    private byte[] data;

    public void setFunctionCode(short  code){
        functionCode = code;
    }
    public short getFunctionCode(){
        return functionCode;
    }

    public short getDataLength() {
        return dataLength;
    }

    public void setDataLength(short dataLength) {
        this.dataLength = dataLength;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

}

2.2 定义编码解码

2.2.1 解码

解码定义ByteToMessageDecoder:

public class TCPModbusResDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
        try {
            byteBuf.resetReaderIndex();
            int count = byteBuf.readableBytes();
            log.info("TCPModbusResDecoder decode:" + count);

            ByteBuf byteBuf1 = Unpooled.copiedBuffer(byteBuf);
            TCPModbusByteBufHolder tcpModbusByteBufHolder = new TCPModbusByteBufHolder(byteBuf1);
            list.add(tcpModbusByteBufHolder);

            byteBuf.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

解码定义SimpleChannelInboundHandler:

public class TCPModbusResHandler extends SimpleChannelInboundHandler<TCPModbusByteBufHolder> {
    public static final int HEADER_LENGTH = 8;// // transactionId(2) + protocolId(2) + length(2) + unitId(1)+ functionCode(1)

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelActive");
        Channel channel = ctx.channel();
        log.info("channelActive channelId:" + channel.id().asLongText());
        log.info("channelActive 终端:" + channel.remoteAddress());
        ChannelManager.addChannel(channel.remoteAddress().toString(), channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelInactive");
        Channel channel = ctx.channel();
        ChannelManager.removeChannel(channel.remoteAddress().toString());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TCPModbusByteBufHolder modbusByteBufHolder) {
        log.info("channelRead0");
        int totalLen = modbusByteBufHolder.content().readableBytes();
        log.info("channelRead0:" + totalLen);
        if (totalLen < HEADER_LENGTH) {
            log.info("not modbus TCP protocol:");
            return;
        }
        //header
        MBAPHeader mbapHeader = MBAPHeaderDecoder.decode(modbusByteBufHolder.content());
        log.info("mbapHeader:" + mbapHeader.toString());
        //pdu
        PduPayload pduPayload = new PduPayload();
        short functionCode = modbusByteBufHolder.content().readUnsignedByte();
        pduPayload.setFunctionCode(functionCode);
        log.info("functionCode:" + functionCode);
        int dataLength = 0;
        if (totalLen > HEADER_LENGTH) {
            dataLength = totalLen - HEADER_LENGTH;
        }
        pduPayload.setDataLength((short) dataLength);
        log.info("dataLength:" + dataLength);
        byte[] data = new byte[dataLength];
        modbusByteBufHolder.content().readBytes(data);
        pduPayload.setData(data);

        RecMessageStrategy messageStrategy = RecMessageStrategyManager.getMessageStrategy(functionCode);
        if (messageStrategy != null) {
            messageStrategy.recMessage(channelHandlerContext.channel(), mbapHeader, pduPayload);
        } else {
            log.info("not support function code...");
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("channelReadComplete");
        ctx.flush();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerRemoved");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("exceptionCaught");
        Channel channel = ctx.channel();
        ChannelManager.removeChannel(channel.remoteAddress().toString());
        cause.printStackTrace();
    }
}

这里针对Message接收处理定义了一个策略:

public interface RecMessageStrategy {
    void recMessage(Channel channel, MBAPHeader mbapHeader, PduPayload pduPayload);
}

增加了不同类型消息策略的管理:

public class RecMessageStrategyManager {

    //根据消息类型获取对应的策略类
    public static RecMessageStrategy getMessageStrategy(int functionCode){
        switch (functionCode){
            case FunctionCodeConstants
                    .ReadCoils:
                return new ReadCoilsResMessageStrategy();
            case FunctionCodeConstants
                    .ReadDiscreteInputs:
                return new ReadDiscreteInputsResMessageStrategy();
            case FunctionCodeConstants
                    .ReadHoldingRegisters:
                return new ReadHoldingRegistersResMessageStrategy();
            case FunctionCodeConstants
                    .ReadInputRegisters:
                return new ReadInputRegistersResMessageStrategy();
            case FunctionCodeConstants
                    .WriteSingleCoil:
                return new WriteSingleCoilResMessageStrategy();
            case FunctionCodeConstants
                    .WriteSingleRegister:
                return new WriteSingleRegisterResMessageStrategy();
            case FunctionCodeConstants
                    .WriteMultipleCoils:
                return new WriteMultipleCoilsResMessageStrategy();
            case FunctionCodeConstants
                    .WriteMultipleRegisters:
                return new WriteMultipleRegistersResMessageStrategy();
            default:
                return null;
        }
    }

}

2.2.2 编码

定义编码器:

public class TCPModbusReqEncoder extends MessageToByteEncoder<TCPModbusMessage> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, TCPModbusMessage tcpModbusMessage, ByteBuf byteBuf) throws Exception {
        log.info("-----------TCPModbusReqEncoder encode begin------------");
        //header
        MBAPHeaderEncoder.encode(byteBuf, tcpModbusMessage.mbapHeader);
        log.info("header:"+tcpModbusMessage.mbapHeader.toString());

        //functionCode
        int functionCode = tcpModbusMessage.pduPayload.getFunctionCode();
        log.info("functionCode:"+functionCode);

        SendMessageStrategy sendMessageStrategy = new SendMessageStrategy();
        sendMessageStrategy.sendMessage(byteBuf,tcpModbusMessage.pduPayload);
        log.info("data:"+ ByteUtil.bytesToHexString(tcpModbusMessage.pduPayload.getData()));
        log.info("-----------TCPModbusReqEncoder encode end------------");
    }
}

这里定义了一个message发送的策略:

public class SendMessageStrategy {

    public ByteBuf sendMessage(ByteBuf byteBuf, PduPayload pduPayload) {
        log.info("SendMessageStrategy ");
        byteBuf.writeByte(pduPayload.getFunctionCode());
        byteBuf.writeBytes(pduPayload.getData());
        return byteBuf;
    }
}

3 测试运行

这里通过测试以下功能:
1)读线圈状态(readCoils)
2)读保持寄存器(readHoldingRegisters)
3)写单个线圈(writeSingleCoil)
4)写单个寄存器(writeSingleRegister)

注:这里网络调试工具发送modbus TCP响应message是手动输入模拟的。

3.1 读线圈状态(readCoils)

事务处理标识符(transactionId):1
功能码(functionCode):1
从机地址(unitId):1

第1步:http触发请求:

第2步:springboot netty发送modbus TCP请求:

第3步:网络调试工具收到请求:

第4步:网络调试工具发送modbus TCP响应:

第5步:springboot netty收到响应:

3.2 读保持寄存器(readHoldingRegisters)

事务处理标识符(transactionId):2
功能码(functionCode):3
从机地址(unitId):1

第1步:http触发请求:

第2步:springboot netty发送modbus TCP请求:

第3步:网络调试工具收到请求:

第4步:网络调试工具发送modbus TCP响应:

第5步:springboot netty收到响应:

3.3 写单个线圈(writeSingleCoil)

事务处理标识符(transactionId):3
功能码(functionCode):5
从机地址(unitId):1

第1步:http触发请求:

第2步:springboot netty发送modbus TCP请求:

第3步:网络调试工具收到请求:

第4步:网络调试工具发送modbus TCP响应:

第5步:springboot netty收到响应:

3.4 写单个寄存器(writeSingleRegister)

事务处理标识符(transactionId):4
功能码(functionCode):6
从机地址(unitId):1

第1步:http触发请求:

第2步:springboot netty发送modbus TCP请求:

第3步:网络调试工具收到请求:

第4步:网络调试工具发送modbus TCP响应:

第5步:springboot netty收到响应:

代码详见:
https://gitee.com/linghufeixia/iot-simple
code4

有关IOT云平台 simple(5)springboot netty实现modbus TCP Master的更多相关文章

  1. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  2. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  3. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  4. MIMO-OFDM无线通信技术及MATLAB实现(1)无线信道:传播和衰落 - 2

     MIMO技术的优缺点优点通过下面三个增益来总体概括:阵列增益。阵列增益是指由于接收机通过对接收信号的相干合并而活得的平均SNR的提高。在发射机不知道信道信息的情况下,MIMO系统可以获得的阵列增益与接收天线数成正比复用增益。在采用空间复用方案的MIMO系统中,可以获得复用增益,即信道容量成倍增加。信道容量的增加与min(Nt,Nr)成正比分集增益。在采用空间分集方案的MIMO系统中,可以获得分集增益,即可靠性性能的改善。分集增益用独立衰落支路数来描述,即分集指数。在使用了空时编码的MIMO系统中,由于接收天线或发射天线之间的间距较远,可认为它们各自的大尺度衰落是相互独立的,因此分布式MIMO

  5. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  6. ruby - Arrays Sets 和 SortedSets 在 Ruby 中是如何实现的 - 2

    通常,数组被实现为内存块,集合被实现为HashMap,有序集合被实现为跳跃列表。在Ruby中也是如此吗?我正在尝试从性能和内存占用方面评估Ruby中不同容器的使用情况 最佳答案 数组是Ruby核心库的一部分。每个Ruby实现都有自己的数组实现。Ruby语言规范只规定了Ruby数组的行为,并没有规定任何特定的实现策略。它甚至没有指定任何会强制或至少建议特定实现策略的性能约束。然而,大多数Rubyist对数组的性能特征有一些期望,这会迫使不符合它们的实现变得默默无闻,因为实际上没有人会使用它:插入、前置或追加以及删除元素的最坏情况步骤复

  7. ruby - "public/protected/private"方法是如何实现的,我该如何模拟它? - 2

    在ruby中,你可以这样做:classThingpublicdeff1puts"f1"endprivatedeff2puts"f2"endpublicdeff3puts"f3"endprivatedeff4puts"f4"endend现在f1和f3是公共(public)的,f2和f4是私有(private)的。内部发生了什么,允许您调用一个类方法,然后更改方法定义?我怎样才能实现相同的功能(表面上是创建我自己的java之类的注释)例如...classThingfundeff1puts"hey"endnotfundeff2puts"hey"endendfun和notfun将更改以下函数定

  8. ruby-on-rails - 将 Amazon Simple Notification service SNS 与 ruby​​ 结合使用 - 2

    很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visitthehelpcenter.关闭9年前。我需要从基于ruby​​的应用程序使用AmazonSimpleNotificationService,但不知道从哪里开始。您对从哪里开始有什么建议吗?

  9. ruby - 实现k最近邻需要哪些数据? - 2

    我目前有一个reddit克隆类型的网站。我正在尝试根据我的用户之前喜欢的帖子推荐帖子。看起来K最近邻或k均值是执行此操作的最佳方法。我似乎无法理解如何实际实现它。我看过一些数学公式(例如k表示维基百科页面),但它们对我来说并没有真正意义。有人可以推荐一些伪代码,或者可以查看的地方,以便我更好地了解如何执行此操作吗? 最佳答案 K最近邻(又名KNN)是一种分类算法。基本上,您采用包含N个项目的训练组并对它们进行分类。如何对它们进行分类完全取决于您的数据,以及您认为该数据的重要分类特征是什么。在您的示例中,这可能是帖子类别、谁发布了该项

  10. ruby-on-rails - 使用 Ruby 正确处理 Stripe 错误和异常以实现一次性收费 - 2

    我查看了Stripedocumentationonerrors,但我仍然无法正确处理/重定向这些错误。基本上无论发生什么,我都希望他们返回到edit操作(通过edit_profile_path)并向他们显示一条消息(无论成功与否)。我在edit操作上有一个表单,它可以POST到update操作。使用有效的信用卡可以正常工作(费用在Stripe仪表板中)。我正在使用Stripe.js。classExtrasController5000,#amountincents:currency=>"usd",:card=>token,:description=>current_user.email)

随机推荐