Big changes

This commit is contained in:
Duc
2025-03-13 12:04:22 -07:00
parent c689fcb7f9
commit ffa9905494
748 changed files with 199255 additions and 3743 deletions

View File

@@ -0,0 +1,512 @@
// 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 Raytheon.Instruments.GeneralIO;
using System.Collections.Generic;
using Automation.BDaq;
using NLog;
using Raytheon.Common;
using System.IO;
using System.Reflection;
namespace Raytheon.Instruments
{
/// <summary>
/// A class that implements a Context DIO card
/// </summary>
public class DIOAdvantech : IGeneralIO, IDisposable
{
#region PrivateClassMembers
private InstantDiCtrl _inputCtrl;
private InstantDoCtrl _outputCtrl;
private string _name;
private readonly int _deviceNum;
private readonly SelfTestResult _selfTestResult;
private State _state;
private object _syncObj = new Object();
private ErrorCode errorCode = ErrorCode.Success;
private int _numChannelPerPort = 8;
private int _channelStartIndex = 0;
private int _numInputChannels;
private int _numOutputChannels;
private bool _shallWeInitializeOutput = false;
private Dictionary<string, IODatatypes.DIOChannelInfo> _signalNameToChannelMap = new Dictionary<string, IODatatypes.DIOChannelInfo>();
/// <summary>
/// NLog logger
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Raytheon configuration
/// </summary>
private readonly IConfigurationManager _configurationManager;
private readonly IConfiguration _configuration;
#endregion
#region PrivateClassFunctions
~DIOAdvantech()
{
Dispose(false);
}
private static bool BioFailed(ErrorCode err)
{
return err < ErrorCode.Success && err >= ErrorCode.ErrorHandleNotValid;
}
/// <summary>
/// Dispose the object's resources
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_state == State.Ready)
{
Shutdown();
_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.
}
}
}
/// <summary>
/// Because the user has to define each channel number in the config file, some people will use 0 or 1 start their starting channel number
/// Whether the user prefers 0 or 1 as their starting channel number, this function will then calculate the port index and bit index that the
/// driver API needs to be able to drive/read the signal
/// <param name="signalName"></param>
/// <param name="portIndex">portIndex will range from 0..N</param>
/// <param name="bitIndex">bitIndex will range from 0..M</param>
/// </summary>
private void GetPortIndexAndBitIndex(string signalName, out int portIndex, out int bitIndex)
{
portIndex = (int)(Math.Ceiling((double)((int)_signalNameToChannelMap[signalName].channelNumber + Math.Abs(_channelStartIndex - 1)) / (double)_numChannelPerPort) - 1.0);
int multiplier = ((int)_signalNameToChannelMap[signalName].channelNumber + _numChannelPerPort) / _numChannelPerPort;
bitIndex = (((int)_signalNameToChannelMap[signalName].channelNumber + _numChannelPerPort) - (_numChannelPerPort * multiplier)) - _channelStartIndex;
if (bitIndex < 0)
{
bitIndex = _numChannelPerPort - 1;
}
}
/// <summary>
/// Invert Contec DIO bits.
/// </summary>
private byte InvertBit(byte bitValue)
{
if (bitValue == 0)
{
return 1;
}
else if (bitValue == 1)
{
return 0;
}
else
{
throw new Exception("Unexpected input value: " + bitValue.ToString());
}
}
private void ReadBit(int port, int bitNum, out byte data)
{
_inputCtrl.ReadBit(port, bitNum, out data);
}
private void WriteBit(int port, int bitNum, byte bitState)
{
errorCode = _outputCtrl.WriteBit(port, bitNum, bitState);
if (BioFailed(errorCode))
{
throw new Exception("call to WriteBit returned error: " + errorCode.ToString() + " on card: " + _name); ;
}
}
#endregion
#region PublicClassFunctions
/// <summary>
/// DIOAdvantech factory constructor
/// </summary>
/// <param name="deviceName"></param>
/// <param name="configurationManager"></param>
public DIOAdvantech(string deviceName, IConfigurationManager configurationManager, ILogger logger)
{
Name = deviceName;
_logger = logger;
_configurationManager = configurationManager;
_configuration = _configurationManager.GetConfiguration(Name);
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string dioModuleDefPath = _configuration.GetConfigurationValue(deviceName, ConfigXml.DIO_MODULE_DEF_FILEPATH.ToString());
if (!Path.IsPathRooted(dioModuleDefPath))
dioModuleDefPath = Path.GetFullPath(Path.Combine(assemblyFolder, dioModuleDefPath));
IConfigurationFile dioModuleConfig = new ConfigurationFile(dioModuleDefPath);
Boolean.TryParse(dioModuleConfig.ReadValue(Name, ConfigIni.SHALL_WE_DRIVE_OUTPUT_UPON_INITIALIZATION.ToString()), out _shallWeInitializeOutput);
Int32.TryParse(dioModuleConfig.ReadValue(Name, ConfigIni.DEVICE_NUMBER.ToString()), out _deviceNum);
Int32.TryParse(dioModuleConfig.ReadValue(Name, ConfigIni.NUM_INPUT_CHANNELS.ToString()), out _numInputChannels);
Int32.TryParse(dioModuleConfig.ReadValue(Name, ConfigIni.NUM_OUTPUT_CHANNELS.ToString()), out _numOutputChannels);
Int32.TryParse(dioModuleConfig.ReadValue(Name, ConfigIni.NUM_CHANNELS_PER_PORT.ToString()), out _numChannelPerPort);
Int32.TryParse(dioModuleConfig.ReadValue(Name, ConfigIni.CHANNEL_START_INDEX.ToString()), out _channelStartIndex);
if (!(_channelStartIndex == 0 || _channelStartIndex == 1))
{
throw new Exception($"The value for key {ConfigIni.CHANNEL_START_INDEX.ToString()} in section {Name} must be 0 or 1 in {dioModuleDefPath}");
}
List<string> outputSignalNames = dioModuleConfig.ReadAllKeys($"{Name}.{ConfigIni.OUTPUT_SIGNALS}");
List<string> intputSignalNames = dioModuleConfig.ReadAllKeys($"{Name}.{ConfigIni.INPUT_SIGNALS}");
IODatatypes.DIOChannelInfo info;
foreach (string signalName in outputSignalNames)
{
if (_signalNameToChannelMap.ContainsKey(signalName))
throw new Exception($"Key {signalName} in section {Name}.{ConfigIni.OUTPUT_SIGNALS} conflicts with the same key defined in another section.");
string iniLine = dioModuleConfig.ReadValue($"{Name}.{ConfigIni.OUTPUT_SIGNALS}", signalName);
string[] infoTokens = iniLine.Split('|');
if (infoTokens.Length != 2)
{
throw new Exception($"Key {signalName} in section {Name}.{ConfigIni.OUTPUT_SIGNALS} does not contain 2 tokens");
}
info.channelNumber = Convert.ToUInt32(infoTokens[0]);
info.initialValue = Convert.ToInt32(infoTokens[1]);
_signalNameToChannelMap[signalName] = info;
}
foreach (string signalName in intputSignalNames)
{
if (_signalNameToChannelMap.ContainsKey(signalName))
throw new Exception($"Key {signalName} in section {Name}.{ConfigIni.INPUT_SIGNALS} conflicts with the same key defined in another section.");
string iniLine = dioModuleConfig.ReadValue($"{Name}.{ConfigIni.INPUT_SIGNALS}", signalName);
info.channelNumber = Convert.ToUInt32(iniLine);
info.initialValue = -1;
_signalNameToChannelMap[signalName] = info;
}
_state = State.Uninitialized;
_selfTestResult = SelfTestResult.Unknown;
}
/// <summary>
///
/// </summary>
public DIOAdvantech(string deviceName, int deviceNum)
{
_deviceNum = deviceNum;
_name = deviceName;
_logger = LogManager.GetCurrentClassLogger();
_state = State.Uninitialized;
_selfTestResult = SelfTestResult.Unknown;
}
public bool ClearErrors()
{
throw new NotImplementedException();
}
/// <summary>
///
/// </summary>
public string DetailedStatus
{
get
{
//_outputCtrl.SelectedDevice; Need to see what the card returns for this
return "This is a Advantech DIO Card " + _name;
}
}
/// <summary>
///
/// </summary>
public bool DisplayEnabled
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <summary>
/// Dispose of this object.
/// </summary>
public void Dispose()
{
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.
}
}
}
}
/// <summary>
///
/// </summary>
public bool FrontPanelEnabled
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/// <summary>
///
/// </summary>
/// <param name="signalName"></param>
/// <returns></returns>
public IODatatypes.BitState GetBitState(string signalName)
{
lock (_syncObj)
{
if (!_signalNameToChannelMap.ContainsKey(signalName))
throw new Exception($"Signal name {signalName} doesn't exist for card: " + _name);
if (_signalNameToChannelMap[signalName].channelNumber >= _numInputChannels || _signalNameToChannelMap[signalName].channelNumber < _channelStartIndex)
{
throw new Exception($"The input channel number {_signalNameToChannelMap[signalName].channelNumber} specified must be >= {_channelStartIndex} and < {_numInputChannels+_channelStartIndex} on card " + _name);
}
GetPortIndexAndBitIndex(signalName, out int portIndex, out int bitIndex);
ReadBit(portIndex, bitIndex, out byte data);
return (IODatatypes.BitState)(data);
}
}
/// <summary>
///
/// </summary>
public InstrumentMetadata Info
{
get
{
throw new NotImplementedException();
}
}
public void Initialize()
{
lock (_syncObj)
{
if (_state == State.Uninitialized)
{
//@@@ do we need both of these? DO can read and write. Read may be for internal read back
_inputCtrl = new InstantDiCtrl();
_outputCtrl = new InstantDoCtrl();
_inputCtrl.SelectedDevice = new DeviceInformation(_deviceNum);
_outputCtrl.SelectedDevice = new DeviceInformation(_deviceNum);
if (_shallWeInitializeOutput)
{
foreach (KeyValuePair<string, IODatatypes.DIOChannelInfo> item in _signalNameToChannelMap)
{
if (item.Value.initialValue != -1)
{
SetBit(item.Key, (IODatatypes.BitState)item.Value.initialValue);
}
}
}
_state = State.Ready;
}
else
{
throw new Exception("expected the state to be Uninitialized, state was: " + _state.ToString() + " on card " + _name);
}
}
}
/// <summary>
/// Return list of signal names
/// </summary>
public List<string> GetSignalNames()
{
return new List<string>(_signalNameToChannelMap.Keys);
}
/// <summary>
///
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
///
/// </summary>
public uint NumberOfInputBits
{
get
{
return (uint)_numInputChannels;
}
}
/// <summary>
///
/// </summary>
public uint NumberOfOutputBits
{
get
{
return (uint)_numOutputChannels;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public SelfTestResult PerformSelfTest()
{
lock (_syncObj)
{
// card does not support self test
//throw new NotImplementedException("card does not support self test" + " on card " + _name);
throw new NotImplementedException();
}
}
public void Reset()
{
lock (_syncObj)
{
Shutdown();
Initialize();
}
}
/// <summary>
///
/// </summary>
/// <param name="signalName"></param>
/// <param name="state"> high(open) or low(closed) </param>
///
public void SetBit(string signalName, IODatatypes.BitState state)
{
lock (_syncObj)
{
if (!_signalNameToChannelMap.ContainsKey(signalName))
throw new Exception($"Signal name {signalName} doesn't exist for card: " + _name);
if (_signalNameToChannelMap[signalName].channelNumber >= _numOutputChannels || _signalNameToChannelMap[signalName].channelNumber < _channelStartIndex)
{
throw new Exception($"The output channel number {_signalNameToChannelMap[signalName].channelNumber} specified must be >= {_channelStartIndex} and < {_numOutputChannels +_channelStartIndex} on card " + _name);
}
GetPortIndexAndBitIndex(signalName, out int portIndex, out int bitIndex);
WriteBit(portIndex, bitIndex, (byte)state);
}
}
public void SetTristate(string signalName)
{
throw new NotImplementedException();
}
/// <summary>
///
/// </summary>
public SelfTestResult SelfTestResult
{
get
{
return _selfTestResult;
}
}
public void Shutdown()
{
lock (_syncObj)
{
if (_state == State.Ready)
{
_outputCtrl.Dispose();
_inputCtrl.Dispose();
_state = State.Uninitialized;
}
}
}
/// <summary>
///
/// </summary>
public State Status
{
get
{
return _state;
}
}
#endregion
}
}

