借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
2.42 KiB
XCoder
using System;
using System.ComponentModel;
using NewLife.XCoder.Tools.Modbus;

namespace XCoder.App.Tests;

/// <summary>Modbus 报文与解析测试</summary>
public class ModbusFrameTests
{
    [Fact]
    [DisplayName("读保持寄存器请求报文正确")]
    public void Build_ReadHolding()
    {
        var frame = MbFrame.BuildRequest(1, MbFunction.ReadHolding, 0x006B, 3);

        Assert.Equal(new Byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x6B, 0x00, 0x03 }, frame);
    }

    [Fact]
    [DisplayName("写单个寄存器请求报文正确")]
    public void Build_WriteSingle()
    {
        var frame = MbFrame.BuildRequest(1, MbFunction.WriteSingle, 0x0001, 0x0123);

        Assert.Equal(new Byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x01, 0x06, 0x00, 0x01, 0x01, 0x23 }, frame);
    }

    [Fact]
    [DisplayName("写多个寄存器带字节数与数据")]
    public void Build_WriteMultiple()
    {
        var frame = MbFrame.BuildRequest(1, MbFunction.WriteMultiple, 0x0010, 2, [0x0102, 0x0304]);

        Assert.Equal(0x0B, frame[5]);
        Assert.Equal(new Byte[] { 0x10, 0x00, 0x10, 0x00, 0x02, 0x04, 0x01, 0x02, 0x03, 0x04 },
            frame[7..]);
    }

    [Fact]
    [DisplayName("解析读响应得到寄存器值")]
    public void Parse_ReadResponse()
    {
        var response = MbFrame.ParseResponse(new Byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x01, 0x03, 0x04, 0x00, 0x01, 0x00, 0x02 });

        Assert.False(response.IsError);
        Assert.Equal(MbFunction.ReadHolding, response.Function);
        Assert.Equal(new UInt16[] { 1, 2 }, response.Values);
    }

    [Fact]
    [DisplayName("解析异常响应得到异常码")]
    public void Parse_ErrorResponse()
    {
        var response = MbFrame.ParseResponse(new Byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x01, 0x83, 0x02 });

        Assert.True(response.IsError);
        Assert.Equal(2, response.ErrorCode);
        Assert.Equal(MbFunction.ReadHolding, response.Function);
    }

    [Fact]
    [DisplayName("报文过短抛 ArgumentException")]
    public void Parse_TooShort_Throws()
        => Assert.Throws<ArgumentException>(() => MbFrame.ParseResponse(new Byte[] { 0x00, 0x01 }));

    [Fact]
    [DisplayName("十六进制格式化每字节两位")]
    public void ToHex_Formats()
        => Assert.Equal("00 01 00 00 00 06 01 03 00 6B 00 03",
            MbFrame.ToHex(MbFrame.BuildRequest(1, MbFunction.ReadHolding, 0x006B, 3)));
}