using System;
using System.ComponentModel;
using NewLife.XCoder.Tools.Io;
using NewLife.XCoder.Tools.Modbus;
using Xunit;
namespace XCoder.App.Tests;
/// <summary>I/O 控制与线圈报文测试</summary>
public class IoControlTests
{
private static MbResponse Response(params UInt16[] values) => new(1, MbFunction.ReadCoils, values, false, 0);
[Fact]
[DisplayName("读线圈请求报文包含功能码 01 与点数")]
public void BuildRequest_ReadCoils()
{
var frame = MbFrame.BuildRequest(1, MbFunction.ReadCoils, 0x0010, 8);
Assert.Equal(12, frame.Length);
Assert.Equal(0x01, frame[7]);
Assert.Equal(0x00, frame[8]);
Assert.Equal(0x10, frame[9]);
Assert.Equal(0x00, frame[10]);
Assert.Equal(0x08, frame[11]);
}
[Fact]
[DisplayName("写线圈 0xFF00 表示吸合、0x0000 表示释放")]
public void BuildRequest_WriteCoil()
{
var on = MbFrame.BuildRequest(1, MbFunction.WriteCoil, 5, 0xFF00);
var off = MbFrame.BuildRequest(1, MbFunction.WriteCoil, 5, 0x0000);
Assert.Equal(0x05, on[7]);
Assert.Equal(0xFF, on[10]);
Assert.Equal(0x00, on[11]);
Assert.Equal(0x00, off[10]);
Assert.Equal(0x00, off[11]);
}
[Fact]
[DisplayName("线圈响应按位解析出布尔量")]
public void ParseResponse_ReadCoils()
{
// MBAP(7) + 功能码 + 字节数 1 + 位图 0b00000101
var frame = new Byte[] { 0, 1, 0, 0, 0, 4, 1, 0x01, 1, 0b0000_0101 };
var response = MbFrame.ParseResponse(frame);
Assert.False(response.IsError);
Assert.Equal(8, response.Values.Count);
Assert.Equal(1, response.Values[0]);
Assert.Equal(0, response.Values[1]);
Assert.Equal(1, response.Values[2]);
Assert.Equal(0, response.Values[7]);
}
[Fact]
[DisplayName("异常响应的功能码高位被识别")]
public void ParseResponse_Error()
{
var frame = new Byte[] { 0, 1, 0, 0, 0, 3, 1, 0x81, 0x02 };
var response = MbFrame.ParseResponse(frame);
Assert.True(response.IsError);
Assert.Equal(2, response.ErrorCode);
}
[Fact]
[DisplayName("Decode 按请求点数截断并转换布尔值")]
public void Decode_TruncatesToCount()
{
var response = Response(1, 0, 1, 1, 0, 1);
var bits = IoControlService.Decode(response, 4);
Assert.Equal(4, bits.Length);
Assert.True(bits[0]);
Assert.False(bits[1]);
Assert.True(bits[2]);
Assert.True(bits[3]);
}
[Fact]
[DisplayName("Decode 遇到异常响应抛出异常")]
public void Decode_Error_Throws()
{
var response = new MbResponse(1, MbFunction.ReadCoils, Array.Empty<UInt16>(), true, 3);
Assert.Throws<InvalidOperationException>(() => IoControlService.Decode(response, 4));
}
[Fact]
[DisplayName("Format 与 CountOn 生成状态摘要")]
public void Format_And_CountOn()
{
var bits = new[] { true, false, true, true };
Assert.Equal("1 0 1 1", IoControlService.Format(bits));
Assert.Equal(3, IoControlService.CountOn(bits));
Assert.Equal("", IoControlService.Format(Array.Empty<Boolean>()));
Assert.Equal(0, IoControlService.CountOn(null));
}
}
|