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

51 lines
1.3 KiB
C#

using System.Diagnostics.CodeAnalysis;
using InnovEnergy.Lib.Protocols.Modbus.Clients;
using InnovEnergy.Lib.Protocols.Modbus.Reflection;
using static System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes;
namespace InnovEnergy.Lib.Protocols.Modbus.Slaves;
public class ModbusDevice<[DynamicallyAccessedMembers(All)] R> where R : notnull
{
private readonly IReadOnlyList<Batch<R>> _Batches;
public ModbusDevice(ModbusClient modbusClient, Int32 addressOffset = 0)
{
_Batches = modbusClient.MakeBatchesFor<R>(addressOffset);
}
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);
}
}