Innovenergy_trunk/csharp/Lib/Devices/Trumpf/TruConvertAc/TruConvertAcDcDevices.cs

75 lines
2.1 KiB
C#

using InnovEnergy.Lib.Devices.Trumpf.SystemControl;
using InnovEnergy.Lib.Protocols.Modbus.Channels;
using InnovEnergy.Lib.Protocols.Modbus.Clients;
using InnovEnergy.Lib.Protocols.Modbus.Slaves;
using InnovEnergy.Lib.Utils;
namespace InnovEnergy.Lib.Devices.Trumpf.TruConvertAc;
public class TruConvertAcDcDevices
{
private readonly ModbusDevice<SystemControlRegisters> _SystemControl;
private readonly IEnumerable<ModbusDevice<AcDcRecord>> _AcDcs;
public TruConvertAcDcDevices(String hostname, UInt16 port) : this(new TcpChannel(hostname, port))
{
}
public TruConvertAcDcDevices(Channel transport)
{
var modbusClient = new ModbusTcpClient(transport, 0);
_SystemControl = new ModbusDevice<SystemControlRegisters>(modbusClient);
_AcDcs = Enumerable
.Range(1, Byte.MaxValue - 1)
.Memoize(CreateAcDc);
ModbusDevice<AcDcRecord> CreateAcDc(Int32 i)
{
var mb = new ModbusTcpClient(transport, (Byte)i);
return new ModbusDevice<AcDcRecord>(mb);
}
}
public AcDcDevicesRecord Read()
{
try
{
var scStatus = _SystemControl.Read();
var n = scStatus.NumberOfConnectedSlaves;
var acDcRecords = _AcDcs
.Take(n)
.Select(acDc => acDc.Read())
.ToArray(n);
return new AcDcDevicesRecord(scStatus, acDcRecords);
}
catch
{
return new AcDcDevicesRecord(null, Array.Empty<AcDcRecord>());
}
}
public void Write(AcDcDevicesRecord r)
{
if (r.SystemControl is not null)
_SystemControl.Write(r.SystemControl); // must run BEFORE the attached devices
foreach (var (ctrl, device) in r.Devices.Zip(_AcDcs))
{
try
{
device.Write(ctrl);
}
catch (Exception e)
{
Console.WriteLine(e);
// TODO: log
}
}
}
}