@@ -18,6 +18,8 @@ public class ModbusReader
1818 private readonly string _host ;
1919 private readonly ushort _port ;
2020
21+ private TcpClient ? _tcpClient ;
22+
2123 private readonly ModbusTcpClient _modbusClient = new ( ) ;
2224 private readonly SemaphoreSlim _modbusLock = new ( 1 ) ;
2325
@@ -34,7 +36,7 @@ public async Task<TDevice> ReadDeviceAsync<TDevice>(byte unit, ushort startRegis
3436 try
3537 {
3638 // Ensure the client is connected
37- if ( ! _modbusClient . IsConnected )
39+ if ( _tcpClient ? . Connected != true )
3840 await ReconnectAsync ( ) ;
3941
4042 _logger . LogDebug (
@@ -101,7 +103,8 @@ public async Task<TDevice> ReadDeviceAsync<TDevice>(byte unit, ushort startRegis
101103 catch
102104 {
103105 // Make sure the connection gets reestablished after a failed read, just in case...
104- _modbusClient . Disconnect ( ) ;
106+ _tcpClient ? . Close ( ) ;
107+ _tcpClient = null ;
105108 throw ;
106109 }
107110
@@ -117,11 +120,14 @@ private async Task ReconnectAsync()
117120 {
118121 _logger . LogInformation ( "Connecting to modbus server at {Host}." , _host ) ;
119122
120- var tcpClient = new TcpClient ( ) ;
121- await tcpClient . ConnectAsync ( _host , _port ) ;
123+ // Close previous TCP client.
124+ _tcpClient ? . Close ( ) ;
125+
126+ _tcpClient = new TcpClient ( ) ;
127+ await _tcpClient . ConnectAsync ( _host , _port ) ;
122128
123129 _modbusClient . ReadTimeout = 5000 ;
124- _modbusClient . Initialize ( tcpClient , ModbusEndianness . LittleEndian ) ;
130+ _modbusClient . Initialize ( _tcpClient , ModbusEndianness . LittleEndian ) ;
125131
126132 _logger . LogInformation ( "Modbus connection to {Host} established." , _host ) ;
127133 }
0 commit comments