Skip to content

Commit

Permalink
Resolve hostnames when connecting to a modbus device
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcusWichelmann committed Jan 27, 2024
1 parent d7fa7ac commit 8f67b86
Showing 1 changed file with 7 additions and 9 deletions.
16 changes: 7 additions & 9 deletions src/EnergyExporter/Modbus/ModbusReader.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -35,7 +35,7 @@ public async Task<TDevice> ReadDeviceAsync<TDevice>(byte unit, ushort startRegis
{
// Ensure the client is connected
if (!_modbusClient.IsConnected)
Reconnect();
await ReconnectAsync();

_logger.LogDebug(
"Reading {Device} at address {StartRegister} from {Host} and unit {Unit}.",
Expand Down Expand Up @@ -113,17 +113,15 @@ public async Task<TDevice> ReadDeviceAsync<TDevice>(byte unit, ushort startRegis
}
}

private void Reconnect()
private async Task ReconnectAsync()
{
_logger.LogInformation("Connecting to modbus server at {Host}.", _host);

if (!IPAddress.TryParse(_host, out IPAddress? address))
throw new ModbusReadException($"Invalid IP address: {_host}");

var endpoint = new IPEndPoint(address, _port);

var tcpClient = new TcpClient();
await tcpClient.ConnectAsync(_host, _port);

_modbusClient.ReadTimeout = 5000;
_modbusClient.Connect(endpoint);
_modbusClient.Initialize(tcpClient, ModbusEndianness.LittleEndian);

_logger.LogInformation("Modbus connection to {Host} established.", _host);
}
Expand Down

0 comments on commit 8f67b86

Please sign in to comment.