View File

@@ -0,0 +1,139 @@
// **********************************************************************************************************
// DIOAdvantechFactory.cs
// 2/20/2023
// NGI - Next Generation Interceptor
//
// Contract No. HQ0856-21-C-0003/1022000209
//
// THIS DOCUMENT DOES NOT CONTAIN TECHNOLOGY OR TECHNICAL DATA CONTROLLED UNDER EITHER THE U.S.
// INTERNATIONAL TRAFFIC IN ARMS REGULATIONS OR THE U.S. EXPORT ADMINISTRATION REGULATIONS.
//
// 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.
//
// UNPUBLISHED WORK - COPYRIGHT RAYTHEON COMPANY.
//
// DESTRUCTION NOTICE: FOR CLASSIFIED DOCUMENTS FOLLOW THE PROCEDURES IN DOD 5220.22-M,
// NATIONAL INDUSTRIAL SECURITY PROGRAM OPERATING MANUAL, FEBRUARY 2006,
// INCORPORATING CHANGE 1, MARCH 28, 2013, CHAPTER 5, SECTION 7, OR DODM 5200.01-VOLUME 3,
// DOD INFORMATION SECURITY PROGRAM: PROTECTION OF CLASSIFIED INFORMATION, ENCLOSURE 3,
// SECTION 17. FOR CONTROLLED UNCLASSIFIED INFORMATION FOLLOW THE PROCEDURES IN DODM 5200.01-VOLUME 4,
// INFORMATION SECURITY PROGRAM: CONTROLLED UNCLASSIFIED INFORMATION.
//
// CONTROLLED BY: MISSILE DEFENSE AGENCY
// CONTROLLED BY: GROUND-BASED MIDCOURSE DEFENSE PROGRAM OFFICE
// CUI CATEGORY: CTI
// 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;
namespace Raytheon.Instruments
{
[ExportInstrumentFactory(ModelNumber = "DIOAdvantechFactory")]
public class DIOAdvantechFactory : 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;
public DIOAdvantechFactory(string defaultConfigPath = DefaultConfigPath)
: this(null, defaultConfigPath)
{
}
/// <summary>
/// COECommDeviceInstrumentFactory injection constructor
/// </summary>
/// <param name="configManager"></param>
/// <param name="simEngine"></param>
/// <param name="logger"></param>
[ImportingConstructor]
public DIOAdvantechFactory([Import(AllowDefault = false)] IConfigurationManager configManager,
[Import(AllowDefault = true)] string defaultConfigPath = null)
{
DefaultPath = defaultConfigPath;
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(IGeneralIO));
}
/// <summary>
/// Gets the instrument
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IInstrument GetInstrument(string name)
{
try
{
_logger = LogManager.GetLogger(name);
return new DIOAdvantech(name, _configurationManager, _logger);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Gets the instrument
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public object GetInstrument(string name, bool simulateHw)
{
try
{
_logger = LogManager.GetLogger(name);
if (simulateHw)
return new DIOSim(name, _configurationManager, _logger);
else
return new DIOAdvantech(name, _configurationManager, _logger);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Gets supported interfaces
/// </summary>
/// <returns></returns>
public ICollection<Type> GetSupportedInterfaces()
{
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);
}
}
}

View File

@@ -0,0 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Solution.props" />
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<AssemblyName>Raytheon.Instruments.DIOAdventech</AssemblyName>
<Product>DIO Adventech implementation</Product>
<Description>Digital IO Adventech implementation</Description>
<OutputType>Library</OutputType>
<!-- Static versioning (Suitable for Development) -->
<!-- Disable the line below for dynamic versioning -->
<Version>1.0.0</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog" Version="5.0.0" />
<PackageReference Include="Raytheon.Common" Version="1.0.0" />
<PackageReference Include="Raytheon.Instruments.GeneralIO.Contracts" Version="1.7.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DIOSim\DIOSim.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="Automation.BDaq4">
<HintPath>..\..\Common\COTS\Advantech\Automation.BDaq4.dll</HintPath>
</Reference>
</ItemGroup>
<!-- Copy all *.dlls and *.pdb in the output folder to a temp folder -->
<Target Name="CopyFiles" AfterTargets="AfterBuild">
<ItemGroup>
<FILES_1 Include="$(OutDir)*.dll" />
<FILES_2 Include="$(OutDir)*.pdb" />
</ItemGroup>
<Copy SourceFiles="@(FILES_1)" DestinationFolder="$(HalTempFolder)" />
<Copy SourceFiles="@(FILES_2)" DestinationFolder="$(HalTempFolder)" />
</Target>
</Project>