Innovenergy_trunk/csharp/Lib/Protocols/Modbus/Protocol/Frames/Commands/ReadInputRegistersCommandFr...

56 lines
2.0 KiB
C#
Raw Normal View History

2023-02-16 12:57:06 +00:00
using InnovEnergy.Lib.Protocols.Modbus.Protocol.Frames.Accessors;
using InnovEnergy.Lib.Protocols.Modbus.Protocol.Frames.Replies;
using static InnovEnergy.Lib.Protocols.Modbus.Protocol.Frames.Constants;
using static InnovEnergy.Lib.Protocols.Modbus.Protocol.FunctionCode;
namespace InnovEnergy.Lib.Protocols.Modbus.Protocol.Frames.Commands;
using MbFc = MbByte<FunctionCode>;
internal class ReadInputRegistersCommandFrame : ModbusFrame
{
internal const Int32 Size = 6;
public MbAddress ReadAddress => Data.AddressAt(2);
public MbWord NbToRead => Data.WordAt(4);
public Int32 ExpectedResponseSize => ReadInputRegistersResponseFrame.ExpectedSize(NbToRead);
public ReadInputRegistersCommandFrame(Byte slave, UInt16 readAddress, UInt16 nValues) : base(Size)
{
if (nValues > MaxRegs)
throw new ArgumentOutOfRangeException($"Maximum number of registers ({MaxRegs}) exceeeded!", nameof(nValues));
SlaveAddress.Set(slave);
FunctionCode.Set(ReadInputRegisters);
ReadAddress .Set(readAddress);
NbToRead .Set(nValues);
}
private ReadInputRegistersCommandFrame(ArraySegment<Byte> data) : base(data)
{
if (data.Count != Size)
throw new ArgumentException($"Expecting an array of size {Size}", nameof(data));
AssertFunctionCode(ReadInputRegisters);
}
public ReadInputRegistersResponseFrame VerifyResponse(ReadInputRegistersResponseFrame response)
{
if (response.SlaveAddress != SlaveAddress)
throw new UnexpectedResponseFieldException(nameof(response.SlaveAddress), SlaveAddress.ToString(), response.SlaveAddress);
if (response.RegistersRead.Count != NbToRead)
throw new UnexpectedResponseFieldException(nameof(response.RegistersRead), NbToRead.ToString(), response.RegistersRead.Count);
return response;
}
public static ReadInputRegistersCommandFrame Parse(ArraySegment<Byte> data)
{
return new ReadInputRegistersCommandFrame(data);
}
}