Innovenergy_trunk/csharp/Lib/Protocols/Modbus/Slaves/ModbusDevice.cs

53 lines
1.2 KiB
C#

using InnovEnergy.Lib.Protocols.Modbus.Clients;
using InnovEnergy.Lib.Protocols.Modbus.Reflection;
namespace InnovEnergy.Lib.Protocols.Modbus.Slaves;
using Float32 = Single;
using Float64 = Double;
public class ModbusDevice<R> where R : notnull
{
private readonly IReadOnlyList<Batch<R>> _Batches;
public ModbusDevice(ModbusClient modbusClient, Int32 addressOffset = 0)
{
var offset = addressOffset + Record.GetAddressOffset<R>();
_Batches = modbusClient.MakeBatchesFor<R>(offset).ToList();
}
public R Read()
{
R r;
try
{
r = Activator.CreateInstance<R>();
}
catch (Exception e)
{
throw new Exception
(
$"type {typeof(R).Name} seems to lack a parameterless constructor. " +
$"Either create one or use the other overload of{nameof(Read)} instead.",
e
);
}
return Read(r);
}
public R Read(R record)
{
foreach (var batch in _Batches)
batch.Read(record);
return record;
}
public void Write(R record)
{
foreach (var batch in _Batches)
batch.Write(record);
}
}