Add VestelEvc04 driver

This commit is contained in:
2023-02-02 12:52:43 +01:00
parent 685e9f9e1d
commit b440594749

View File

@@ -0,0 +1,84 @@
using NModbus;
using System.Net.Sockets;
namespace TestApp.Driver
{
internal class VestelEvc04
{
private IModbusMaster? _Modbus;
private bool _Running;
private Thread _HeartbeatThread;
public string HostAddress { get; set; } = "192.168.178.100";
public int Port { get; set; } = 502;
public VestelEvc04()
{
_Running = true;
_HeartbeatThread = new Thread(HeartbeatLoop);
_HeartbeatThread.IsBackground = true;
_HeartbeatThread.Start();
}
private void Connect()
{
var factory = new ModbusFactory();
var tcpClient = new TcpClient(HostAddress, Port);
_Modbus = factory.CreateMaster(tcpClient);
}
private void Disconnect()
{
if (_Modbus is null) { return; }
_Modbus.Dispose();
_Modbus = null;
}
private void HeartbeatLoop()
{
try
{
while (_Running)
{
if (_Modbus is null)
{
Connect();
}
if (_Modbus is null) { continue; }
var heardbeatValue = _Modbus.ReadHoldingRegisters(255, 6000, 1)[0];
if (heardbeatValue == 0) {
_Modbus.WriteSingleRegister(255, 6000, 1);
}
Thread.Sleep(100);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
Disconnect();
}
}
public void SetLoadingCurrent(double value)
{
try
{
if (_Modbus is null)
{
Connect();
}
if (_Modbus is null) { return; }
ushort registerValue = (ushort)value;
_Modbus.WriteSingleRegister(255, 5004, registerValue);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
Disconnect();
}
}
}
}