Innovenergy_trunk/csharp/Lib/Devices/Adam6060/Adam6060Device.cs

72 lines
2.2 KiB
C#

using InnovEnergy.Lib.Protocols.Modbus.Clients;
using InnovEnergy.Lib.Protocols.Modbus.Connections;
using static InnovEnergy.Lib.Devices.Adam6060.Adam6060Status;
using static InnovEnergy.Lib.Devices.Adam6060.Adam6060Control;
namespace InnovEnergy.Lib.Devices.Adam6060;
public class Adam6060Device
{
private ModbusTcpClient Modbus { get; }
public Adam6060Device(String hostname, UInt16 port = 5004, Byte slaveAddress = 2)
{
var connection = new ModbusTcpConnection(hostname, port);
Modbus = new ModbusTcpClient(connection, slaveAddress);
}
public Adam6060Status? ReadStatus()
{
try
{
return TryReadStatus();
}
catch (Exception)
{
Modbus.CloseConnection();
return null;
}
}
private Adam6060Status TryReadStatus()
{
var inputs = Modbus.ReadDiscreteInputs(DigitalInputsStartRegister, NbDigitalInputs);
var relays = Modbus.ReadDiscreteInputs(RelaysStartRegister, NbRelays);
return new Adam6060Status
{
DigitalInput0 = inputs[0],
DigitalInput1 = inputs[1],
DigitalInput2 = inputs[2],
DigitalInput3 = inputs[3],
DigitalInput4 = inputs[4],
DigitalInput5 = inputs[5],
Relay0 = relays[0],
Relay1 = relays[1],
Relay2 = relays[2],
Relay3 = relays[3],
Relay4 = relays[4],
Relay5 = relays[5],
};
}
public Boolean WriteControl(Adam6060Control control)
{
try
{
Modbus.WriteMultipleCoils(RelaysStartRegister, control.Relay0,
control.Relay1,
control.Relay2,
control.Relay3,
control.Relay4,
control.Relay5);
return true;
}
catch (Exception)
{
Modbus.CloseConnection();
return false;
}
}
}