using HslCommunication.ModBus;
|
|
namespace ModBusTcp
|
{
|
public class ModBusTcpController
|
{
|
public string Ip { get; set; }
|
public int Port { get; set; }
|
|
private ModbusTcpNet client;
|
|
public ModBusTcpController(string ip, int port)
|
{
|
Ip = ip;
|
Port = port;
|
}
|
|
public bool Start(out string errMsg)
|
{
|
errMsg = string.Empty;
|
client = new ModbusTcpNet(Ip, Port);
|
var res = client.ConnectServer();
|
errMsg = res.Message;
|
return res.IsSuccess;
|
}
|
|
public bool ReadDIBool(string address, out bool res, out string msg)
|
{
|
var result = client?.ReadBool($"x=2;{address}");
|
msg = result?.Message;
|
res = result?.Content == true;
|
return result?.IsSuccess == true;
|
}
|
|
public bool ReadDOBool(string address, out bool res, out string msg)
|
{
|
var result = client?.ReadBool(address);
|
msg = result?.Message;
|
res = result?.Content == true;
|
return result?.IsSuccess == true;
|
}
|
|
public bool WriteBool(string address, bool value, out string msg)
|
{
|
msg = string.Empty;
|
var res = client?.Write(address, value);
|
msg = res.Message;
|
return res?.IsSuccess == true;
|
}
|
|
public bool ReadDIInt(string address, out int res, out string msg)
|
{
|
var result = client?.ReadInt32($"x=2;{address}");
|
msg = result?.Message;
|
res = result?.Content ?? 0;
|
return result?.IsSuccess == true;
|
}
|
|
public bool ReadDOInt(string address, out int res, out string msg)
|
{
|
var result = client?.ReadInt32(address);
|
msg = result?.Message;
|
res = result?.Content ?? 0;
|
return result?.IsSuccess == true;
|
}
|
|
public bool WriteInt(string address, int value, out string msg)
|
{
|
msg = string.Empty;
|
var res = client?.Write(address, value);
|
msg = res.Message;
|
return res?.IsSuccess == true;
|
}
|
|
public bool Close()
|
{
|
return client?.ConnectClose()?.IsSuccess == true;
|
|
}
|
public void Dispose()
|
{
|
client?.Dispose();
|
}
|
}
|
}
|