// UNCLASSIFIED /*------------------------------------------------------------------------- RAYTHEON PROPRIETARY: THIS DOCUMENT CONTAINS DATA OR INFORMATION PROPRIETARY TO RAYTHEON COMPANY AND IS RESTRICTED TO USE ONLY BY PERSONS AUTHORIZED BY RAYTHEON COMPANY IN WRITING TO USE IT. DISCLOSURE TO UNAUTHORIZED PERSONS WOULD LIKELY CAUSE SUBSTANTIAL COMPETITIVE HARM TO RAYTHEON COMPANY'S BUSINESS POSITION. NEITHER SAID DOCUMENT NOR ITS CONTENTS SHALL BE FURNISHED OR DISCLOSED TO OR COPIED OR USED BY PERSONS OUTSIDE RAYTHEON COMPANY WITHOUT THE EXPRESS WRITTEN APPROVAL OF RAYTHEON COMPANY. THIS PROPRIETARY NOTICE IS NOT APPLICABLE IF DELIVERED TO THE U.S. GOVERNMENT. UNPUBLISHED WORK - COPYRIGHT RAYTHEON COMPANY. -------------------------------------------------------------------------*/ using NLog; using Raytheon.Common; using System; using System.Net; using System.Net.Sockets; namespace Raytheon.Instruments { /// /// Class for controlling a UDP communication device /// public class CommDeviceUdp : ICommDevice, IDisposable { #region PrivateClassMembers private const uint _DEFAULT_SEND_TIMEOUT = 5000; private static readonly object _syncObj = new Object(); private UdpClient _udpClient; private readonly int _localPort; private readonly int _remotePort; private readonly string _remoteAddress; private IPEndPoint _remoteIPEndPoint; private string _name; private readonly SelfTestResult _selfTestResult; private State _state; /// /// NLog logger /// private readonly ILogger _logger; /// /// Raytheon configuration /// private readonly IConfigurationManager _configurationManager; private readonly IConfiguration _configuration; #endregion #region PrivateFunctions /// /// The Finalizer /// ~CommDeviceUdp() { Dispose(false); } /// /// Dispose of the resources contained by this object /// /// protected virtual void Dispose(bool disposing) { if (disposing) { // close the socket and threads try { if (_state == State.Ready) { _udpClient.Close(); _udpClient.Dispose(); _state = State.Uninitialized; } } catch (Exception) { try { } catch (Exception) { //Do not rethrow. Exception from error logger that has already been garbage collected } } } } #endregion #region PublicFuctions /// /// CommDevice factory constructor /// /// /// public CommDeviceUdp(string deviceName, IConfigurationManager configurationManager, ILogger logger) { Name = deviceName; _logger = logger; _configurationManager = configurationManager; _configuration = _configurationManager.GetConfiguration(Name); _localPort = _configuration.GetConfigurationValue("CommDeviceUdp", "LocalPort", 0); _remotePort = _configuration.GetConfigurationValue("CommDeviceUdp", "RemotePort", 0); _remoteAddress = _configuration.GetConfigurationValue("CommDeviceUdp", "RemoteAddress", "127.0.0.1"); // created in Initialize() _udpClient = null; _selfTestResult = SelfTestResult.Unknown; _state = State.Uninitialized; } /// /// /// /// The name of this instance /// the port on the local computer to use /// the port on the remote computer to send to /// the address to send to public CommDeviceUdp(string name, int localPort, int remotePort, string remoteAddress) { _name = name; _localPort = localPort; _remotePort = remotePort; _remoteAddress = remoteAddress; // created in Initialize() _udpClient = null; _selfTestResult = SelfTestResult.Unknown; _state = State.Uninitialized; _logger = LogManager.GetCurrentClassLogger(); } /// /// /// /// public bool ClearErrors() { throw new NotImplementedException(); } /// /// /// public bool DisplayEnabled { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// /// /// public string DetailedStatus { get { return "This is a UDP Device called " + _name; } } /// /// Dispose of the resources contained by this object /// public void Dispose() { try { Dispose(true); GC.SuppressFinalize(this); } catch (Exception) { try { //ErrorLogger.Instance().Write(err.Message + "\r\n" + err.StackTrace); } catch (Exception) { //Do not rethrow. Exception from error logger that has already been garbage collected } } } /// /// /// public bool FrontPanelEnabled { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// /// /// public InstrumentMetadata Info { get { throw new NotImplementedException(); } } /// /// /// public void Initialize() { lock (_syncObj) { if (_state == State.Uninitialized) { _udpClient = new UdpClient(_localPort); _udpClient.Client.ReceiveBufferSize = int.MaxValue; _udpClient.Client.SendBufferSize = int.MaxValue; _udpClient.Client.SendTimeout = (int)_DEFAULT_SEND_TIMEOUT; // set an arbitrary short receive timeout. Don't want the read call to block _udpClient.Client.ReceiveTimeout = 5; IPAddress remoteAddy = IPAddress.Parse(_remoteAddress); _remoteIPEndPoint = new IPEndPoint(remoteAddy, _remotePort); _state = State.Ready; } else { throw new Exception("expected the state to be Uninitialized, state was: " + _state.ToString() + " on device " + _name); } } } /// /// /// public string Name { get { return _name; } set { _name = value; } } /// /// /// /// public SelfTestResult PerformSelfTest() { lock (_syncObj) { throw new NotImplementedException(); } } /// /// Read data from the device. /// /// The buffer to put the data in /// The number of bytes read public uint Read(ref byte[] dataRead) { lock (_syncObj) { try { dataRead = _udpClient.Receive(ref _remoteIPEndPoint); uint numBytesRead = (uint)(dataRead.Length); return numBytesRead; } catch (SocketException e) { if (e.SocketErrorCode == SocketError.TimedOut) { // expected, do nothing return 0; } else { throw; } } } } /// /// public void Reset() { lock (_syncObj) { } } /// /// /// public SelfTestResult SelfTestResult { get { return _selfTestResult; } } /// /// /// public State Status { get { return _state; } } /// /// /// /// public void SetReadTimeout(uint timeoutMs) { lock (_syncObj) { _udpClient.Client.ReceiveTimeout = (int)timeoutMs; } } /// /// /// public void Shutdown() { lock (_syncObj) { if (_state == State.Ready) { _udpClient.Close(); _udpClient.Dispose(); _state = State.Uninitialized; } } } /// /// Write data to the device /// /// The data to write /// The number of bytes to write /// THe number of bytes that were written public uint Write(byte[] dataToSend, uint numBytesToWrite) { lock (_syncObj) { const uint MAX_BYTES_PER_PACKET = 65400; uint index = 0; if (numBytesToWrite > MAX_BYTES_PER_PACKET) { uint numPacketsToSend = numBytesToWrite / MAX_BYTES_PER_PACKET; int packetsSent = 0; while (packetsSent < numPacketsToSend) { Byte[] segment1 = new Byte[MAX_BYTES_PER_PACKET]; Array.Copy(dataToSend, index, segment1, 0, MAX_BYTES_PER_PACKET); uint count = (uint)(_udpClient.Send(segment1, (int)MAX_BYTES_PER_PACKET, _remoteIPEndPoint)); index += count; packetsSent++; } Byte[] segment = new Byte[MAX_BYTES_PER_PACKET]; uint numBytesRemaining = numBytesToWrite - index; Array.Copy(dataToSend, index, segment, 0, numBytesRemaining); index += (uint)(_udpClient.Send(segment, (int)numBytesRemaining, _remoteIPEndPoint)); } else { index = (uint)(_udpClient.Send(dataToSend, (int)numBytesToWrite, _remoteIPEndPoint)); } return index; } } public void Close() { //throw new NotImplementedException(); } public void Open() { //throw new NotImplementedException(); } #endregion } }