diff --git a/TestApp/Program.cs b/TestApp/Program.cs index c3ec0f7..6d00cd5 100644 --- a/TestApp/Program.cs +++ b/TestApp/Program.cs @@ -1,10 +1,50 @@ -namespace TestApp +using NModbus; +using System.Net.Sockets; + +namespace TestApp { internal class Program { static void Main(string[] args) { - Console.WriteLine("Hello, World!"); + 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); + } + } + } + } } \ No newline at end of file diff --git a/TestApp/TestApp.csproj b/TestApp/TestApp.csproj index f02677b..e5cd5bb 100644 --- a/TestApp/TestApp.csproj +++ b/TestApp/TestApp.csproj @@ -7,4 +7,8 @@ enable + + + +