From 48fe29ef88808eb2fe36ce024d632119ffef2b1e Mon Sep 17 00:00:00 2001 From: ig Date: Mon, 10 Jul 2023 10:38:46 +0200 Subject: [PATCH] add 500ms Timeout to TcpChannel --- .../Trumpf/TruConvertDc/DcDcRecord.Modbus.cs | 8 ----- .../Protocols/Modbus/Channels/TcpChannel.cs | 35 +++++++++++++++++-- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/csharp/Lib/Devices/Trumpf/TruConvertDc/DcDcRecord.Modbus.cs b/csharp/Lib/Devices/Trumpf/TruConvertDc/DcDcRecord.Modbus.cs index 62a8396e2..c58364efb 100644 --- a/csharp/Lib/Devices/Trumpf/TruConvertDc/DcDcRecord.Modbus.cs +++ b/csharp/Lib/Devices/Trumpf/TruConvertDc/DcDcRecord.Modbus.cs @@ -106,11 +106,3 @@ public partial class DcDcRecord // // #endregion IDcDc } - - - - - - - - diff --git a/csharp/Lib/Protocols/Modbus/Channels/TcpChannel.cs b/csharp/Lib/Protocols/Modbus/Channels/TcpChannel.cs index d026cf6cf..4aa3bd71b 100644 --- a/csharp/Lib/Protocols/Modbus/Channels/TcpChannel.cs +++ b/csharp/Lib/Protocols/Modbus/Channels/TcpChannel.cs @@ -6,9 +6,15 @@ namespace InnovEnergy.Lib.Protocols.Modbus.Channels; public class TcpChannel : ConnectionChannel { + private const Int32 TimeoutMs = 500; // TODO: parametrize - public TcpChannel(Ip4Address ip4Address,Boolean closeAfterSuccessfulRead = false, - Boolean closeAfterSuccessfulWrite = false) : this(ip4Address.Host, ip4Address.Port, closeAfterSuccessfulRead, closeAfterSuccessfulWrite) + public TcpChannel(Ip4Address ip4Address, + Boolean closeAfterSuccessfulRead = false, + Boolean closeAfterSuccessfulWrite = false) : + this(ip4Address.Host, + ip4Address.Port, + closeAfterSuccessfulRead, + closeAfterSuccessfulWrite) { } @@ -18,7 +24,30 @@ public class TcpChannel : ConnectionChannel Boolean closeAfterSuccessfulRead = false, Boolean closeAfterSuccessfulWrite = false) : base(closeAfterSuccessfulRead, closeAfterSuccessfulWrite) { - TcpClient Open() => new(hostname, port); + TcpClient Open() + { + var tcpClient = new TcpClient + { + LingerState = new LingerOption(false, 0), + NoDelay = true, + ReceiveTimeout = TimeoutMs, + SendTimeout = TimeoutMs + }; + + var cts = new CancellationTokenSource(); + + var connected = tcpClient + .ConnectAsync(hostname, port, cts.Token) + .AsTask() + .Wait(TimeoutMs); + + if (connected) + return tcpClient; + + cts.Cancel(); + throw new Exception($"Failed to connect to {hostname}:{port}"); + } + _Open = Open; }