Major upgrade
This commit is contained in:
@@ -30,439 +30,434 @@
|
||||
// DISTRIBUTION/DISSEMINATION CONTROL: F
|
||||
// POC: Alex Kravchenko (1118268)
|
||||
// **********************************************************************************************************
|
||||
using NLog;
|
||||
using Raytheon.Common;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using NLog;
|
||||
using Raytheon.Common;
|
||||
|
||||
namespace Raytheon.Instruments
|
||||
{
|
||||
/// <summary>
|
||||
/// A sim communication device
|
||||
/// </summary>
|
||||
public class CommDeviceUdpAsync : ICommAsync
|
||||
{
|
||||
#region PrivateClassMembers
|
||||
private uint _defaultReadTimeout;
|
||||
private uint _defaultSendTimeout;
|
||||
private uint _defaultReadBufferSize;
|
||||
private static readonly object _syncObj = new object();
|
||||
|
||||
private UdpClient _udpClient;
|
||||
private IPEndPoint _remoteEndPoint;
|
||||
|
||||
private int _localPort;
|
||||
private int _remotePort;
|
||||
private string _remoteAddress;
|
||||
private readonly string _name;
|
||||
private State _state;
|
||||
|
||||
/// <summary>
|
||||
/// NLog logger
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
/// <summary>
|
||||
/// Raytheon configuration
|
||||
/// </summary>
|
||||
private readonly IConfigurationManager _configurationManager;
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
#endregion
|
||||
|
||||
public bool ClearErrors() => false;
|
||||
public bool FrontPanelEnabled { get => false; set => throw new NotImplementedException(); }
|
||||
public bool DisplayEnabled { get => false; set => throw new NotImplementedException(); }
|
||||
public string DetailedStatus => $"This is a TCP/IP Device called {_name}";
|
||||
public InstrumentMetadata Info => throw new NotImplementedException();
|
||||
public State Status => _state;
|
||||
public string Name => _name;
|
||||
public SelfTestResult PerformSelfTest() => SelfTestResult;
|
||||
public SelfTestResult SelfTestResult => SelfTestResult.Unknown;
|
||||
public void Open() => Initialize();
|
||||
public void Close() => Shutdown();
|
||||
public void Reset()
|
||||
{
|
||||
Close();
|
||||
Open();
|
||||
}
|
||||
|
||||
#region Private Functions
|
||||
/// <summary>
|
||||
/// Dispose of the resources contained by this object
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_syncObj)
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
_logger.Error(err.Message + "\r\n" + err.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose of the resources contained by this object
|
||||
/// </summary>
|
||||
/// <param name="disposing"></param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
// close the socket
|
||||
try
|
||||
{
|
||||
Shutdown();
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
_logger.Error(err.Message + "\r\n" + err.StackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Functions
|
||||
|
||||
/// <summary>
|
||||
/// CommDevice factory constructor
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <param name="configurationManager"></param>
|
||||
public CommDeviceUdpAsync(string name, IConfigurationManager configurationManager, ILogger logger)
|
||||
{
|
||||
_name = name;
|
||||
|
||||
_state = State.Uninitialized;
|
||||
|
||||
_logger = logger;
|
||||
|
||||
_configurationManager = configurationManager;
|
||||
_configuration = _configurationManager.GetConfiguration(Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// initialize instrument
|
||||
/// </summary>
|
||||
public void Initialize()
|
||||
{
|
||||
if (_state != State.Uninitialized)
|
||||
{
|
||||
_logger.Warn("Reinitialization of existing UDP Async Connection. Attempting to call Shutdown.");
|
||||
Shutdown();
|
||||
}
|
||||
|
||||
_defaultReadTimeout = _configuration.GetConfigurationValue<uint>("UdpClient", "ReadTimeout", 25);
|
||||
_defaultSendTimeout = _configuration.GetConfigurationValue<uint>("UdpClient", "SendTimeout", 5000);
|
||||
_defaultReadBufferSize = _configuration.GetConfigurationValue<uint>("UdpClient", "BufferSize", 1024);
|
||||
|
||||
_localPort = _configuration.GetConfigurationValue("UdpClient", "LocalPort", 0);
|
||||
|
||||
_remoteAddress = _configuration.GetConfigurationValue("UdpClient", "RemoteAddress", "127.0.0.1");
|
||||
_remotePort = _configuration.GetConfigurationValue("UdpClient", "RemotePort", 0);
|
||||
|
||||
_udpClient = new UdpClient();
|
||||
|
||||
if (string.IsNullOrEmpty(_remoteAddress))
|
||||
{
|
||||
_logger.Debug($"Initializing as UDP Server. Listening on port: {_localPort}");
|
||||
_udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, _localPort));
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Debug($"Initializing as UDP Client. Ready to Talk to: {_remoteAddress}:{_remotePort}");
|
||||
// get the remote endpoint
|
||||
_remoteEndPoint = new IPEndPoint(IPAddress.Parse(_remoteAddress), _remotePort);
|
||||
}
|
||||
|
||||
// set timeouts
|
||||
_udpClient.Client.SendTimeout = (int)_defaultSendTimeout;
|
||||
_udpClient.Client.ReceiveTimeout = (int)_defaultReadTimeout;
|
||||
|
||||
_state = State.Ready;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// shuts down the device
|
||||
/// </summary>
|
||||
public void Shutdown()
|
||||
{
|
||||
_logger.Debug("Shutting Down...");
|
||||
_state = State.Uninitialized;
|
||||
_udpClient?.Dispose();
|
||||
_udpClient = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read data from the device asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="dataRead">The buffer to put the data in</param>
|
||||
/// <returns>The number of bytes read</returns>
|
||||
public async Task<uint> ReadAsync(byte[] dataRead, CancellationToken token = default)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return 0;
|
||||
|
||||
var received = await _udpClient.ReceiveAsync();
|
||||
Array.Copy(received.Buffer, dataRead, Math.Min(dataRead.Length, received.Buffer.Length));
|
||||
|
||||
UpdateRemoteAddressAndPort(received.RemoteEndPoint);
|
||||
|
||||
_logger.Trace($"Reading Data, bytes received: {received.Buffer?.Length}");
|
||||
|
||||
return (uint)received.Buffer.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read string from the device asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="dataRead">The buffer to put the data in</param>
|
||||
/// <returns>The number of bytes read</returns>
|
||||
public async Task<string> ReadAsync(CancellationToken token = default)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return null;
|
||||
|
||||
var received = await _udpClient.ReceiveAsync();
|
||||
|
||||
UpdateRemoteAddressAndPort(received.RemoteEndPoint);
|
||||
|
||||
var data = Encoding.UTF8.GetString(received.Buffer);
|
||||
|
||||
_logger.Trace($"Reading Data, message received: {data}");
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the read timeout
|
||||
/// </summary>
|
||||
/// <param name="timeoutMs"></param>
|
||||
public void SetReadTimeout(uint timeoutMs)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return;
|
||||
|
||||
_logger.Trace($"Setting Reader Timeout: {timeoutMs} Ms");
|
||||
|
||||
_udpClient.Client.ReceiveTimeout = (int)timeoutMs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write data to the device asynchronously
|
||||
/// </summary>
|
||||
/// <param name="dataToSend"></param>
|
||||
/// <param name="numBytesToWrite"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<uint> WriteAsync(byte[] dataToSend, uint numBytesToWrite, CancellationToken token = default)
|
||||
{
|
||||
if (_udpClient == null || _remoteEndPoint == null)
|
||||
return 0;
|
||||
|
||||
_logger.Trace($"Writing message to ({_remoteAddress}:{_remotePort}), bytes: {dataToSend?.Length}");
|
||||
|
||||
_state = State.Busy;
|
||||
await _udpClient.SendAsync(dataToSend, (int)numBytesToWrite, _remoteEndPoint);
|
||||
_state = State.Ready;
|
||||
return numBytesToWrite;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write string data to the device asynchronously
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
public async Task WriteAsync(string message, CancellationToken token = default)
|
||||
{
|
||||
if (_udpClient == null || _remoteEndPoint == null)
|
||||
return;
|
||||
|
||||
_logger.Trace($"Writing message to ({_remoteAddress}:{_remotePort}), message: {message}");
|
||||
|
||||
_state = State.Busy;
|
||||
var dataToSend = Encoding.UTF8.GetBytes(message);
|
||||
await _udpClient.SendAsync(dataToSend, dataToSend.Length, _remoteEndPoint);
|
||||
_state = State.Ready;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send Command and Get Response asynchronously
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <param name="timeoutInMs"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> SendCommandGetResponseAsync(string message, CancellationToken cancellationToken = default, int timeoutInMs = 5000)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return null;
|
||||
|
||||
_logger.Trace($"Sending command waiting for response from ({_remoteAddress}:{_remotePort}), message: {message}");
|
||||
|
||||
using (CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(timeoutInMs)))
|
||||
{
|
||||
if (cancellationToken == default)
|
||||
{
|
||||
cancellationToken = cts.Token;
|
||||
}
|
||||
await WriteAsync(message, cancellationToken);
|
||||
string readResponse = await ReadAsync(cancellationToken);
|
||||
_logger.Trace($"Received response: {readResponse}");
|
||||
|
||||
return readResponse;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send Command and Get Response asynchronously
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <param name="timeoutInMs"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<byte[]> SendCommandGetResponseAsync(byte[] data, CancellationToken cancellationToken = default, int timeoutInMs = 5000)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return null;
|
||||
|
||||
_logger.Trace($"Sending command waiting for response from ({_remoteAddress}:{_remotePort}), message length: {data.Length}");
|
||||
|
||||
using (CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(timeoutInMs)))
|
||||
{
|
||||
if (cancellationToken == default)
|
||||
{
|
||||
cancellationToken = cts.Token;
|
||||
}
|
||||
await WriteAsync(data, (uint)data.Length, cancellationToken);
|
||||
byte[] buffer = new byte[_defaultReadBufferSize];
|
||||
uint bytesRead = await ReadAsync(buffer, cancellationToken);
|
||||
_logger.Trace($"Received response of size: {bytesRead}");
|
||||
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// keeps reading until canceled via token,
|
||||
/// received messages sent to dataReceived function
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <param name="dataReceived"></param>
|
||||
/// <returns></returns>
|
||||
public async Task KeepReadingAsync(CancellationToken cancellationToken, Action<string> dataReceived)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return;
|
||||
|
||||
_logger.Debug($"Starting continuous reading from port: {_localPort} ...");
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
break;
|
||||
|
||||
var received = await ReceiveAsync(_udpClient, cancellationToken);
|
||||
|
||||
if (received != null && received.Buffer != null)
|
||||
{
|
||||
UpdateRemoteAddressAndPort(received.RemoteEndPoint);
|
||||
_logger.Trace($"Incoming Data from {_remoteAddress}:{_remotePort}: size {received.Buffer.Length}");
|
||||
string data = Encoding.UTF8.GetString(received.Buffer, 0, received.Buffer.Length);
|
||||
dataReceived(data);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.Debug($"Finished continuous reading from {_remoteAddress}:{_remotePort} ...");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// keeps reading until canceled via token,
|
||||
/// received messages sent to dataReceived function
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <param name="dataReceived"></param>
|
||||
/// <returns></returns>
|
||||
public async Task KeepReadingAsync(CancellationToken cancellationToken, Action<byte[]> dataReceived)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return;
|
||||
|
||||
_logger.Debug($"Starting continuous reading from port: {_localPort} ...");
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
break;
|
||||
|
||||
var received = await ReceiveAsync(_udpClient, cancellationToken);
|
||||
if (received != null && received.Buffer != null)
|
||||
{
|
||||
UpdateRemoteAddressAndPort(received.RemoteEndPoint);
|
||||
_logger.Trace($"Incoming Data from {_remoteAddress}:{_remotePort}: size {received.Buffer.Length}");
|
||||
dataReceived(received.Buffer);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.Debug($"Finished continuous reading from {_remoteAddress}:{_remotePort} ...");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Functions
|
||||
/// <summary>
|
||||
/// Update client information for logging
|
||||
/// </summary>
|
||||
/// <param name="remoteEndPoint"></param>
|
||||
private void UpdateRemoteAddressAndPort(IPEndPoint remoteEndPoint)
|
||||
{
|
||||
if (remoteEndPoint == null)
|
||||
return;
|
||||
|
||||
if (_remotePort == 0 || string.IsNullOrEmpty(_remoteAddress))
|
||||
{
|
||||
_remotePort = remoteEndPoint.Port;
|
||||
_remoteAddress = remoteEndPoint.Address.ToString();
|
||||
}
|
||||
|
||||
if(_remoteEndPoint == null || _remoteEndPoint.Port != remoteEndPoint.Port )
|
||||
{
|
||||
// get the remote endpoint
|
||||
_remoteEndPoint = remoteEndPoint;
|
||||
|
||||
_logger.Debug($"Starting to receive data from {_remoteAddress}:{_remotePort}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ReceiveAsyc with cancellation token implementation
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="breakToken"></param>
|
||||
/// <returns></returns>
|
||||
private Task<UdpReceiveResult> ReceiveAsync(UdpClient client, CancellationToken breakToken) => breakToken.IsCancellationRequested
|
||||
? Task.Run(() => new UdpReceiveResult())
|
||||
: Task<UdpReceiveResult>.Factory.FromAsync
|
||||
((callback, state) => client.BeginReceive(callback, state), (ar) =>
|
||||
{
|
||||
if (breakToken.IsCancellationRequested)
|
||||
return new UdpReceiveResult();
|
||||
|
||||
IPEndPoint remoteEP = null;
|
||||
var buffer = client.EndReceive(ar, ref remoteEP);
|
||||
return new UdpReceiveResult(buffer, remoteEP);
|
||||
},null);
|
||||
|
||||
#endregion
|
||||
}
|
||||
/// <summary>
|
||||
/// A sim communication device
|
||||
/// </summary>
|
||||
public class CommDeviceUdpAsync : ICommAsync
|
||||
{
|
||||
#region PrivateClassMembers
|
||||
private uint _defaultReadTimeout;
|
||||
private uint _defaultSendTimeout;
|
||||
private uint _defaultReadBufferSize;
|
||||
private static readonly object _syncObj = new object();
|
||||
|
||||
private UdpClient _udpClient;
|
||||
private IPEndPoint _remoteEndPoint;
|
||||
|
||||
private int _localPort;
|
||||
private int _remotePort;
|
||||
private string _remoteAddress;
|
||||
private readonly string _name;
|
||||
private State _state;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly IConfigurationManager _configurationManager;
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
#endregion
|
||||
|
||||
public bool ClearErrors() => false;
|
||||
public bool FrontPanelEnabled { get => false; set => throw new NotImplementedException(); }
|
||||
public bool DisplayEnabled { get => false; set => throw new NotImplementedException(); }
|
||||
public string DetailedStatus => $"This is a TCP/IP Device called {_name}";
|
||||
public InstrumentMetadata Info => throw new NotImplementedException();
|
||||
public State Status => _state;
|
||||
public string Name => _name;
|
||||
public SelfTestResult PerformSelfTest() => SelfTestResult;
|
||||
public SelfTestResult SelfTestResult => SelfTestResult.Unknown;
|
||||
public void Open() => Initialize();
|
||||
public void Close() => Shutdown();
|
||||
public void Reset()
|
||||
{
|
||||
Close();
|
||||
Open();
|
||||
}
|
||||
|
||||
#region Private Functions
|
||||
/// <summary>
|
||||
/// Dispose of the resources contained by this object
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_syncObj)
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
_logger.Error(err.Message + "\r\n" + err.StackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose of the resources contained by this object
|
||||
/// </summary>
|
||||
/// <param name="disposing"></param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
// close the socket
|
||||
try
|
||||
{
|
||||
Shutdown();
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
_logger.Error(err.Message + "\r\n" + err.StackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Functions
|
||||
|
||||
/// <summary>
|
||||
/// CommDevice factory constructor
|
||||
/// </summary>
|
||||
/// <param name="deviceName"></param>
|
||||
/// <param name="configurationManager"></param>
|
||||
public CommDeviceUdpAsync(string deviceName, IConfigurationManager configurationManager)
|
||||
{
|
||||
_name = deviceName;
|
||||
|
||||
_state = State.Uninitialized;
|
||||
|
||||
_logger = LogManager.GetLogger($"{this.GetType().Name} - {deviceName}");
|
||||
|
||||
_configurationManager = configurationManager;
|
||||
_configuration = _configurationManager.GetConfiguration(Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// initialize instrument
|
||||
/// </summary>
|
||||
public void Initialize()
|
||||
{
|
||||
if (_state != State.Uninitialized)
|
||||
{
|
||||
_logger.Warn("Reinitialization of existing UDP Async Connection. Attempting to call Shutdown.");
|
||||
Shutdown();
|
||||
}
|
||||
|
||||
_defaultReadTimeout = _configuration.GetConfigurationValue<uint>("UdpClient", "ReadTimeout", 25);
|
||||
_defaultSendTimeout = _configuration.GetConfigurationValue<uint>("UdpClient", "SendTimeout", 5000);
|
||||
_defaultReadBufferSize = _configuration.GetConfigurationValue<uint>("UdpClient", "BufferSize", 1024);
|
||||
|
||||
_localPort = _configuration.GetConfigurationValue("UdpClient", "LocalPort", 0);
|
||||
|
||||
_remoteAddress = _configuration.GetConfigurationValue("UdpClient", "RemoteAddress", "127.0.0.1");
|
||||
_remotePort = _configuration.GetConfigurationValue("UdpClient", "RemotePort", 0);
|
||||
|
||||
_udpClient = new UdpClient();
|
||||
|
||||
if (string.IsNullOrEmpty(_remoteAddress))
|
||||
{
|
||||
_logger.Debug($"Initializing as UDP Server. Listening on port: {_localPort}");
|
||||
_udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, _localPort));
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Debug($"Initializing as UDP Client. Ready to Talk to: {_remoteAddress}:{_remotePort}");
|
||||
// get the remote endpoint
|
||||
_remoteEndPoint = new IPEndPoint(IPAddress.Parse(_remoteAddress), _remotePort);
|
||||
}
|
||||
|
||||
// set timeouts
|
||||
_udpClient.Client.SendTimeout = (int)_defaultSendTimeout;
|
||||
_udpClient.Client.ReceiveTimeout = (int)_defaultReadTimeout;
|
||||
|
||||
_state = State.Ready;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// shuts down the device
|
||||
/// </summary>
|
||||
public void Shutdown()
|
||||
{
|
||||
_logger.Debug("Shutting Down...");
|
||||
_state = State.Uninitialized;
|
||||
_udpClient?.Dispose();
|
||||
_udpClient = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read data from the device asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="dataRead">The buffer to put the data in</param>
|
||||
/// <returns>The number of bytes read</returns>
|
||||
public async Task<uint> ReadAsync(byte[] dataRead, CancellationToken token = default)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return 0;
|
||||
|
||||
var received = await _udpClient.ReceiveAsync();
|
||||
Array.Copy(received.Buffer, dataRead, Math.Min(dataRead.Length, received.Buffer.Length));
|
||||
|
||||
UpdateRemoteAddressAndPort(received.RemoteEndPoint);
|
||||
|
||||
_logger.Trace($"Reading Data, bytes received: {received.Buffer?.Length}");
|
||||
|
||||
return (uint)received.Buffer.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read string from the device asynchronously.
|
||||
/// </summary>
|
||||
/// <param name="dataRead">The buffer to put the data in</param>
|
||||
/// <returns>The number of bytes read</returns>
|
||||
public async Task<string> ReadAsync(CancellationToken token = default)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return null;
|
||||
|
||||
var received = await _udpClient.ReceiveAsync();
|
||||
|
||||
UpdateRemoteAddressAndPort(received.RemoteEndPoint);
|
||||
|
||||
var data = Encoding.UTF8.GetString(received.Buffer);
|
||||
|
||||
_logger.Trace($"Reading Data, message received: {data}");
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the read timeout
|
||||
/// </summary>
|
||||
/// <param name="timeoutMs"></param>
|
||||
public void SetReadTimeout(uint timeoutMs)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return;
|
||||
|
||||
_logger.Trace($"Setting Reader Timeout: {timeoutMs} Ms");
|
||||
|
||||
_udpClient.Client.ReceiveTimeout = (int)timeoutMs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write data to the device asynchronously
|
||||
/// </summary>
|
||||
/// <param name="dataToSend"></param>
|
||||
/// <param name="numBytesToWrite"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<uint> WriteAsync(byte[] dataToSend, uint numBytesToWrite, CancellationToken token = default)
|
||||
{
|
||||
if (_udpClient == null || _remoteEndPoint == null)
|
||||
return 0;
|
||||
|
||||
_logger.Trace($"Writing message to ({_remoteAddress}:{_remotePort}), bytes: {dataToSend?.Length}");
|
||||
|
||||
_state = State.Busy;
|
||||
await _udpClient.SendAsync(dataToSend, (int)numBytesToWrite, _remoteEndPoint);
|
||||
_state = State.Ready;
|
||||
return numBytesToWrite;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write string data to the device asynchronously
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns></returns>
|
||||
public async Task WriteAsync(string message, CancellationToken token = default)
|
||||
{
|
||||
if (_udpClient == null || _remoteEndPoint == null)
|
||||
return;
|
||||
|
||||
_logger.Trace($"Writing message to ({_remoteAddress}:{_remotePort}), message: {message}");
|
||||
|
||||
_state = State.Busy;
|
||||
var dataToSend = Encoding.UTF8.GetBytes(message);
|
||||
await _udpClient.SendAsync(dataToSend, dataToSend.Length, _remoteEndPoint);
|
||||
_state = State.Ready;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send Command and Get Response asynchronously
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <param name="timeoutInMs"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> SendCommandGetResponseAsync(string message, CancellationToken cancellationToken = default, int timeoutInMs = 5000)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return null;
|
||||
|
||||
_logger.Trace($"Sending command waiting for response from ({_remoteAddress}:{_remotePort}), message: {message}");
|
||||
|
||||
using (CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(timeoutInMs)))
|
||||
{
|
||||
if (cancellationToken == default)
|
||||
{
|
||||
cancellationToken = cts.Token;
|
||||
}
|
||||
await WriteAsync(message, cancellationToken);
|
||||
string readResponse = await ReadAsync(cancellationToken);
|
||||
_logger.Trace($"Received response: {readResponse}");
|
||||
|
||||
return readResponse;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send Command and Get Response asynchronously
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <param name="timeoutInMs"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<byte[]> SendCommandGetResponseAsync(byte[] data, CancellationToken cancellationToken = default, int timeoutInMs = 5000)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return null;
|
||||
|
||||
_logger.Trace($"Sending command waiting for response from ({_remoteAddress}:{_remotePort}), message length: {data.Length}");
|
||||
|
||||
using (CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(timeoutInMs)))
|
||||
{
|
||||
if (cancellationToken == default)
|
||||
{
|
||||
cancellationToken = cts.Token;
|
||||
}
|
||||
await WriteAsync(data, (uint)data.Length, cancellationToken);
|
||||
byte[] buffer = new byte[_defaultReadBufferSize];
|
||||
uint bytesRead = await ReadAsync(buffer, cancellationToken);
|
||||
_logger.Trace($"Received response of size: {bytesRead}");
|
||||
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// keeps reading until canceled via token,
|
||||
/// received messages sent to dataReceived function
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <param name="dataReceived"></param>
|
||||
/// <returns></returns>
|
||||
public async Task KeepReadingAsync(CancellationToken cancellationToken, Action<string> dataReceived)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return;
|
||||
|
||||
_logger.Debug($"Starting continuous reading from port: {_localPort} ...");
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
break;
|
||||
|
||||
var received = await ReceiveAsync(_udpClient, cancellationToken);
|
||||
|
||||
if (received != null && received.Buffer != null)
|
||||
{
|
||||
UpdateRemoteAddressAndPort(received.RemoteEndPoint);
|
||||
_logger.Trace($"Incoming Data from {_remoteAddress}:{_remotePort}: size {received.Buffer.Length}");
|
||||
string data = Encoding.UTF8.GetString(received.Buffer, 0, received.Buffer.Length);
|
||||
dataReceived(data);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.Debug($"Finished continuous reading from {_remoteAddress}:{_remotePort} ...");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// keeps reading until canceled via token,
|
||||
/// received messages sent to dataReceived function
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <param name="dataReceived"></param>
|
||||
/// <returns></returns>
|
||||
public async Task KeepReadingAsync(CancellationToken cancellationToken, Action<byte[]> dataReceived)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
return;
|
||||
|
||||
_logger.Debug($"Starting continuous reading from port: {_localPort} ...");
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
break;
|
||||
|
||||
var received = await ReceiveAsync(_udpClient, cancellationToken);
|
||||
if (received != null && received.Buffer != null)
|
||||
{
|
||||
UpdateRemoteAddressAndPort(received.RemoteEndPoint);
|
||||
_logger.Trace($"Incoming Data from {_remoteAddress}:{_remotePort}: size {received.Buffer.Length}");
|
||||
dataReceived(received.Buffer);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.Debug($"Finished continuous reading from {_remoteAddress}:{_remotePort} ...");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Functions
|
||||
/// <summary>
|
||||
/// Update client information for logging
|
||||
/// </summary>
|
||||
/// <param name="remoteEndPoint"></param>
|
||||
private void UpdateRemoteAddressAndPort(IPEndPoint remoteEndPoint)
|
||||
{
|
||||
if (remoteEndPoint == null)
|
||||
return;
|
||||
|
||||
if (_remotePort == 0 || string.IsNullOrEmpty(_remoteAddress))
|
||||
{
|
||||
_remotePort = remoteEndPoint.Port;
|
||||
_remoteAddress = remoteEndPoint.Address.ToString();
|
||||
}
|
||||
|
||||
if (_remoteEndPoint == null || _remoteEndPoint.Port != remoteEndPoint.Port)
|
||||
{
|
||||
// get the remote endpoint
|
||||
_remoteEndPoint = remoteEndPoint;
|
||||
|
||||
_logger.Debug($"Starting to receive data from {_remoteAddress}:{_remotePort}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ReceiveAsyc with cancellation token implementation
|
||||
/// </summary>
|
||||
/// <param name="client"></param>
|
||||
/// <param name="breakToken"></param>
|
||||
/// <returns></returns>
|
||||
private Task<UdpReceiveResult> ReceiveAsync(UdpClient client, CancellationToken breakToken) => breakToken.IsCancellationRequested
|
||||
? Task.Run(() => new UdpReceiveResult())
|
||||
: Task<UdpReceiveResult>.Factory.FromAsync
|
||||
((callback, state) => client.BeginReceive(callback, state), (ar) =>
|
||||
{
|
||||
if (breakToken.IsCancellationRequested)
|
||||
return new UdpReceiveResult();
|
||||
|
||||
IPEndPoint remoteEP = null;
|
||||
var buffer = client.EndReceive(ar, ref remoteEP);
|
||||
return new UdpReceiveResult(buffer, remoteEP);
|
||||
}, null);
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,71 +30,64 @@
|
||||
// DISTRIBUTION/DISSEMINATION CONTROL: F
|
||||
// POC: Alex Kravchenko (1118268)
|
||||
// **********************************************************************************************************
|
||||
using NLog;
|
||||
using Raytheon.Common;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.Composition;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using NLog;
|
||||
using Raytheon.Common;
|
||||
|
||||
namespace Raytheon.Instruments
|
||||
{
|
||||
[ExportInstrumentFactory(ModelNumber = "CommDeviceUdpAsyncFactory")]
|
||||
public class CommDeviceUdpAsyncFactory : IInstrumentFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// The supported interfaces
|
||||
/// </summary>
|
||||
private readonly List<Type> _supportedInterfaces = new List<Type>();
|
||||
private ILogger _logger;
|
||||
private readonly IConfigurationManager _configurationManager;
|
||||
private const string DefaultConfigPath = @"C:\ProgramData\Raytheon\InstrumentManagerService";
|
||||
private static string DefaultPath;
|
||||
[ExportInstrumentFactory(ModelNumber = "CommDeviceUdpAsyncFactory")]
|
||||
public class CommDeviceUdpAsyncFactory : IInstrumentFactory
|
||||
{
|
||||
private readonly List<Type> _supportedInterfaces = new List<Type>();
|
||||
|
||||
public CommDeviceUdpAsyncFactory(string defaultConfigPath = DefaultConfigPath)
|
||||
: this(null, defaultConfigPath)
|
||||
{
|
||||
}
|
||||
private readonly IConfigurationManager _configurationManager;
|
||||
private const string DefaultConfigPath = @"C:\ProgramData\Raytheon\InstrumentManagerService";
|
||||
private static string DefaultPath;
|
||||
|
||||
/// <summary>
|
||||
/// CommDeviceUdpAsyncFactory injection constructor
|
||||
/// </summary>
|
||||
/// <param name="configManager"></param>
|
||||
/// <param name="simEngine"></param>
|
||||
/// <param name="logger"></param>
|
||||
[ImportingConstructor]
|
||||
public CommDeviceUdpAsyncFactory([Import(AllowDefault = false)] IConfigurationManager configManager,
|
||||
[Import(AllowDefault = true)] string defaultConfigPath = null)
|
||||
{
|
||||
DefaultPath = defaultConfigPath;
|
||||
public CommDeviceUdpAsyncFactory(string defaultConfigPath = DefaultConfigPath)
|
||||
: this(null, defaultConfigPath)
|
||||
{
|
||||
}
|
||||
|
||||
if (LogManager.Configuration == null)
|
||||
{
|
||||
var assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
||||
LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(assemblyFolder + "\\nlog.config");
|
||||
}
|
||||
/// <summary>
|
||||
/// CommDeviceUdpAsyncFactory injection constructor
|
||||
/// </summary>
|
||||
[ImportingConstructor]
|
||||
public CommDeviceUdpAsyncFactory([Import(AllowDefault = false)] IConfigurationManager configManager,
|
||||
[Import(AllowDefault = true)] string defaultConfigPath = null)
|
||||
{
|
||||
DefaultPath = defaultConfigPath;
|
||||
|
||||
_configurationManager = configManager ?? GetConfigurationManager();
|
||||
_supportedInterfaces.Add(typeof(ICommAsync));
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets the instrument
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <returns></returns>
|
||||
public IInstrument GetInstrument(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger = LogManager.GetLogger(name);
|
||||
return new CommDeviceUdpAsync(name, _configurationManager, _logger);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
if (LogManager.Configuration == null)
|
||||
{
|
||||
var assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
||||
LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(assemblyFolder + "\\nlog.config");
|
||||
}
|
||||
|
||||
_configurationManager = configManager ?? GetConfigurationManager();
|
||||
_supportedInterfaces.Add(typeof(ICommAsync));
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets the instrument
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <returns></returns>
|
||||
public IInstrument GetInstrument(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new CommDeviceUdpAsync(name, _configurationManager);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the instrument
|
||||
@@ -105,9 +98,7 @@ namespace Raytheon.Instruments
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger = LogManager.GetLogger(name);
|
||||
|
||||
return new CommDeviceUdpAsync(name, _configurationManager, _logger);
|
||||
return new CommDeviceUdpAsync(name, _configurationManager);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
@@ -120,17 +111,17 @@ namespace Raytheon.Instruments
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public ICollection<Type> GetSupportedInterfaces()
|
||||
{
|
||||
return _supportedInterfaces.ToArray();
|
||||
}
|
||||
{
|
||||
return _supportedInterfaces.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// returns configuration based on the predefined path or default path c:/ProgramData/Raytheon/InstrumentManagerService
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static IConfigurationManager GetConfigurationManager()
|
||||
{
|
||||
return string.IsNullOrEmpty(DefaultPath) ? new RaytheonConfigurationManager() : new RaytheonConfigurationManager(DefaultPath);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// returns configuration based on the predefined path or default path c:/ProgramData/Raytheon/InstrumentManagerService
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static IConfigurationManager GetConfigurationManager()
|
||||
{
|
||||
return string.IsNullOrEmpty(DefaultPath) ? new RaytheonConfigurationManager() : new RaytheonConfigurationManager(DefaultPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user