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

77 lines
2.2 KiB
C#
Raw Normal View History

2023-06-13 11:01:01 +00:00
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);
}
2023-07-10 08:34:51 +00:00
catch (Exception e)
2023-06-13 11:01:01 +00:00
{
2023-07-10 08:34:51 +00:00
Console.WriteLine( "Failed to read AcDc data \n"+ e.Message );
// TODO: log
2023-06-13 11:01:01 +00:00
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
}
}
}
}