// 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 System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using NLog;
using Raytheon.Common;
namespace Raytheon.Instruments
{
///
/// A class the provides an interface for read/write to registers on an FPGA that implement a custom ascii serial interface
///
public class CommFpgaCustomAsciiSerial : IFpgaComm, IDisposable
{
#region PrivateClassMembers
private SerialPort _serialPort;
private byte[] _readBuf;
private static object _syncObj = new Object();
private uint _delayBeforeReadMs;
private string _readFormat;
private string _writeFormat;
private SelfTestResult _selfTestResult;
private State _state;
private string _name;
private readonly ILogger _logger;
private readonly IConfigurationManager _configurationManager;
private readonly IConfiguration _configuration;
#endregion
#region PrivateFuctions
///
/// The Finalizer
///
~CommFpgaCustomAsciiSerial()
{
Dispose(false);
}
///
/// Reads the serial port until it is empty
///
private void ClearBuffer()
{
lock (_syncObj)
{
bool isClearComplete = false;
while (isClearComplete == false)
{
try
{
int numBytesRead = _serialPort.Read(_readBuf, 0, _readBuf.Length);
if (numBytesRead < _readBuf.Length)
{
isClearComplete = true;
}
}
catch (Exception)
{
//expected if buffer is already cleared
isClearComplete = true;
}
}
}
}
///
/// Dispose of this object
///
///
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_state == State.Ready)
{
_serialPort.Dispose();
_state = State.Uninitialized;
}
}
}
#endregion
#region PublicFuctions
///
/// ELoadScpiKeysight factory constructor
///
///
///
public CommFpgaCustomAsciiSerial(string deviceName, IConfigurationManager configurationManager)
{
Name = deviceName;
_logger = LogManager.GetLogger($"{this.GetType().Name} - {deviceName}");
_configurationManager = configurationManager;
_configuration = _configurationManager.GetConfiguration(Name);
const int READ_BUF_SIZE = 1024;
try
{
_selfTestResult = SelfTestResult.Unknown;
_state = State.Uninitialized;
string comPortName = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "ComPortName", "COM1");
int baudRate = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "BaudRate", 9600);
Parity parity = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "Parity", Parity.None);
int dataBits = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "DataBits", 8);
StopBits stopBits = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "StopBits", StopBits.None);
_serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);
_readFormat = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "ReadFormat", "");
_writeFormat = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "WriteFormat", "");
_serialPort.ReadTimeout = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "ReadTimeout", 100);
_delayBeforeReadMs = _configuration.GetConfigurationValue("CommFpgaCustomAsciiSerial", "DelayBeforeReadMs", 0);
_readBuf = new byte[READ_BUF_SIZE];
//check format of readFormat and writeFormat
if (!_readFormat.Contains(""))
{
throw new Exception("the read format input for card " + _name + " does not contain the tag");
}
if (!_writeFormat.Contains(""))
{
throw new Exception("the write format input for card " + _name + " does not contain the tag");
}
if (!_writeFormat.Contains(""))
{
throw new Exception("the write format input for card " + _name + " does not contain the tag");
}
}
catch (Exception ex)
{
_logger.Error(ex);
if (_serialPort.IsOpen == true)
{
_serialPort.Close();
}
throw;
}
}
///
/// The constructor which opens up a serial port
///
/// The port name. "Com1' for example
/// The num of ms to wait before a read
/// The baud rate
/// The parity
/// Number of data bits
/// Number of Stop Bits
public CommFpgaCustomAsciiSerial(string deviceName, string comPortName, uint delayBeforeReadMs, string readFormat, string writeFormat, int baudRate = 115200, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
{
const int READ_BUF_SIZE = 1024;
_logger = LogManager.GetLogger($"{this.GetType().Name} - {deviceName}");
try
{
_name = deviceName;
_selfTestResult = SelfTestResult.Unknown;
_state = State.Uninitialized;
_serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);
_readFormat = readFormat;
_writeFormat = writeFormat;
_serialPort.ReadTimeout = 100;
_delayBeforeReadMs = delayBeforeReadMs;
_readBuf = new byte[READ_BUF_SIZE];
Array.Clear(_readBuf, 0, _readBuf.Length);
//check format of readFormat and writeFormat
if (readFormat.Contains("") == false)
{
throw new Exception("the read format input for card " + _name + " does not contain the tag");
}
if (writeFormat.Contains("") == false)
{
throw new Exception("the write format input for card " + _name + " does not contain the tag");
}
if (writeFormat.Contains("") == false)
{
throw new Exception("the write format input for card " + _name + " does not contain the tag");
}
}
catch (Exception ex)
{
_logger.Error(ex);
if (_serialPort.IsOpen == true)
{
_serialPort.Close();
}
throw;
}
}
///
///
///
///
public bool ClearErrors()
{
return false;
}
///
///
///
public string DetailedStatus
{
get
{
return "This is a FPGA Custom Ascii called " + _name;
}
}
///
///
///
public bool DisplayEnabled
{
get
{
return false;
}
set
{
throw new NotImplementedException();
}
}
///
/// Dispose of this object
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
///
///
public bool FrontPanelEnabled
{
get
{
return false;
}
set
{
throw new NotImplementedException();
}
}
///
///
///
public InstrumentMetadata Info
{
get
{
throw new NotImplementedException();
}
}
///
///
///
public void Initialize()
{
Initialize(string.Empty);
}
///
///
///
///
public void Initialize(string fpga)
{
lock (_syncObj)
{
if (_state == State.Uninitialized)
{
if (_serialPort.IsOpen == false)
{
_serialPort.Open();
}
//ClearBuffer();
_state = State.Ready;
}
else
{
throw new Exception("expected the state to be Uninitialized, state was: " + _state.ToString() + " on card " + _name);
}
}
}
///
///
///
public string Name
{
get
{
return _name;
}
set { _name = value; }
}
///
///
///
///
public SelfTestResult PerformSelfTest()
{
_selfTestResult = SelfTestResult.Unknown;
return _selfTestResult;
}
///
///
///
///
///
///
public uint Read(string fpga, uint address)
{
// lock up the FPGA resource
lock (_syncObj)
{
string hexAddress = "0x" + address.ToString("X8");
string commandToSend = _readFormat.Replace("", hexAddress);
commandToSend = commandToSend.Trim();
_serialPort.Write(commandToSend);
Thread.Sleep((int)_delayBeforeReadMs);
int numBytesRead = _serialPort.Read(_readBuf, 0, _readBuf.Length);
string data = Encoding.UTF8.GetString(_readBuf, 0, _readBuf.Length);
// get rid of new lines
data = data.Replace("\r", " ");
data = data.Replace("\n", " ");
data = data.Trim();
uint dataToReturn = Convert.ToUInt32(data, 16);
return dataToReturn;
}
}
///
///
///
///
///
///
///
///
public void ReadBlock(string fpgaName, uint address, uint numberOfWordsToRead, bool shallWeIncrementAddress, ref uint[] dataRead)
{
// lock up the FPGA resource
lock (_syncObj)
{
Thread.Sleep((int)_delayBeforeReadMs);
int bytesRead = _serialPort.Read(_readBuf, 0, _readBuf.Length);
int bytesToCopy = Math.Min(bytesRead, dataRead.Length);
Array.Copy(_readBuf, dataRead, bytesToCopy);
Array.Clear(_readBuf, 0, _readBuf.Length);
}
}
///
///
///
public void Reset()
{
Shutdown();
Initialize();
}
///
///
///
public SelfTestResult SelfTestResult
{
get
{
return _selfTestResult;
}
}
///
///
///
public State Status
{
get
{
return _state;
}
}
///
///
///
public void Shutdown()
{
// lock up the FPGA resource
lock (_syncObj)
{
if (_state == State.Ready)
{
_serialPort.Dispose();
_state = State.Uninitialized;
}
}
}
///
///
///
///
///
///
public void Write(string fpga, uint address, uint data)
{
// lock up the FPGA resource
lock (_syncObj)
{
string hexAddress = "0x" + address.ToString("X8");
string hexData = "0x" + data.ToString("X8");
string commandToSend = _writeFormat.Replace("", hexAddress);
commandToSend = commandToSend.Replace("", hexData);
commandToSend = commandToSend.Trim();
_serialPort.Write(commandToSend);
}
}
///
///
///
///
///
///
///
///
public void WriteBlock(string fpgaName, uint address, uint numberOfWordsToWrite, uint[] data, bool shallWeIncrementAddress)
{
// lock up the FPGA resource
lock (_syncObj)
{
throw new Exception("Not Implemented");
}
}
///
/// Loads firmware
///
///
public void LoadFirmware(string fpgaName)
{
Initialize(fpgaName);
}
#endregion
}
}