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

103 lines
2.7 KiB
C#
Raw Normal View History

2023-02-16 12:57:06 +00:00
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
{
public String Hostname { get; }
public UInt16 Port { get; }
public Byte SlaveAddress { get; }
private ModbusTcpClient? Modbus { get; set; }
2023-02-16 12:57:06 +00:00
public Adam6060Device(String hostname, UInt16 port = 5004, Byte slaveAddress = 2)
{
Hostname = hostname;
Port = port;
SlaveAddress = slaveAddress;
}
private void OpenConnection()
{
if (Modbus is null)
{
var connection = new ModbusTcpConnection(Hostname, Port);
Modbus = new ModbusTcpClient(connection, SlaveAddress);
}
2023-02-16 12:57:06 +00:00
}
public Adam6060Status? ReadStatus()
{
try
{
OpenConnection();
2023-02-16 12:57:06 +00:00
return TryReadStatus();
}
catch
2023-02-16 12:57:06 +00:00
{
CloseConnection();
2023-02-16 12:57:06 +00:00
return null;
}
}
private void CloseConnection()
{
try
{
Modbus?.CloseConnection();
}
catch
{
// ignored
}
Modbus = null;
}
2023-02-16 12:57:06 +00:00
private Adam6060Status TryReadStatus()
{
var inputs = Modbus!.ReadDiscreteInputs(DigitalInputsStartRegister, NbDigitalInputs);
var relays = Modbus!.ReadDiscreteInputs(RelaysStartRegister, NbRelays);
2023-02-16 12:57:06 +00:00
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
{
OpenConnection();
Modbus!.WriteMultipleCoils(RelaysStartRegister, control.Relay0,
control.Relay1,
control.Relay2,
control.Relay3,
control.Relay4,
control.Relay5);
2023-02-16 12:57:06 +00:00
return true;
}
catch
2023-02-16 12:57:06 +00:00
{
CloseConnection();
2023-02-16 12:57:06 +00:00
return false;
}
}
}