// 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 FpgaMeasurementInstrumentsLib;
using NLog;
using Raytheon.Common;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Raytheon.Instruments
{
///
/// A class that implements the Teradyne HSS Test Station Chassis
///
public unsafe class CommFpgaHssubChassisTs : IFpgaComm
{
#region PrivateClassMembers
public struct LocalBusParams
{
public int cardHandle;
public int address;
public int data;
}
public struct CardInfo
{
public string cardName;
public string cardAddress;
public int startingOffset;
public string cardFirmwareFile;
public string memMap;
}
private static object _syncObj = new Object();
private SortedDictionary _hssCardNameMap;
private SortedDictionary _hssCardHandleMap;
private readonly string _chassisAddress;
private readonly string _killHandlerAppName;
private readonly string _msgHandlerAppName;
private uint _chassisHandle;
private int _hssubAppInit;
private int _hssubSubSystemApp;
private int _hssubSubSystemAppSync;
private int _hssubCloseAppSync;
private int _hssubKillApp;
private int _hsiHandle;
private List _cardList;
private SelfTestResult _selfTestResult;
private State _state;
private string _name;
private HssubNativeMethods.MessageCallbackDelagate _callBack;
///
/// NLog logger
///
private readonly ILogger _logger;
///
/// Raytheon configuration
///
private readonly IConfigurationManager _configurationManager;
private readonly IConfiguration _configuration;
#endregion
#region PrivateFuctions
///
/// The finalizer.
///
~CommFpgaHssubChassisTs()
{
Dispose(false);
}
///
///
///
///
///
///
///
private void CreateCard(string cardName, string cardAddress, int startingOffset, string cardFirmwareFile, string memMap)
{
lock (_syncObj)
{
// create the card
CommFpgaHssubCardTs card = new CommFpgaHssubCardTs(cardName, cardAddress, startingOffset, cardFirmwareFile, _chassisHandle, _hssubSubSystemApp, _hssubSubSystemAppSync, memMap);
// wait for the chassis to respond
HssUtilTs.WaitForSync(_chassisHandle, _hssubSubSystemAppSync, _name);
// make sure the chassis gave us a good card handle
if (_hsiHandle == 0)
{
throw new Exception("_hsiHandle is 0");
}
// give the card its handle
card.SetHandle(_hsiHandle);
// hold onto the card
_hssCardNameMap[cardName] = card;
_hssCardHandleMap[_hsiHandle] = card;
// set the _hsiHandle back to zero for the next card
_hsiHandle = 0;
}
}
///
/// Dispose of this object's resources.
///
/// True = currently disposing, False = not disposing.
protected virtual void Dispose(bool disposing)
{
try
{
if (disposing)
{
lock (_syncObj)
{
if (_state == State.Ready)
{
int ret = HssubNativeMethods.terHss_close(_chassisHandle);
_state = State.Uninitialized;
}
}
}
}
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
}
}
}
///
///
///
private void InitChassis()
{
//0 is VI_FALSE, 1 is VI_TRUE
int ret = HssubNativeMethods.terHss_init(_chassisAddress, 0, 1, ref _chassisHandle);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_init returned returned an error(" + ret + ")" + ": " + errorStr);
}
// start the message application
LoadMessageApp();
}
///
///
///
private void LoadMessageApp()
{
int ret = HssubNativeMethods.terHss_Application_CreateSyncObject(_chassisHandle, "AppInit", ref _hssubAppInit);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_Application_CreateSyncObject(AppInit) returned an error(" + ret + ")" + ": " + errorStr);
}
ret = HssubNativeMethods.terHss_Application_CreateSyncObject(_chassisHandle, "AppSync", ref _hssubSubSystemAppSync);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_Application_CreateSyncObject(AppSync) returned an error(" + ret + ")" + ": " + errorStr);
}
ret = HssubNativeMethods.terHss_Application_CreateSyncObject(_chassisHandle, "SubAppQuit", ref _hssubCloseAppSync);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_Application_CreateSyncObject(SubAppQuit) returned an error(" + ret + ")" + ": " + errorStr);
}
ret = HssubNativeMethods.terHss_Application_RegisterMessageCallback(_chassisHandle, _callBack);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_Application_RegisterMessageCallback() returned an error(" + ret + ")" + ": " + errorStr);
}
ret = HssubNativeMethods.terHss_Subsystem_SendFile(_chassisHandle, _killHandlerAppName, "c:\\temp\\killhndlr.bat", HssubNativeMethods.TERHSS_OPTION_ALLOW_OVERWRITE);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_SubSyste_SendFile(Killer App) returned an error(" + ret + ")" + ": " + errorStr);
}
ret = HssubNativeMethods.terHss_Application_Load(_chassisHandle, "Killer App", "c:\\temp\\killhndlr.bat", ref _hssubKillApp);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_Application_Load(Killer App) returned an error(" + ret + ")" + ": " + errorStr);
}
ret = HssubNativeMethods.terHss_Application_Start(_chassisHandle, _hssubKillApp, "", 1);
/*if (ret != 0)
{
string errorStr = HssUtil.BuildErrorString(_chassisHandle, ret, _chassisLogicalName);
throw new Exception("terHss_Application_Start(Killer App) returned an error(" + ret + ")" + ": " + errorStr);
}*/
ret = HssubNativeMethods.terHss_Subsystem_SendFile(_chassisHandle, _msgHandlerAppName, "c:\\temp\\hndlr.exe", HssubNativeMethods.TERHSS_OPTION_ALLOW_OVERWRITE);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_SubSyste_SendFile(Msg Handler App) returned an error(" + ret + ")" + ": " + errorStr);
}
ret = HssubNativeMethods.terHss_Application_Load(_chassisHandle, "Subsystem App", "c:\\temp\\hndlr.exe", ref _hssubSubSystemApp);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_Application_Load(Msg Handler App) returned an error(" + ret + ")" + ": " + errorStr);
}
ret = HssubNativeMethods.terHss_Application_Start(_chassisHandle, _hssubSubSystemApp, "", HssubNativeMethods.TERHSS_TIMEOUT_60SEC);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_Application_Start(Msg Handler App) returned an error(" + ret + ")" + ": " + errorStr);
}
// wait for the chassis to respond
HssUtilTs.WaitForSync(_chassisHandle, _hssubAppInit, _name);
}
///
///
///
///
///
///
///
///
private void MessageCallback(uint sessionHandle, int applicationHandle, int messageContext, uint messageSize, byte* pMessage)
{
try
{
//ErrorLogger.Instance().Write("received message ID: " + messageContext.ToString(), ErrorLogger.LogLevel.INFO);
if (messageContext == HssubNativeMethods.MESSAGE_CONTEXT_INIT_INSTRUMENT)
{
int* pTemp = (int*)pMessage;
_hsiHandle = *pTemp;
}
else if (messageContext == HssubNativeMethods.MESSAGE_CONTEXT_LB_READ32)
{
// get data into array and convert to the LocalBusParams structure
byte[] arr = new byte[messageSize];
Marshal.Copy((IntPtr)pMessage, arr, 0, (int)messageSize);
HssUtilTs.LocalBusParams lbParams = HssUtilTs.ByteArrayToLocalBusParms(arr);
_hssCardHandleMap[lbParams.cardHandle].SetLocalBusRxData(lbParams.address, lbParams.data);
}
/*else if (messageContext == HssubNativeMethods.MESSAGE_CONTEXT_LB_WRITE32)//@@@ this case does not exist...
{
//HssubChassis.LocalBusParams lbParams = HssUtil.ByteArrayToLocalBusParms(message);
//_hssCardHandleMap[lbParams.cardHandle].SetLocalBusRxData(lbParams.address, lbParams.data);
}*/
else
{
//ErrorLogger.Instance().Write("" + messageContext + " not yet handled");
}
}
catch (Exception)
{
//ErrorLogger.Instance().Write("" + err.Message);
}
}
#endregion
#region PublicFuctions
///
/// CommFpgaHssubChassisTs factory constructor
///
///
///
public CommFpgaHssubChassisTs(string deviceName, IConfigurationManager configurationManager, ILogger logger)
{
Name = deviceName;
_logger = logger;
_configurationManager = configurationManager;
_configuration = _configurationManager.GetConfiguration(Name);
_chassisAddress = _configuration.GetConfigurationValue("CommFpgaHssubChassisTs", "ChassisAddress", "127.0.0.1");
_killHandlerAppName = _configuration.GetConfigurationValue("CommFpgaHssubChassisTs", "KillHandlerAppName", "");
_msgHandlerAppName = _configuration.GetConfigurationValue("CommFpgaHssubChassisTs", "MsgHandlerAppName", "");
_cardList = new List();
_selfTestResult = SelfTestResult.Unknown;
_state = State.Uninitialized;
// hold onto callback
_callBack = new HssubNativeMethods.MessageCallbackDelagate(MessageCallback);
// _chassisHandle gets set in Initialize
_chassisHandle = 0;
// these get initialized in LoadMessageApp()
_hssubAppInit = 0;
_hssubSubSystemApp = 0;
_hssubSubSystemAppSync = 0;
_hssubCloseAppSync = 0;
_hssubKillApp = 0;
// this is for card handles, it gets set in the MessageCallback() and passed over to the card object
_hsiHandle = 0;
// hold onto the card objects
_hssCardNameMap = new SortedDictionary();
_hssCardHandleMap = new SortedDictionary();
}
///
///
///
///
///
///
///
public CommFpgaHssubChassisTs(string name, string chassisAddress, string killHandlerAppName, string msgHandlerAppName)
{
// hang onto passed in args
_name = name;
_logger = LogManager.GetCurrentClassLogger();
_chassisAddress = chassisAddress;
_killHandlerAppName = killHandlerAppName;
_msgHandlerAppName = msgHandlerAppName;
_cardList = new List();
_selfTestResult = SelfTestResult.Unknown;
_state = State.Uninitialized;
// hold onto callback
_callBack = new HssubNativeMethods.MessageCallbackDelagate(MessageCallback);
// _chassisHandle gets set in Initialize
_chassisHandle = 0;
// these get initialized in LoadMessageApp()
_hssubAppInit = 0;
_hssubSubSystemApp = 0;
_hssubSubSystemAppSync = 0;
_hssubCloseAppSync = 0;
_hssubKillApp = 0;
// this is for card handles, it gets set in the MessageCallback() and passed over to the card object
_hsiHandle = 0;
// hold onto the card objects
_hssCardNameMap = new SortedDictionary();
_hssCardHandleMap = new SortedDictionary();
}
///
///
///
///
public void AddCard(CardInfo cardInfo)
{
// lock up the FPGA resource
lock (_syncObj)
{
_cardList.Add(cardInfo);
}
}
///
///
///
///
public bool ClearErrors()
{
return false;
}
///
///
///
public string DetailedStatus
{
get
{
return "This is a FPGA HSS TS called " + _name;
}
}
///
///
///
public bool DisplayEnabled
{
get
{
return false;
}
set
{
throw new NotImplementedException();
}
}
///
/// Dispose of this object's resources.
///
public void Dispose()
{
// lock up the FPGA resource
lock (_syncObj)
{
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
{
return false;
}
set
{
throw new NotImplementedException();
}
}
///
///
///
public InstrumentMetadata Info
{
get
{
throw new NotImplementedException();
}
}
///
///
///
public void Initialize()
{
throw new NotImplementedException();
}
///
///
///
///
public void Initialize(string fpga)
{
// lock up the FPGA resource
lock (_syncObj)
{
if (_state == State.Uninitialized)
{
InitChassis();
// init each card
for (int i = 0; i < _cardList.Count; i++)
{
CreateCard(_cardList[i].cardName, _cardList[i].cardAddress, _cardList[i].startingOffset, _cardList[i].cardFirmwareFile, _cardList[i].memMap);
}
_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()
{
// lock up the FPGA resource
lock (_syncObj)
{
short testResults = -1;
StringBuilder errorStrTemp = new StringBuilder(512);
int ret = HssubNativeMethods.terHss_self_test(_chassisHandle, ref testResults, errorStrTemp);
if (ret != 0)
{
string errorStr = HssUtilTs.BuildErrorString(_chassisHandle, ret, _name);
throw new Exception("terHss_self_test returned an error(" + ret + ")" + ": " + errorStr);
}
else if (testResults != 0)
{
_selfTestResult = SelfTestResult.Fail;
throw new Exception("HSSub Self Test returned an error: " + testResults.ToString() + ": " + errorStrTemp.ToString());
}
else
{
_selfTestResult = SelfTestResult.Pass;
}
return _selfTestResult;
}
}
///
///
///
///
///
///
public uint Read(string fpgaName, uint address)
{
// lock up the FPGA resource
lock (_syncObj)
{
return _hssCardNameMap[fpgaName].Read(fpgaName, address);
}
}
///
///
///
///
///
///
///
///
public void ReadBlock(string fpgaName, uint address, uint numberOfWordsToRead, bool shallWeIncrementAddress, ref uint[] dataRead)
{
// lock up the FPGA resource
lock (_syncObj)
{
_hssCardNameMap[fpgaName].ReadBlock(fpgaName, address, numberOfWordsToRead, shallWeIncrementAddress, ref dataRead);
}
}
///
///
///
public void Reset()
{
lock (_syncObj)
{
throw new NotImplementedException();
}
}
///
///
///
public SelfTestResult SelfTestResult
{
get
{
return _selfTestResult;
}
}
///
///
///
public void Shutdown()
{
// lock up the FPGA resource
lock (_syncObj)
{
if (_state == State.Ready)
{
int ret = HssubNativeMethods.terHss_close(_chassisHandle);
_state = State.Uninitialized;
}
}
}
///
///
///
public State Status
{
get
{
return _state;
}
}
///
///
///
///
///
///
public void Write(string fpgaName, uint address, uint value)
{
// lock up the FPGA resource
lock (_syncObj)
{
_hssCardNameMap[fpgaName].Write(fpgaName, address, value);
}
}
///
///
///
///
///
///
///
///
public void WriteBlock(string fpgaName, uint address, uint numberOfWordsToWrite, uint[] data, bool shallWeIncrementAddress)
{
// lock up the FPGA resource
lock (_syncObj)
{
_hssCardNameMap[fpgaName].WriteBlock(fpgaName, address, numberOfWordsToWrite, data, shallWeIncrementAddress);
}
}
///
/// Loads firmware
///
///
public void LoadFirmware(string fpgaName)
{
Initialize(fpgaName);
}
#endregion
}
}