130 lines
3.4 KiB
C#
130 lines
3.4 KiB
C#
using NModbus;
|
|
using System.Net.Sockets;
|
|
|
|
namespace TestApp.Driver
|
|
{
|
|
public class VestelEvc04 : IChargerDriver, IDisposable
|
|
{
|
|
private IModbusMaster? _Modbus;
|
|
private bool _Running;
|
|
private Thread _HeartbeatThread;
|
|
|
|
private string _HostAddress = "192.168.178.100";
|
|
public string HostAddress
|
|
{
|
|
get => _HostAddress;
|
|
set
|
|
{
|
|
if (_HostAddress == value) { return; }
|
|
_HostAddress = value;
|
|
Disconnect();
|
|
}
|
|
}
|
|
|
|
private int _Port = 502;
|
|
public int Port
|
|
{
|
|
get => _Port;
|
|
set
|
|
{
|
|
if (_Port == value) { return; }
|
|
_Port = value;
|
|
Disconnect();
|
|
}
|
|
}
|
|
|
|
public VestelEvc04()
|
|
{
|
|
_Running = true;
|
|
_HeartbeatThread = new Thread(HeartbeatLoop);
|
|
_HeartbeatThread.IsBackground = true;
|
|
_HeartbeatThread.Start();
|
|
}
|
|
|
|
private void Connect()
|
|
{
|
|
if (!_Running) { return; }
|
|
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()
|
|
{
|
|
while (_Running)
|
|
{
|
|
try
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
System.Diagnostics.Debug.WriteLine(e.Message);
|
|
Disconnect();
|
|
}
|
|
Thread.Sleep(100);
|
|
}
|
|
}
|
|
|
|
public (double I1, double I2, double I3) GetCurrents()
|
|
{
|
|
if (_Modbus is null)
|
|
{
|
|
Connect();
|
|
}
|
|
if (_Modbus is null) { return (double.NaN, double.NaN, double.NaN); }
|
|
|
|
var i1 = _Modbus.ReadHoldingRegisters(255, 1008, 1)[0];
|
|
var i2 = _Modbus.ReadHoldingRegisters(255, 1010, 1)[0];
|
|
var i3 = _Modbus.ReadHoldingRegisters(255, 1012, 1)[0];
|
|
|
|
return (0.001 * i1, 0.001 * i2, 0.001 * i3);
|
|
}
|
|
|
|
public void SetLoadingCurrent(double value)
|
|
{
|
|
if (!_Running) { return; }
|
|
|
|
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();
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_Running = false;
|
|
Disconnect();
|
|
}
|
|
}
|
|
}
|