50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using NModbus;
|
|
using System.Net.Sockets;
|
|
|
|
namespace TestApp
|
|
{
|
|
internal class Program
|
|
{
|
|
static void Main(string[] args)
|
|
{
|
|
while (true)
|
|
{
|
|
try
|
|
{
|
|
ConnectToModBus();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error connecting to ModBus slave: {ex.Message}");
|
|
Thread.Sleep(5000);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void ConnectToModBus()
|
|
{
|
|
var factory = new ModbusFactory();
|
|
var tcpClient = new TcpClient("192.168.188.21", 502);
|
|
var master = factory.CreateMaster(tcpClient);
|
|
Console.WriteLine("ModBus TCP Connection established!");
|
|
|
|
while (tcpClient.Connected)
|
|
{
|
|
try
|
|
{
|
|
ushort input = master.ReadHoldingRegisters(1, 1000, 1)[0];
|
|
ushort output = (ushort)(input + 50);
|
|
master.WriteMultipleRegisters(1, 1100, new ushort[] { output });
|
|
Console.WriteLine($"Register values updated to {input} + 50 = {output}");
|
|
Thread.Sleep(100);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine($"Error updating ModBus registers: {e.Message}");
|
|
Thread.Sleep(1000);
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
} |