2023-06-13 11:03:36 +00:00
|
|
|
using System.Diagnostics.CodeAnalysis;
|
2023-05-04 07:32:35 +00:00
|
|
|
using InnovEnergy.Lib.Protocols.Modbus.Clients;
|
|
|
|
using InnovEnergy.Lib.Protocols.Modbus.Reflection;
|
2023-06-13 11:03:36 +00:00
|
|
|
using static System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes;
|
2023-05-04 07:32:35 +00:00
|
|
|
|
|
|
|
namespace InnovEnergy.Lib.Protocols.Modbus.Slaves;
|
|
|
|
|
2023-07-07 07:39:03 +00:00
|
|
|
public class ModbusDevice<[DynamicallyAccessedMembers(All)] R> where R : notnull
|
2023-05-04 07:32:35 +00:00
|
|
|
{
|
|
|
|
private readonly IReadOnlyList<Batch<R>> _Batches;
|
|
|
|
|
|
|
|
public ModbusDevice(ModbusClient modbusClient, Int32 addressOffset = 0)
|
|
|
|
{
|
2023-06-13 11:03:36 +00:00
|
|
|
_Batches = modbusClient.MakeBatchesFor<R>(addressOffset);
|
2023-05-04 07:32:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2023-07-07 07:39:03 +00:00
|
|
|
public R Read(R record)
|
2023-05-04 07:32:35 +00:00
|
|
|
{
|
|
|
|
foreach (var batch in _Batches)
|
|
|
|
batch.Read(record);
|
|
|
|
|
|
|
|
return record;
|
|
|
|
}
|
|
|
|
|
2023-07-07 07:39:03 +00:00
|
|
|
public void Write(R record)
|
2023-05-04 07:32:35 +00:00
|
|
|
{
|
|
|
|
foreach (var batch in _Batches)
|
|
|
|
batch.Write(record);
|
|
|
|
}
|
|
|
|
}
|