77 lines
2.2 KiB
C#
77 lines
2.2 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, slaveId: 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 (Exception e)
|
|
{
|
|
Console.WriteLine( "Failed to read AcDc data \n"+ e.Message );
|
|
// TODO: log
|
|
return new AcDcDevicesRecord(null, Array.Empty<AcDcRecord>());
|
|
}
|
|
}
|
|
|
|
public void Write(AcDcDevicesRecord r)
|
|
{
|
|
try
|
|
{
|
|
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))
|
|
{
|
|
device.Write(ctrl);
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine(e);
|
|
// TODO: log
|
|
}
|
|
}
|
|
|
|
} |