|
@@ -0,0 +1,78 @@
|
|
|
+using ModbusSimulationProtocol.Interface;
|
|
|
+using NModbus;
|
|
|
+using System.Net.Sockets;
|
|
|
+
|
|
|
+namespace ModbusSimulationProtocol.Services;
|
|
|
+
|
|
|
+public class ModbusMasterClient : IModbusMasterClient
|
|
|
+{
|
|
|
+ private readonly IModbusLogger? _logger;
|
|
|
+
|
|
|
+ private readonly ModbusFactory _factory;
|
|
|
+ private IModbusMaster? _master = null;
|
|
|
+
|
|
|
+ private bool disposedValue;
|
|
|
+
|
|
|
+ public ModbusMasterClient(IModbusLogger? logger)
|
|
|
+ {
|
|
|
+ _logger = logger;
|
|
|
+
|
|
|
+ _factory = new ModbusFactory();
|
|
|
+ }
|
|
|
+
|
|
|
+ public void Initialize(string ip,ushort port)
|
|
|
+ {
|
|
|
+ ArgumentNullException.ThrowIfNullOrWhiteSpace(ip);
|
|
|
+ if (_master is not null)
|
|
|
+ {
|
|
|
+ WriteLog(LoggingLevel.Information, "The master has been created.");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ try
|
|
|
+ {
|
|
|
+ TcpClient tcpClient = new TcpClient(ip, port);
|
|
|
+ _master = _factory.CreateMaster(tcpClient);
|
|
|
+ }
|
|
|
+ catch (Exception ex)
|
|
|
+ {
|
|
|
+ WriteLog(LoggingLevel.Error, ex.ToString());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ private void WriteLog(LoggingLevel loggingLevel, string log)
|
|
|
+ {
|
|
|
+ _logger?.Log(loggingLevel, $"[{nameof(ModbusMasterClient)}]:{log}");
|
|
|
+ }
|
|
|
+
|
|
|
+ protected virtual void Dispose(bool disposing)
|
|
|
+ {
|
|
|
+ if (!disposedValue)
|
|
|
+ {
|
|
|
+ if (disposing)
|
|
|
+ {
|
|
|
+ // TODO: dispose managed state (managed objects)
|
|
|
+ }
|
|
|
+
|
|
|
+ // TODO: free unmanaged resources (unmanaged objects) and override finalizer
|
|
|
+ // TODO: set large fields to null
|
|
|
+ disposedValue = true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
|
|
|
+ // ~ModbusMasterClient()
|
|
|
+ // {
|
|
|
+ // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
|
|
|
+ // Dispose(disposing: false);
|
|
|
+ // }
|
|
|
+
|
|
|
+ public void Dispose()
|
|
|
+ {
|
|
|
+ // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
|
|
|
+ Dispose(disposing: true);
|
|
|
+ GC.SuppressFinalize(this);
|
|
|
+ }
|
|
|
+}
|