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,143 @@
// **********************************************************************************************************
// BITCOEDeviceInstrumentFactory.cs
// 6/21/2022
// 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 = "BITCOEDeviceInstrumentFactory")]
public class BITCOEDeviceInstrumentFactory : IInstrumentFactory
{
/// <summary>
///
/// </summary>
private ILogger _logger;
/// <summary>
/// The supported interfaces
/// </summary>
private readonly List<Type> _supportedInterfaces = new List<Type>();
private readonly IConfigurationManager _configurationManager;
private const string DefaultConfigPath = @"C:\ProgramData\Raytheon\InstrumentManagerService";
private static string DefaultPath;
private readonly DriverType _driverType;
public BITCOEDeviceInstrumentFactory(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 BITCOEDeviceInstrumentFactory([Import(AllowDefault = false)] IConfigurationManager configManager,
[Import(AllowDefault = true)] string defaultConfigPath = null,
[Import(AllowDefault = true)] DriverType driverType = DriverType.TCP)
{
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();
_driverType = driverType;
_supportedInterfaces.Add(typeof(IBit));
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IInstrument GetInstrument(string name)
{
try
{
_logger = LogManager.GetLogger(name);
return new BITCOEDeviceInstrument(name, _configurationManager, _driverType, _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);
return new BITCOEDeviceInstrument(name, _configurationManager, _driverType, _logger);
}
catch (Exception)
{
throw;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ICollection<Type> GetSupportedInterfaces()
{
return _supportedInterfaces.ToArray();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static IConfigurationManager GetConfigurationManager()
{
return string.IsNullOrEmpty(DefaultPath) ? new RaytheonConfigurationManager() : new RaytheonConfigurationManager(DefaultPath);
}
}
}

View File

@@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Solution.props" />
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<AssemblyName>Raytheon.Instruments.BITCOEDeviceNode</AssemblyName>
<Description>Specialized instrument implementation of IBit interface for running real time Build In Tests via COE</Description>
<!-- Static versioning (Suitable for Development) -->
<!-- Disable the line below for dynamic versioning -->
<Version>1.0.0</Version>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Deploy|AnyCPU'">
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog" Version="5.0.0" />
<PackageReference Include="Raytheon.Common" Version="1.0.0" />
<PackageReference Include="Raytheon.Instruments.BIT.Contracts" Version="1.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\COEComm\COEComm.csproj" />
</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>

View File

@@ -0,0 +1,135 @@
// **********************************************************************************************************
// ConfigurationHelper.cs
// 7/5/2022
// 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 Raytheon.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Raytheon.Instruments
{
/// <summary>
/// type conversion utility with a special case for enums
/// </summary>
public static class TypeConverter
{
public static T ChangeType<T>(object value)
{
return typeof(T).IsEnum ? (T)Enum.Parse(typeof(T), value.ToString()) : (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
System.ComponentModel.TypeConverter tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : System.ComponentModel.TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
/// <summary>
/// Helper class contains extention fuctions for reading types other than strings from configuration,
/// as well as reading lists of values
/// </summary>
public static class ConfigurationHelper
{
/// <summary>
/// template function for reading different types from configuration
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static T GetConfigurationValue<T>(this IConfiguration configuration, string section, string key, string defaultValue)
{
var tmpResult = configuration.GetConfigurationValue(section, key, defaultValue);
return !string.IsNullOrEmpty(tmpResult) ? TypeConverter.ChangeType<T>(tmpResult) : default;
}
/// <summary>
/// returns multivalue result (list of T) from configuration
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static List<T> GetConfigurationListValue<T>(this IConfiguration configuration, string section, string key, List<T> defaultValue)
{
var tmpResult = configuration.GetXmlConfiguration(section);
if (string.IsNullOrEmpty(tmpResult))
{
var xmlStr = new StringBuilder();
xmlStr.Append($"<{key}s>");
foreach (var item in defaultValue)
{
xmlStr.Append($"<{key}>");
xmlStr.Append(item.ToString());
xmlStr.Append($"</{key}>");
}
xmlStr.Append($"</{key}s>");
configuration.SetXmlConfiguration(section, xmlStr.ToString());
return defaultValue;
}
else
{
var stringRes = BuildElementListFromXml(tmpResult, key);
return new List<T>(stringRes.Select(x => TypeConverter.ChangeType<T>(x)));
}
}
/// <summary>
/// returns values from XML section converted to string list
/// </summary>
/// <param name="data"></param>
/// <param name="key"></param>
/// <returns></returns>
private static List<string> BuildElementListFromXml(string data, string key)
{
XElement doc = XElement.Parse(data);
IEnumerable<XElement> xmlMessages = from m
in doc.Elements($"{key}s").Elements(key)
select m;
var messages = xmlMessages.Select(x => x.Value);
return messages?.ToList();
}
}
}

View File

@@ -0,0 +1,56 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Solution.props" />
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<AssemblyName>Raytheon.Instruments.COEComm</AssemblyName>
<Description>C# wrapper for the COE Windows, integrated real-time software operating environment designed for use in embedded systems</Description>
<!-- Static versioning (Suitable for Development) -->
<!-- Disable the line below for dynamic versioning -->
<Version>1.0.0</Version>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup>
<NoWarn>1701;1702;NU1803</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog" Version="5.0.0" />
</ItemGroup>
<PropertyGroup>
<PrepareForRunDependsOn>$(PrepareForRunDependsOn);CopyFilesTargetName</PrepareForRunDependsOn>
</PropertyGroup>
<PropertyGroup>
<coeDLLs>build\R04.$(Configuration)\x86\coeWindows-shared.dll</coeDLLs>
<coeDLLs Condition="'$(Configuration)'=='Debug' OR '$(Configuration)'=='Release' OR '$(Configuration)'=='Deploy'">build\R04.06.05.02\x86\coeWindows-shared.dll;build\R04.06.05.02\x86\coeWindows-sharedd.dll</coeDLLs>
</PropertyGroup>
<ItemGroup>
<Content Include="$(coeDLLs)">
<PackagePath>lib\$(TargetFramework)</PackagePath>
<TargetPath></TargetPath>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<Pack>True</Pack>
</Content>
</ItemGroup>
<Target Name="CopyFilesTargetName" BeforeTargets="Build">
<Copy SourceFiles="$(coeDLLs)" DestinationFolder="$(OutDir)" />
</Target>
<!-- 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>

View File

@@ -0,0 +1,218 @@
// **********************************************************************************************************
// BitFieldGeneric.cs
// 5/18/2022
// 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 System;
namespace Raytheon.Instruments.MessagingUtilities
{
// This is a generic class used to apply a bitfield to
// a value to get the desired value
class BitFieldGeneric<T> where T : IConvertible
{
protected long m_Value; // This is the value being operated on
protected ulong m_Mask;
public char ToChar()
{
return (char)m_Value;
}
public sbyte ToSByte()
{
return (sbyte)m_Value;
}
public short ToShort()
{
return (short)m_Value;
}
public int ToInt()
{
return (int)m_Value;
}
public long ToLong()
{
return (long)m_Value;
}
public ushort ToUShort()
{
return (ushort)m_Value;
}
public uint ToUInt()
{
return (uint)m_Value;
}
public ulong ToULong()
{
return (ulong)m_Value;
}
public BitFieldGeneric(T value, ulong bitMask)
{
m_Mask = bitMask;
try
{
m_Value = ApplyBitMask((ulong)value.ToInt64(null), bitMask);
}
catch
{
m_Value = ApplyBitMask(value.ToUInt64(null), bitMask);
}
}
public BitFieldGeneric(string value, ulong bitMask)
{
m_Mask = bitMask;
if(string.IsNullOrEmpty(value))
{
value = "0";
}
if (Parse.Try(value, out m_Value) == true)
{
m_Value = PrepareWithBitMask(m_Value, bitMask);
}
else
{
throw new Exception("Unable to parse value = " + value);
}
}
// count the number of 1 bits in a ulong
int BitCount(ulong x)
{
int n = 0;
if (x > 0) do ++n; while ((x &= x - 1) > 1);
return n;
}
// Check to see if the MSB is set after accounting for
// the mask. If it is, then the number should be converted
// to display a negative number
public void ToSigned()
{
if (m_Mask > 0)
{
// See if the sign bit is set
int numbits = BitCount(m_Mask);
if (m_Value > (Math.Pow(2, numbits - 1)))
{
// If it is, take the two's complement
m_Value = (~m_Value) + 1;
// Mask off the leading F's from the conversion
ulong mask = 1;
for (int i = 0; i < numbits - 1; i++)
{
mask = (mask << 1) + 1;
}
m_Value = (long)(((ulong)m_Value) & mask);
// Add the negative sign
m_Value = -m_Value;
}
}
}
public override string ToString()
{
return m_Value.ToString();
}
public void BitOR(T value)
{
long orValue = value.ToInt64(null);
m_Value |= orValue;
}
private long PrepareWithBitMask(long val, ulong bitMask)
{
ulong value = (ulong)val;
ulong mask = bitMask;
if (bitMask != 0)
{
if ((mask & 1) != 1)
{
while (((mask >> 1) & 1) != 1) //shift mask to LSB
{
mask >>= 1;
}
mask >>= 1; // one last shift not done by loop
}
value &= mask; // ensure value is contained in the same # of bits as the mask
// Shift the value back to its proper spot in the memory
while (mask != bitMask)
{
value <<= 1;
mask <<= 1;
}
}
return (long)value;
}
private long ApplyBitMask(ulong val, ulong bitMask)
{
ulong value = val;
if (bitMask != 0) // Apply the bit field
{
value &= bitMask;
// Shift until the bitmask resides in the LSB
if ((bitMask & 1) != 1)
{
while (((bitMask >> 1) & 1) != 1)
{
value >>= 1;
bitMask >>= 1;
}
// We need one more shift after leaving the while loop
value >>= 1;
}
}
return (long)value;
}
}
}

View File

@@ -0,0 +1,502 @@
// **********************************************************************************************************
// BytePackingXml.cs
// 5/18/2022
// 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 System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
namespace Raytheon.Instruments.MessagingUtilities
{
// Takes an XML ICD and adds in nodes to represent the byte packing
// The padding added will be displayed in the tool as arrays of characters
internal class BytePackingXml : XmlDocument
{
private readonly int m_Packing = 8;
private readonly Dictionary<string, double> m_ConstMap;
private readonly Dictionary<string, int> m_SizeMap;
private readonly Dictionary<string, int> m_PadMap;
public BytePackingXml(string icdStr) : base()
{
// Create the dictionaries
m_ConstMap = new Dictionary<string, double>();
m_PadMap = new Dictionary<string, int>();
m_SizeMap = new Dictionary<string, int>();
// Create an XML document from the string
LoadXml(icdStr);
XPathNavigator node = CreateNavigator();
//Get the type of packing
XPathNodeIterator nodeset = node.Select("/interface/packing");
if (nodeset.MoveNext() == true)
{
if (!Parse.Try(nodeset.Current.Value.Trim(), out m_Packing))
{
switch (nodeset.Current.Value.Trim())
{
case "char":
case "1":
m_Packing = 1;
break;
case "short":
case "2":
m_Packing = 2;
break;
case "long":
case "4":
m_Packing = 4;
break;
case "double":
case "8":
default:
m_Packing = 8;
break;
}
}
}
// Handle all of the constants
nodeset = node.Select("/interface/constant");
while (nodeset.MoveNext())
{
ProcessConstantNode(nodeset.Current);
}
nodeset = node.Select("/interface/typedef");
while (nodeset.MoveNext())
{
ProcessTypedefNode(nodeset.Current);
}
nodeset = node.Select("/interface/enum");
while (nodeset.MoveNext())
{
ProcessEnumerationNode(nodeset.Current);
}
nodeset = node.Select("/interface/structure|/interface/message");
while (nodeset.MoveNext())
{
ProcessStructureNode(nodeset.Current);
}
NormalizeIcdLabels();
}
// This function takes all of the messages in the ICD
// and converts the labels into decimal, so when we do
// a string lookup, they will all be in the same known format
private void NormalizeIcdLabels()
{
XPathNavigator navigator = CreateNavigator();
XPathNodeIterator nodeset;
nodeset = navigator.Select("/interface/message/label");
while (nodeset.MoveNext())
{
try
{
double dLabel = GetConstFromString(nodeset.Current.Value);
nodeset.Current.SetValue(((int)dLabel).ToString());
}
catch
{
throw new Exception("Message Label, " + nodeset.Current.Value + ", can not be converted to an integer");
}
}
}
private void ProcessConstantNode(XPathNavigator node)
{
string name = "";
string constStr = "";
double constNum = 0;
if (node.MoveToChild("name", ""))
{
name = node.Value.Trim();
node.MoveToParent();
}
if (node.MoveToChild("value", ""))
{
constStr = node.Value.Trim();
if ((constStr.Length != 0) && (constStr[0] != '\"'))
{
constNum = GetConstFromString(constStr);
}
else
{
constNum = 0;
}
node.MoveToParent();
}
// Verify the correctnes of the <constant> tag
if ((name != "") && (constStr != ""))
{
AddItemToMap(m_ConstMap, name, constNum);
}
else
{
throw new Exception(
"ERROR: Constant Definition Incorrect - <name>:" + name +
" <value>:" + constStr);
}
}
private void ProcessTypedefNode(XPathNavigator node)
{
string name = "";
string type = "";
int typeSize = 0; // Size of the item
int typePad = 0; //Size of the largest item to pad to
if (node.MoveToChild("name", ""))
{
name = node.Value.Trim();
node.MoveToParent();
}
if (node.MoveToChild("value", ""))
{
type = node.Value.Trim();
GetSizeFromType(type, out typeSize, out typePad);
node.MoveToParent();
}
// Verify the correctnes of the <typedef> tag
if ((name != "") && (type != ""))
{
AddItemToMap(m_PadMap, name, typePad);
AddItemToMap(m_SizeMap, name, typeSize);
}
else
{
throw new Exception(
"ERROR: Typedef Definition Incorrect - <name>:" + name +
" <value>:" + type);
}
}
private void ProcessEnumerationNode(XPathNavigator node)
{
string name;
double constNum = 0;
var constStr = string.Empty;
if (node.MoveToChild("name", ""))
{
name = node.Value.Trim();
AddItemToMap(m_PadMap, name, 4);
AddItemToMap(m_SizeMap, name, 4);
node.MoveToParent();
}
else
{
throw new Exception("ERROR: Enumeration Definition Incorrect. No <name> tag present.");
}
XPathNodeIterator nodeSet = node.Select("item|enum_item");
while (nodeSet.MoveNext())
{
name = string.Empty;
if ((nodeSet.Current.MoveToChild("name", "")) ||
(nodeSet.Current.MoveToChild("item_name", "")))
{
name = nodeSet.Current.Value.Trim();
nodeSet.Current.MoveToParent();
}
if (nodeSet.Current.MoveToChild("value", ""))
{
constStr = nodeSet.Current.Value.Trim();
constNum = GetConstFromString(constStr);
nodeSet.Current.MoveToParent();
}
// Verify the correctnes of the <enum><item> tag
if ((name != "") && (constStr != ""))
{
AddItemToMap(m_ConstMap, name, constNum);
}
else
{
throw new Exception($"ERROR: Enumeration Item Definition Incorrect - <name>: {name} <value>: {constStr}");
}
}
}
private void ProcessStructureNode(XPathNavigator node)
{
string name;
if (node.MoveToChild("name", ""))
{
name = node.Value.Trim();
node.MoveToParent();
}
else
{
throw new Exception("ERROR: Stucture/Message Definition Incorrect. No <name> tag present.");
}
int maxSize = 0;
int padCount = 0;
uint bitCount = 0; // Used to see how many bits have been processed.
int lastItemSize = 0;
var nodeSet = node.Select("item|struct_item|msg_item");
while (nodeSet.MoveNext())
{
GetItemSize(nodeSet.Current, out int padSize, out int itemSize, out int reps, out uint bits);
if ((lastItemSize != itemSize) || ((bitCount + bits) > (uint)(itemSize * 8)))
{
bitCount = 0; // Size changed or bit rollover
}
if (bitCount == 0)
{
padCount += AddPadding(node, nodeSet.Current, padSize, padCount);
// Set maxSize
if (padSize > maxSize)
{
maxSize = padSize;
}
// Keep up with the pad count
padCount += (itemSize * reps);
}
lastItemSize = itemSize;
bitCount += bits;
}
if (maxSize != 0)
{
// Add final padding
padCount += AddPadding(node, null, maxSize, padCount);
}
AddItemToMap(m_PadMap, name, maxSize);
AddItemToMap(m_SizeMap, name, padCount);
}
private void GetItemSize(XPathNavigator node, out int padSize, out int itemSize, out int reps, out uint bits)
{
string name = "";
if ((node.MoveToChild("name", "")) ||
(node.MoveToChild("item_name", "")))
{
name = node.Value.Trim();
node.MoveToParent();
}
itemSize = -1;
padSize = -1;
reps = 1;
bits = 0;
var nodeSet = node.Select("type");
while (nodeSet.MoveNext())
{
GetSizeFromType(nodeSet.Current.Value.Trim(), out padSize, out itemSize);
}
nodeSet = node.Select("bits");
if (nodeSet.MoveNext())
{
bits = (uint)GetConstFromString(nodeSet.Current.Value.Trim());
}
nodeSet = node.Select("arrayLength|imageWidth|imageHeight");
while (nodeSet.MoveNext())
{
try
{
reps *= (int)GetConstFromString(nodeSet.Current.Value.Trim());
}
catch (Exception e)
{
throw new Exception
(e.Message + " item name = \"" + name + "\", tag = <" +
nodeSet.Current.Name + ">.");
}
}
if ((itemSize == -1) || (padSize == -1))
{
throw new Exception
("ERROR: Item named " + name + "does not contain a <type> tag.");
}
if (bits == 0)
bits = (uint)padSize * 8;
}
private double GetConstFromString(string constStr)
{
if ((constStr.Length > 0) && (constStr[0] == '\''))
{
byte charData = (byte)constStr[1];
constStr = charData.ToString();
}
if (Parse.Try(constStr, out double data) == false)
{
if (Parse.Try(constStr, out int iData) == false)
{
try
{
data = m_ConstMap[constStr];
}
catch
{
throw new Exception("ERROR: ConstantValue - \"" + constStr + "\" does not resolve to a number.");
}
}
else
{
data = (double)iData;
}
}
return data;
}
private void AddItemToMap(Dictionary<string, int> map, string name, int value)
{
if (map.ContainsKey(name))
{
throw new Exception("ERROR: Element " + name + " is defined multiple times.");
}
else
{
map.Add(name, value);
}
}
private void AddItemToMap(Dictionary<string, double> map, string name, double value)
{
if (map.ContainsKey(name))
{
throw new Exception("ERROR: Element " + name + " is defined multiple times.");
}
else
{
map.Add(name, value);
}
}
private void GetSizeFromType(string type, out int typePad, out int typeSize)
{
// Remove all whitespace
type = type.Replace(" ", "");
if ((type == "char") || (type == "unsignedchar"))
{
typePad = 1;
typeSize = 1;
}
else if ((type == "short") || (type == "unsignedshort"))
{
typePad = 2;
typeSize = 2;
}
else if ((type == "unsigned") || (type == "unsignedint") ||
(type == "int") || (type == "float") ||
(type == "boolean") || (type == "address"))
{
typePad = 4;
typeSize = 4;
}
else if ((type == "double") || (type == "longlong") ||
(type == "unsignedlonglong"))
{
typePad = 8;
typeSize = 8;
}
else // The type is complex and has already been defined
{
try
{
typePad = m_PadMap[type];
typeSize = m_SizeMap[type];
}
catch
{
throw new Exception("ERROR: <type> - " + type + " used without being defined.");
}
}
}
private int AddPadding(XPathNavigator ParentElement, XPathNavigator CurrentElement, int padSize, int padCount)
{
int padAdd = 0;
int padTo = padSize;
if (m_Packing < padSize)
{
padTo = m_Packing;
}
if ((padTo != 0) && (padCount % padTo != 0))
{
padAdd = padTo - (padCount % padTo);
InsertPaddingNode(ParentElement, CurrentElement, padAdd);
}
return padAdd;
}
private void InsertPaddingNode(XPathNavigator ParentElement, XPathNavigator CurrentElement, int padAdd)
{
string pad = "<item>" +
"<name>" + Message.PADDING_ITEM_NAME + "</name>" +
"<type>char</type>" +
"<arrayLength>" + padAdd + "</arrayLength>" +
"<instruType>S</instruType>" +
"</item>";
if (CurrentElement != null)
{
CurrentElement.InsertBefore(pad);
}
else // End padding
{
ParentElement.AppendChild(pad);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,600 @@
// **********************************************************************************************************
// MessageData.cs
// 5/18/2022
// 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 System;
using System.Collections.Generic;
using System.IO;
using Raytheon.Instruments.coeCSharp;
namespace Raytheon.Instruments.MessagingUtilities
{
public class MessageData : ICloneable
{
public string FieldName;
public string FieldType;
public string FieldValue;
public string FieldArrayValue;
public string FieldDefaultValue;
public string FieldMaxValue;
public string FieldMinValue;
public string FieldBitValue;
public string FieldInstruType;
public string Variable;
public string MaxOffset;
public string MinOffset;
public string VerifyType;
public bool isSelected;
public bool isArray;
public bool isStructure;
public bool isArrayOfStructures;
public bool isEnum;
public bool usesRegister;
public bool isValid;
public bool useRange;
public int arrayLength;
public uint imageWidth;
public uint imageHeight;
public uint imagePixelSize;
public ulong bitMask;
public bool expanded;
public int depth;
public byte[] imageBuffer;
public uint imageBufferSize;
public MessageData[] MessageArray;
public delegate coe.Status ReadImageDelegate
(
string filename,
uint columns,
uint rows,
uint pixel_size,
byte[] buffer
);
private MessageXmlDocument m_Icd;
internal int m_BitCounter = 0; // used to calculate the bit mask
internal static Dictionary<string, ReadImageDelegate> m_ReadFunctions = null;
private MessageData() { }
private MessageData(MessageXmlDocument Icd)
{
FieldName = null;
FieldType = null;
FieldValue = null;
FieldArrayValue = null;
FieldDefaultValue = null;
FieldMaxValue = null;
FieldMinValue = null;
FieldBitValue = null;
Variable = null;
MaxOffset = null;
MinOffset = null;
VerifyType = null;
isSelected = false;
isArray = false;
isStructure = false;
isArrayOfStructures = false;
usesRegister = false;
useRange = false;
arrayLength = 0;
imageWidth = 0;
imageHeight = 0;
imagePixelSize = 0;
bitMask = 0;
expanded = false;
depth = 0;
imageBufferSize = 0;
imageBuffer = null;
m_Icd = Icd;
}
public MessageData(string fieldname,
string fieldtype,
string fieldvalue,
string fielddefaultvalue,
MessageXmlDocument Icd) :
this(Icd)
{
FieldName = fieldname;
FieldType = fieldtype;
FieldValue = fieldvalue;
SetInstruType(null);
SetDefaultValue(fielddefaultvalue);
}
public MessageData(string fieldname,
string fieldtype,
string fieldvalue,
string fielddefaultvalue,
string fieldmaxvalue,
string fieldminvalue,
MessageXmlDocument Icd) :
this(fieldname, fieldtype, fieldvalue, fielddefaultvalue, Icd)
{
SetMaxValue(fieldmaxvalue);
SetMinValue(fieldminvalue);
}
public string FormattedValue
{
get { return FormatValue(FieldValue); }
}
public string FormattedMinValue
{
get { return FormatValue(FieldMinValue); }
}
public string FormattedMaxValue
{
get { return FormatValue(FieldMaxValue); }
}
public static string ImageFileReadTypes
{
get
{
string fileTypes = "";
if (m_ReadFunctions == null) return null;
foreach (string type in m_ReadFunctions.Keys)
{
if (fileTypes != "")
fileTypes += "|";
fileTypes += type.ToUpper() + " files (*." + type.ToLower() + ")|*." + type.ToLower();
}
return fileTypes;
}
}
public void AddReadExtension(string extension, ReadImageDelegate readFunc)
{
if (m_ReadFunctions == null)
m_ReadFunctions = new Dictionary<string, ReadImageDelegate>();
if (m_ReadFunctions.ContainsKey(extension))
m_ReadFunctions[extension] = readFunc;
else
m_ReadFunctions.Add(extension, readFunc);
}
public void UpdateImage()
{
if (FieldInstruType == "P")
{
if (File.Exists(FieldValue))
{
string extension = FieldValue.Substring(FieldValue.LastIndexOf(".") + 1);
m_ReadFunctions[extension](FieldValue,
imageWidth,
imageHeight,
imagePixelSize,
imageBuffer);
}
else
{
// TODO add error message
//MessageBox.Show("Unable to open file " + FieldValue +
// " to populate " + FieldName,
// "File Read Error",
// MessageBoxButtons.OK,
// MessageBoxIcon.Error);
FieldValue = "";
for (int i = 0; i < imageBuffer.Length; i++)
{
imageBuffer[i] = 0;
}
}
}
}
public void SetDefaultValue(string fieldDefaultValue)
{
// Initialize uninitialized value
if (fieldDefaultValue == null)
{
fieldDefaultValue = "";
}
if ((FieldType == "char") && (fieldDefaultValue.Contains("\"")))
{
FieldInstruType = "S";
}
FieldDefaultValue = RemoveCharFromString(fieldDefaultValue, '\"');
}
public void SetMaxValue(string fieldmaxvalue)
{
if (fieldmaxvalue == null) return; /* Bad argument */
if ((FieldType == "char") && (fieldmaxvalue.Contains("\"")))
{
FieldInstruType = "S";
}
FieldMaxValue = RemoveCharFromString(fieldmaxvalue, '\"');
}
public void SetMinValue(string fieldminvalue)
{
if (fieldminvalue == null) return; /* Bad argument */
if ((FieldType == "char") && (fieldminvalue.Contains("\"")))
{
FieldInstruType = "S";
}
FieldMinValue = RemoveCharFromString(fieldminvalue, '\"');
}
public void SetBitValue(int bits)
{
int size = (int)Message.GetTypeSize(FieldType, isEnum);
// Determine the bitMask
if (bits == 0)
{
m_BitCounter = 0;
FieldBitValue = null;
}
else
{
FieldBitValue = bits.ToString();
// If bits overflow across the type boundary, then
// they start at the next boundary.
//
// MSDN :
// "Note that nYear is 8 bits long and would overflow
// the word boundary of the declared type, unsigned short.
// Therefore, it is begun at the beginning of a
// new unsigned short."
if (m_BitCounter + bits > size * 8)
{
m_BitCounter = 0;
}
// 2^bits-1 will give a bit mask with bit# of 1's
// ex: bits = 5, bitMask = 11111
bitMask = (ulong)Math.Pow(2, (double)bits) - 1;
// We must slide the bitMask left to put it in place
bitMask <<= m_BitCounter;
m_BitCounter += bits;
// If we have used all the bits in the type that was defined, then
// restart the counter
if (m_BitCounter == size * 8)
m_BitCounter = 0;
}
if (bitMask == 0xffffff)
{
bitMask = 0;
}
}
public void SetArraySize(int size)
{
char result;
arrayLength = size; // Save the size
if (!isArray && !isStructure)
{
// Don't handle strings as arrays
if ((FieldInstruType != "S") && (FieldInstruType != "P"))
{
isArray = true;
MessageArray = new MessageData[size];
// If the field type is char or unsigned char and the default value
// exists and is a string then write one char of the string to
// each element of the array
if ((FieldType == "char" || FieldType == "unsigned char") &&
FieldDefaultValue != null &&
!Parse.Try(FieldDefaultValue, out result))
{
for (uint index = 0; index < size; index++)
{
//Only the elements that are required to spell out the string should
//receive default values.
if (index < FieldDefaultValue.Length)
{
MessageArray[index] = new MessageData(FieldName + "[" + index + "]",
FieldType, FieldValue, FieldDefaultValue[(int)index].ToString(),
FieldMaxValue, FieldMinValue, m_Icd);
MessageArray[index].FieldInstruType = FieldInstruType;
}
else
{
MessageArray[index] = new MessageData(FieldName + "[" + index + "]",
FieldType, FieldValue, "0",
FieldMaxValue, FieldMinValue, m_Icd);
MessageArray[index].FieldInstruType = FieldInstruType;
}
MessageArray[index].depth = depth + 1;
}
}
else
{
for (uint index = 0; index < size; index++)
{
MessageArray[index] = new MessageData(FieldName + "[" + index + "]",
FieldType, FieldValue, FieldDefaultValue, FieldMaxValue,
FieldMinValue, m_Icd);
MessageArray[index].FieldInstruType = FieldInstruType;
MessageArray[index].depth = depth + 1;
}
}
}
}
}
public void SetStructureSize(int size)
{
if (!isArray && !isStructure)
{
isStructure = true;
MessageArray = new MessageData[size];
for (uint index = 0; index < size; index++)
{
MessageArray[index] = new MessageData(FieldName + ".", null, null, null, m_Icd);
}
}
}
internal void SetInstruType(string Type)
{
if (Type != null)
{
FieldInstruType = Type;
// Ensure 'S' is used properly
if ((Type == "S") && (FieldType != "char"))
{
return; /* << EXIT >> */
}
}
else
{
if ((FieldType != null) &&
((FieldType.Trim() == "float") || (FieldType.Trim() == "double")))
{
FieldInstruType = "F";
}
else
{
FieldInstruType = "I";
}
}
}
internal void SetPixelSize()
{
// Only do this if the user did not define a size
if (imagePixelSize == 0)
{
switch (FieldType)
{
case "char":
case "unsigned char":
case "unsignedchar":
imagePixelSize = 1;
break;
case "short":
case "unsigned short":
case "unsignedshort":
imagePixelSize = 2;
break;
case "int":
case "unsigned int":
case "unsignedint":
case "unsigned":
case "boolean":
case "address":
case "float":
imagePixelSize = 4;
break;
case "double":
case "long long":
case "longlong":
case "unsigned long long":
case "unsignedlonglong":
imagePixelSize = 8;
break;
default:
if (isEnum)
{
imagePixelSize = 4;
}
else // Error case
{
imagePixelSize = 1;
}
break;
}
}
}
private string FormatValue(string Value)
{
if ((Value == null) || (Value == ""))
{
return "";
}
else // Value exists
{
if (isEnum == false)
{
if (FieldInstruType == "I")
{
// This is being represented as a decimal
if (Parse.Try(Value, out long dec) == true)
{
return dec.ToString();
}
}
else if (FieldInstruType == "F")
{
// This is being represented as floating point
if (Parse.Try(Value, out double flt) == true)
{
return flt.ToString();
}
}
else if ((FieldInstruType == "X") ||
(FieldInstruType == "B") ||
(FieldInstruType == "T"))
{
// This is being represented as a hexadecimal value
if (Parse.Try(Value, out long hex) == true)
{
return "0x" + hex.ToString("X");
}
}
else if (FieldInstruType == "N")
{
// This is being represented as a binary number
if (Parse.Try(Value, out long bin) == true)
{
return Convert.ToString(bin, 2) + "b";
}
}
// else InstruType == 'S' or 'P' or anything else return the value
}
else // This value is an enumeration
{
Dictionary<string, string> enums = m_Icd.GetEnumerations(FieldType);
if (enums.ContainsValue(Value) == true)
{
foreach (KeyValuePair<string, string> pair in enums)
{
if (pair.Value.Trim() == Value.Trim())
{
return pair.Key;
}
}
}
}
}
return Value; // If nothing above applies, simply return the value string
}
private String RemoveCharFromString(String str, char c)
{
if (str == null) return null; // Handle null case
int index = str.IndexOf(c);
while (index != -1)
{
str = str.Remove(index, 1);
index = str.IndexOf(c);
}
return str;
}
#region ICloneable Members
public object Clone()
{
MessageData clone = new MessageData();
clone.FieldName = FieldName;
clone.FieldType = FieldType;
clone.FieldValue = FieldValue;
clone.FieldArrayValue = FieldArrayValue;
clone.FieldDefaultValue = FieldDefaultValue;
clone.FieldMaxValue = FieldMaxValue;
clone.FieldMinValue = FieldMinValue;
clone.FieldBitValue = FieldBitValue;
clone.FieldInstruType = FieldInstruType;
clone.Variable = Variable;
clone.MaxOffset = MaxOffset;
clone.MinOffset = MinOffset;
clone.VerifyType = VerifyType;
clone.isSelected = isSelected;
clone.isArray = isArray;
clone.isStructure = isStructure;
clone.isArrayOfStructures = isArrayOfStructures;
clone.isEnum = isEnum;
clone.usesRegister = usesRegister;
clone.isValid = isValid;
clone.useRange = useRange;
clone.arrayLength = arrayLength;
clone.bitMask = bitMask;
clone.expanded = expanded;
clone.depth = depth;
clone.m_Icd = m_Icd;
clone.imageWidth = imageWidth;
clone.imageHeight = imageHeight;
clone.imagePixelSize = imagePixelSize;
clone.imageBufferSize = imageBufferSize;
if (imageBufferSize > 0)
{
clone.imageBuffer = new byte[imageBufferSize];
imageBuffer.CopyTo(clone.imageBuffer, 0);
}
if (MessageArray == null)
{
clone.MessageArray = null;
}
else
{
clone.MessageArray = new MessageData[MessageArray.Length];
for (int i = 0; i < MessageArray.Length; i++)
{
clone.MessageArray[i] = (MessageData)MessageArray[i].Clone();
}
}
return clone;
}
#endregion
}
}

View File

@@ -0,0 +1,426 @@
// **********************************************************************************************************
// MessageXmlDocument.cs
// 5/18/2022
// 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 System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Diagnostics;
using System.Threading;
using NLog;
namespace Raytheon.Instruments.MessagingUtilities
{
public class MessageXmlDocument : XmlDocument
{
private readonly ILogger _logger;
private readonly string _XmlFileName;
private string BuiltXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><?xml-stylesheet type=\"text/xsl\" ?><interface>";
private uint m_MaxMsgSize = 0;
private readonly List<string> m_IncludeList;
private MessageXmlDocument() : base()
{
}
public MessageXmlDocument(string Pathname,
ILogger logger) :
base()
{
_logger = logger;
_XmlFileName = Pathname;
m_IncludeList = new List<string>();
RecurseProcessing(Pathname);
BuiltXML = string.Concat(BuiltXML, "</interface>");
BytePackingXml addPacking = new BytePackingXml(BuiltXML);
LoadXml(addPacking.OuterXml);
}
public Dictionary<string, string> GetEnumerations(string Type)
{
Dictionary<string, string> enumList = new Dictionary<string, string>();
// Get XML nodes to parse the XML ICD document
XPathNavigator Node = CreateNavigator();
XPathNodeIterator Nodeset = Node.Select("interface/enum/name");
while (Nodeset.MoveNext())
{
// Find the enumeration with the name of the type
if (Nodeset.Current.Value.Trim().Equals(Type.Trim()))
{
// Find all the enumeration items
XPathNavigator enumNode = Nodeset.Current.Clone();
while (enumNode.MoveToNext())
{
if (enumNode.Name.Trim().Equals("item") ||
enumNode.Name.Trim().Equals("enum_item"))
{
string name = null;
string value = null;
// Find all name nodes
XPathNavigator childNode = enumNode.Clone();
childNode.MoveToFirstChild();
do
{
if (childNode.Name.Trim().Equals("name"))
{
name = childNode.Value.Trim();
}
else if (childNode.Name.Trim().Equals("item_name"))
{
name = childNode.Value.Trim();
}
if (childNode.Name.Trim().Equals("value"))
{
value = childNode.Value.Trim();
}
// Once we find the name & value, add it to the list
if ((name != null) && (value != null))
{
enumList.Add(name, value);
break;
}
} while (childNode.MoveToNext());
}
}
break; // We found the enumeration we wanted
}
}
return enumList;
}
private void RecurseProcessing(string pathName)
{
string directory;
string IncludePathname;
XPathNodeIterator nodeset;
// Only process each file once
pathName = pathName.Replace('/', '\\');
if (m_IncludeList.Contains(pathName))
{
return; // This file has already been processed
}
else
{
m_IncludeList.Add(pathName);
}
_logger.Log(LogLevel.Info, $"Loading File: {pathName}");
XPathDocument document = new XPathDocument(pathName);
XPathNavigator navigator = document.CreateNavigator();
// Verify this is a COE XML ICD
nodeset = navigator.Select("/interface");
if (nodeset.Count == 0)
{
// This is not an XML ICD
throw new Exception($"Invalid COE XML Format. Unable to process {pathName}" +
"\nEnsure this is a properly formatted ICD.");
}
nodeset = navigator.Select("/interface/include/file");
while (nodeset.MoveNext())
{
try
{
directory = DirectoryOf(pathName);
}
catch
{
directory = ".\\";
}
IncludePathname = nodeset.Current.Value.Trim();
if ((!IncludePathname.StartsWith("\\")) && (!IncludePathname.Contains(":")))
{
while (IncludePathname.StartsWith("."))
{
if ((IncludePathname.StartsWith("..\\")) || (IncludePathname.StartsWith("../")))
{
directory = DirectoryOf(directory);
IncludePathname = IncludePathname.Remove(0, 3);
}
else if ((IncludePathname.StartsWith(".\\")) || (IncludePathname.StartsWith("./")))
{
IncludePathname = IncludePathname.Remove(0, 2);
}
}
IncludePathname = string.Concat(directory, "\\", IncludePathname);
}
RecurseProcessing(IncludePathname);
}
nodeset = navigator.Select("/interface/packing|/interface/typedef|/interface/constant|interface/enum|/interface/structure|/interface/message");
while (nodeset.MoveNext())
{
string item = nodeset.Current.OuterXml;
int index;
while ((index = item.IndexOf("<description>")) != -1)
{
item = item.Remove(index, item.IndexOf("</description>") + 14 - index);
}
while ((index = item.IndexOf("<!--")) != -1)
{
item = item.Remove(index, item.IndexOf("-->") + 3 - index);
}
while (item.IndexOf("> ") != -1)
{
item = item.Replace("> ", ">");
}
while (item.IndexOf(" <") != -1)
{
item = item.Replace(" <", "<");
}
//_logger.Log(LogLevel.Trace, $"Loading Node :\n{item}");
Thread.Sleep(1);
BuiltXML = string.Concat(BuiltXML, item);
}
}
private string DirectoryOf(string Pathname)
{
return Pathname.Remove(Pathname.LastIndexOf("\\"));
}
//
// From the XML document, the definition of a single message can be identified
// from the Message Name and returned as an XML string.
//
public string XmlFileName
{
get
{
return _XmlFileName;
}
}
public string GetMessage(string messageName)
{
string message;
messageName = messageName.Trim();
_logger.Log(LogLevel.Info, $"Searching for message : {messageName}");
try
{
message = SelectSingleNode($"/interface/message[name='{messageName}']").OuterXml;
message = TranslateValue(message);
_logger.Log(LogLevel.Trace, $"Found by name: {message}");
}
catch
{
message = null;
_logger.Log(LogLevel.Error, "Message not found");
}
return message;
}
//
// From the XML document, the definition of a single message can be identified
// from the Message Label and returned as an XML string.
//
public string GetMessageFromLabel(string messageLabel)
{
string message;
string msgLabel = "";
if (Parse.Try(messageLabel, out int label) == true)
{
msgLabel = label.ToString();
}
_logger.Log(LogLevel.Info, $"Searching for message: {msgLabel}");
try
{
// Search by message label
message = SelectSingleNode($"/interface/message[label='{msgLabel}']").OuterXml;
message = TranslateValue(message);
_logger.Log(LogLevel.Trace, $"Found by label: {message}");
}
catch
{
try
{
// Search by instruLabel
message = SelectSingleNode($"/interface/message[instruLabel='{messageLabel}']").OuterXml;
message = TranslateValue(message);
_logger.Log(LogLevel.Trace, $"Found by instrument Label: {message}");
}
catch
{
message = null;
_logger.Log(LogLevel.Error, "Message not found");
}
}
return message;
}
//
// From the XML document, the definition of a single message can be identified
// from the Message InstruLabel and returned as an XML string.
//
public string GetMessageFromInstruLabel(string messageInstruLabel)
{
string message;
messageInstruLabel = messageInstruLabel.Trim();
_logger.Log(LogLevel.Info, $"Searching for message: {messageInstruLabel}");
try
{
message = SelectSingleNode($"/interface/message[instruLabel='{messageInstruLabel}']").OuterXml;
message = TranslateValue(message);
_logger.Log(LogLevel.Trace, $"Found by instrument label: {message}");
}
catch
{
message = null;
_logger.Log(LogLevel.Error, "Message not found");
}
return message;
}
public uint GetLargestMessageSize()
{
lock (this)
{
// return the max message size if we have already calculated it
if (m_MaxMsgSize != 0)
{
return m_MaxMsgSize;
}
else
{
DateTime t1 = DateTime.Now;
XPathNavigator navigator = CreateNavigator();
XPathNodeIterator nodeset = navigator.Select("/interface/message/name");
while (nodeset.MoveNext())
{
Message msg = new Message(nodeset.Current.Value.Trim(), this);
uint msgSize = msg.GetMessageSize();
if (msgSize > m_MaxMsgSize)
{
m_MaxMsgSize = msgSize;
}
}
DateTime t2 = DateTime.Now;
TimeSpan duration = t2 - t1;
Debug.WriteLine("Max Msg Size Algorithm Time = " + duration);
}
}
return m_MaxMsgSize;
}
public uint GetMessageSize(string MsgName)
{
uint msg_size = 0;
lock (this)
{
XPathNavigator navigator = CreateNavigator();
XPathNodeIterator nodeset = navigator.Select("/interface/message/name");
while (nodeset.MoveNext())
{
if (MsgName == nodeset.Current.Value.Trim())
{
Message msg = new Message(nodeset.Current.Value.Trim(), this);
msg_size = msg.GetMessageSize();
}
}
}
return msg_size;
}
//
// Since the XML message definitions contain the definitions of all the enumerations and constants,
// this object is the only one containing the knowledge to interpret strings using enumerations and/or
// constants. This method will substitute enumerations and constants with their respective base values
// in a specified string.
//
public string TranslateValue(string Value)
{
XPathNavigator navigator = CreateNavigator();
XPathNavigator position;
string NewValue = Value;
//
// Substitute enumeration
//
try
{
position = navigator.SelectSingleNode("/interface/enum/item[name='" + NewValue + "']");
if (position == null)
{
position = navigator.SelectSingleNode("/interface/enum/item[item_name='" + NewValue + "']");
}
if (position != null)
{
position.MoveToChild("value", "");
NewValue = position.Value;
}
//
// Substitute constants
//
position = navigator.SelectSingleNode("/interface/constant[name='" + NewValue + "']");
if (position != null)
{
NewValue = position.Value;
_logger.Log(LogLevel.Info, "Translating field value : " + Value + " -> " + NewValue);
}
}
catch (Exception e)
{
_logger.Error(e.Message);
}
return NewValue;
}
}
}

View File

@@ -0,0 +1,130 @@
// **********************************************************************************************************
// OeMessage.cs
// 5/18/2022
// 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 Raytheon.Instruments.coeCSharp;
using System;
namespace Raytheon.Instruments.MessagingUtilities
{
public class OeMessage : coeMessage
{
public Message XmlMessage
{
get { return m_Msg; }
set
{
m_Msg = value;
Label = value.Label;
Size = value.GetMessageSize();
}
}
public new string Label
{
get { return base.Label.ToString(); }
set
{
if (Parse.Try(value, out uint label) == true)
{
base.Label = label;
}
else
{
throw new Exception("OeMessage: Label does not parse to an Unsigned Integer");
}
}
}
public new string Domain
{
get { return base.Domain.ToString(); }
set
{
if (Parse.Try(value, out uint domain) == true)
{
base.Domain = domain;
}
else
{
throw new Exception("OeMessage: Domain does not parse to an Unsigned Integer");
}
}
}
public OeMessage() : base(0) { m_Msg = null; }
public OeMessage(int size) : base(size) { m_Msg = null; }
public OeMessage(Message msg)
: base(0)
{
XmlMessage = msg;
}
public OeMessage(Message msg, int msgSize) : base(msgSize)
{
XmlMessage = msg;
}
override public void Serialize()
{
if (m_Msg != null)
{
byte[] serializedBuffer = m_Msg.serialize();
if (serializedBuffer.Length > BufferSize)
{
BufferSize = serializedBuffer.Length;
}
Size = (uint)serializedBuffer.Length;
copyToMessageBuffer(serializedBuffer);
Domain = m_Msg.Domain;
}
}
override public void Deserialize()
{
if (m_Msg != null)
{
// Get sending time and pass it to the XmlMessage object;
GetSendTime(out ulong sendSec, out uint sendSecFrac);
m_Msg.SendSecond = sendSec;
m_Msg.SendSecondFraction = sendSecFrac;
m_Msg.Domain = Domain;
byte[] receiveBuffer = copyFromMessageBuffer();
if (receiveBuffer != null)
{
m_Msg.deserialize(receiveBuffer);
}
}
}
Message m_Msg = null;
}
}

View File

@@ -0,0 +1,377 @@
// **********************************************************************************************************
// Parse.cs
// 5/18/2022
// 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 System;
namespace Raytheon.Instruments.MessagingUtilities
{
public class Parse
{
public static bool Try(string value, out byte result)
{
result = 0;
if (value == null)
return false; // Handle bad argument
bool passed = byte.TryParse(value, out result);
if (passed == false)
{
if (value.StartsWith("0x") == true)
{
value = value.Substring(2, value.Length - 2);
passed = byte.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out result);
}
else if (value.EndsWith("b") == true)
{
value = value.TrimEnd("b".ToCharArray());
try
{
result = Convert.ToByte(value, 2);
passed = true;
}
catch
{
passed = false;
}
}
else
{
passed = true; // Handle Boolean TYPES
if (value.Trim().ToUpper().Equals("TRUE"))
result = 1;
else if (value.Trim().ToUpper().Equals("FALSE"))
result = 0;
else
passed = false;
}
}
return passed;
}
public static bool Try(string value, out decimal result)
{
result = 0;
if (value == null)
return false; // Handle bad argument
bool passed = decimal.TryParse(value, System.Globalization.NumberStyles.Any, null, out result);
if (passed == false)
{
if (value.StartsWith("0x") == true)
{
value = value.Substring(2, value.Length - 2);
passed = int.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out int hexResult);
if (passed)
{
result = hexResult;
}
}
}
return passed;
}
public static bool Try(string value, out short result)
{
result = 0;
if (value == null)
return false; // Handle bad argument
bool passed = short.TryParse(value, out result);
if (passed == false)
{
if (value.StartsWith("0x") == true)
{
value = value.Substring(2, value.Length - 2);
passed = short.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out result);
}
else if (value.EndsWith("b") == true)
{
value = value.TrimEnd("b".ToCharArray());
try
{
result = Convert.ToInt16(value, 2);
passed = true;
}
catch
{
passed = false;
}
}
else
{
passed = true; // Handle Boolean TYPES
if (value.Trim().ToUpper().Equals("TRUE"))
result = 1;
else if (value.Trim().ToUpper().Equals("FALSE"))
result = 0;
else
passed = false;
}
}
return passed;
}
public static bool Try(string value, out ushort result)
{
result = 0;
if (value == null)
return false; // Handle bad argument
bool passed = ushort.TryParse(value, out result);
if (passed == false)
{
if (value.StartsWith("0x") == true)
{
value = value.Substring(2, value.Length - 2);
passed = ushort.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out result);
}
else if (value.EndsWith("b") == true)
{
value = value.TrimEnd("b".ToCharArray());
try
{
result = Convert.ToUInt16(value, 2);
passed = true;
}
catch
{
passed = false;
}
}
else
{
passed = true; // Handle Boolean TYPES
if (value.Trim().ToUpper().Equals("TRUE"))
result = 1;
else if (value.Trim().ToUpper().Equals("FALSE"))
result = 0;
else
passed = false;
}
}
return passed;
}
public static bool Try(string value, out int result)
{
result = 0;
if (value == null)
return false; // Handle bad argument
bool passed = int.TryParse(value, System.Globalization.NumberStyles.Any, null, out result);
if (passed == false)
{
if (value.StartsWith("0x") == true)
{
value = value.Substring(2, value.Length - 2);
passed = int.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out result);
}
else if (value.EndsWith("b") == true)
{
value = value.TrimEnd("b".ToCharArray());
try
{
result = Convert.ToInt32(value, 2);
passed = true;
}
catch
{
passed = false;
}
}
else
{
passed = true; // Handle Boolean TYPES
if (value.Trim().ToUpper().Equals("TRUE"))
result = 1;
else if (value.Trim().ToUpper().Equals("FALSE"))
result = 0;
else
passed = false;
}
}
return passed;
}
public static bool Try(string value, out uint result)
{
result = 0;
if (value == null)
return false; // Handle bad argument
bool passed = uint.TryParse(value, out result);
if (passed == false)
{
if (value.StartsWith("0x") == true)
{
value = value.Substring(2, value.Length - 2);
passed = uint.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out result);
}
else if (value.EndsWith("b") == true)
{
value = value.TrimEnd("b".ToCharArray());
try
{
result = Convert.ToUInt32(value, 2);
passed = true;
}
catch
{
passed = false;
}
}
else
{
passed = true; // Handle Boolean TYPES
if (value.Trim().ToUpper().Equals("TRUE"))
result = 1;
else if (value.Trim().ToUpper().Equals("FALSE"))
result = 0;
else
passed = false;
}
}
return passed;
}
public static bool Try(string value, out long result)
{
result = 0;
if (value == null || value == "")
return false; // Handle bad argument
bool passed = long.TryParse(value, out result);
if (passed == false)
{
if (value.StartsWith("0x") == true)
{
value = value.Substring(2, value.Length - 2);
passed = long.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out result);
}
else if (value.EndsWith("b") == true)
{
value = value.TrimEnd("b".ToCharArray());
try
{
result = Convert.ToInt64(value, 2);
passed = true;
}
catch
{
passed = false;
}
}
else
{
passed = true; // Handle Boolean TYPES
if (value.Trim().ToUpper().Equals("TRUE"))
result = 1;
else if (value.Trim().ToUpper().Equals("FALSE"))
result = 0;
else
passed = false;
}
}
return passed;
}
public static bool Try(string value, out ulong result)
{
result = 0;
if (value == null)
return false; // Handle bad argument
bool passed = ulong.TryParse(value, out result);
if (passed == false)
{
if (value.StartsWith("0x") == true)
{
value = value.Substring(2, value.Length - 2);
passed = ulong.TryParse(value, System.Globalization.NumberStyles.HexNumber, null, out result);
}
else if (value.EndsWith("b") == true)
{
value = value.TrimEnd("b".ToCharArray());
try
{
result = Convert.ToUInt64(value, 2);
passed = true;
}
catch
{
passed = false;
}
}
else
{
passed = true; // Handle Boolean TYPES
if (value.Trim().ToUpper().Equals("TRUE"))
result = 1;
else if (value.Trim().ToUpper().Equals("FALSE"))
result = 0;
else
passed = false;
}
}
return passed;
}
public static bool Try(string value, out char result)
{
return char.TryParse(value, out result);
}
public static bool Try(string value, out float result)
{
if (value.EndsWith("f") == true)
value = value.TrimEnd("f".ToCharArray());
return float.TryParse(value, System.Globalization.NumberStyles.Any, null, out result);
}
public static bool Try(string value, out double result)
{
if (value.EndsWith("f") == true)
value = value.TrimEnd("f".ToCharArray());
return double.TryParse(value, System.Globalization.NumberStyles.Any, null, out result);
}
}
}

View File

@@ -0,0 +1,329 @@
// **********************************************************************************************************
// XmlMbitParser.cs
// 6/6/2022
// 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 System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace Raytheon.Instruments.XmlUtilities
{
public class XmlMbitParser
{
private readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
private readonly Dictionary<string, XmlParser.CommonXmlElements> _commonElements = new Dictionary<string, XmlParser.CommonXmlElements>(StringComparer.InvariantCultureIgnoreCase);
// store messages defined in xml files
private readonly List<XmlParser.XmlMbitMessage> _mbitMessages = new List<XmlParser.XmlMbitMessage>();
// store duplicate messages for diagnostic purposes
private readonly Dictionary<string, List<string>> _duplicateMbitMessages = new Dictionary<string, List<string>>();
// store each enumeration type and its associate key/value pairs
private readonly Dictionary<string, XmlParser.XmlEnumeration> _xmlEnums = new Dictionary<string, XmlParser.XmlEnumeration>(StringComparer.InvariantCultureIgnoreCase);
// store duplicate enumerations for diagnostic purposes
private readonly Dictionary<string, List<string>> _duplicateEnums = new Dictionary<string, List<string>>();
// store each structure type and its associated data members
private readonly Dictionary<string, XmlParser.XmlStructure> _xmlStructures = new Dictionary<string, XmlParser.XmlStructure>(StringComparer.InvariantCultureIgnoreCase);
// store duplicate structures for diagnostic purposes
private readonly Dictionary<string, List<string>> _duplicateStructures = new Dictionary<string, List<string>>();
// look up table for constants, the key is the constant name. A constant name can be defined in more than one namespace and have different values
private ILookup<string, XmlParser.XmlConstant> _xmlConstantsLookUpByConstantName = null;
// look up table for constants, the key is the namespace in which the constant is defined. A constant name can be defined in more than one namespace and have different values
private ILookup<string, XmlParser.XmlConstant> _xmlConstantsLookUpByNameSpace = null;
// store duplicate constants for diagnostic purposes
private readonly Dictionary<string, List<string>> _duplicateConstants = new Dictionary<string, List<string>>();
// store names of files that contain data types that we need to generate
public List<string> m_dataTypeFilesToBeGenerated = new List<string>();
/// <summary>
/// Parse XML files from the path folder
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public bool ParseXmlFiles(string path)
{
bool isSuccessful = true;
string xmlNamespace = string.Empty;
List<XmlParser.XmlConstant> constantList = new List<XmlParser.XmlConstant>();
if (!Directory.Exists(path))
{
_logger.Error($"Path {path} not found");
isSuccessful = false;
return isSuccessful;
}
string[] files = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);
List<string> dataTypeFiles = new List<string>(files.ToList());
foreach (string xmlFile in dataTypeFiles)
{
XPathDocument doc = null;
int prevEnumCount = _xmlEnums.Count;
int prevStructureCount = _xmlStructures.Count;
int prevMessageCount = _mbitMessages.Count;
int prevConstantCount = constantList.Count;
List<string> comments = new List<string>();
try
{
XmlReaderSettings readerSettings = new XmlReaderSettings()
{
// tells the xmlreader to ignore comment in XML file
IgnoreComments = true
};
using (XmlReader reader = XmlReader.Create(xmlFile, readerSettings))
{
// load the XML file
doc = new XPathDocument(reader);
}
XPathNavigator nav = doc.CreateNavigator();
xmlNamespace = Path.GetFileNameWithoutExtension(xmlFile);
_commonElements[xmlNamespace] = new XmlParser.CommonXmlElements();
nav.MoveToRoot();
try
{
_logger.Info($"Parsing {Path.GetFileName(xmlFile)}");
if (nav.MoveToFirstChild())
{
do
{
if (string.Equals(nav.Name, "interface", StringComparison.OrdinalIgnoreCase))
{
if (nav.MoveToFirstChild())
{
do
{
if (!XmlParser.GetCommonElementsFromXml(nav, _commonElements[xmlNamespace]))
{
if (string.Equals(nav.Name, "enum", StringComparison.OrdinalIgnoreCase))
{
XmlParser.GetEnumeration(nav, xmlNamespace, _xmlEnums, _duplicateEnums);
}
else if (string.Equals(nav.Name, "structure", StringComparison.OrdinalIgnoreCase))
{
XmlParser.GetStructure(nav, xmlNamespace, _xmlStructures, comments, _duplicateStructures);
comments.Clear();
}
else if (string.Equals(nav.Name, "constant", StringComparison.OrdinalIgnoreCase))
{
XmlParser.GetConstant(nav, xmlNamespace, constantList, _duplicateConstants);
}
else if (string.Equals(nav.Name, "message", StringComparison.OrdinalIgnoreCase))
{
XmlParser.GetMbitMessage(nav, xmlNamespace, _mbitMessages, _duplicateMbitMessages);
}
else if (string.Equals(nav.Name, "comment", StringComparison.OrdinalIgnoreCase))
{
comments.Add(nav.Value.Trim());
}
else if (nav.Name.Length > 0)
{
throw new XmlParsingException("Unknown element \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
}
} while (nav.MoveToNext());
}
}
} while (nav.MoveToNext());
}
}
catch (XmlParsingException ex)
{
string message = "File : " + xmlFile + "\n" + ex.Message;
throw new Exception(message);
}
}
catch (Exception e)
{
_logger.Error(e);
isSuccessful = false;
}
if (isSuccessful)
{
_logger.Info(" - SUCCESS");
_logger.Info("Results:");
_logger.Info($"Constants: {constantList.Count - prevConstantCount}");
_logger.Info($"Enumerations: {_xmlEnums.Count - prevEnumCount}");
_logger.Info($"Structures: {_xmlStructures.Count - prevStructureCount}");
_logger.Info($"Messages: {_mbitMessages.Count - prevMessageCount}");
}
else
{
_logger.Warn(" - FAIL");
break;
}
}
if (constantList.Count > 0)
{
// we want to create a look up table from a list of constants
// the key for this table will be the constant name
_xmlConstantsLookUpByConstantName = constantList.ToLookup(item => item.name);
// we want to create a look up table from a list of constants
// the key for this table will be the namespace
_xmlConstantsLookUpByNameSpace = constantList.ToLookup(item => item.nameSpace);
}
if (_duplicateMbitMessages.Count > 0 || _duplicateConstants.Count > 0 || _duplicateEnums.Count > 0 || _duplicateStructures.Count > 0)
{
StreamWriter writer = null;
FileStream fs = null;
bool firstLineInFileAllocated = false;
string textToBeWrittenToFile = string.Empty;
string diagnosticFile = Path.Combine(path, "diagnostics.txt");
_logger.Info("Generating diagnostic information...");
foreach (KeyValuePair<string, List<string>> dictItem in _duplicateMbitMessages)
{
if (!firstLineInFileAllocated)
firstLineInFileAllocated = true;
else
textToBeWrittenToFile += "\r\n\r\n";
textToBeWrittenToFile += "Duplicate definition for message \"" + dictItem.Key + "\" found in the following files: ";
foreach (string listItem in dictItem.Value)
{
textToBeWrittenToFile += "\r\n" + GetCodeIndentation(1) + listItem;
}
}
foreach (KeyValuePair<string, List<string>> dictItem in _duplicateStructures)
{
if (!firstLineInFileAllocated)
firstLineInFileAllocated = true;
else
textToBeWrittenToFile += "\r\n\r\n";
textToBeWrittenToFile += "Duplicate definition for structure \"" + dictItem.Key + "\" found in the following files: ";
foreach (string listItem in dictItem.Value)
{
textToBeWrittenToFile += "\r\n" + GetCodeIndentation(1) + listItem;
}
}
foreach (KeyValuePair<string, List<string>> dictItem in _duplicateEnums)
{
if (!firstLineInFileAllocated)
firstLineInFileAllocated = true;
else
textToBeWrittenToFile += "\r\n\r\n";
textToBeWrittenToFile += "Duplicate definition for enum \"" + dictItem.Key + "\" found in the following files: ";
foreach (string listItem in dictItem.Value)
{
textToBeWrittenToFile += "\r\n" + GetCodeIndentation(1) + listItem;
}
}
foreach (KeyValuePair<string, List<string>> dictItem in _duplicateConstants)
{
if (!firstLineInFileAllocated)
firstLineInFileAllocated = true;
else
textToBeWrittenToFile += "\r\n\r\n";
textToBeWrittenToFile += "Duplicate definition for constant \"" + dictItem.Key + "\" found in the following files: ";
foreach (string listItem in dictItem.Value)
{
textToBeWrittenToFile += "\r\n" + GetCodeIndentation(1) + listItem;
}
}
if (textToBeWrittenToFile.Length > 0)
{
try
{
fs = new FileStream(diagnosticFile, FileMode.Create, FileAccess.ReadWrite);
writer = new StreamWriter(fs, Encoding.Default);
writer.Write(textToBeWrittenToFile);
}
catch (System.Exception ex)
{
_logger.Error(ex);
isSuccessful = false;
}
finally
{
if (writer != null)
{
writer.Close();
fs.Close();
}
}
}
//m_mainWindow.updateStatusBox("DONE\n");
}
return isSuccessful;
}
public static string GetCodeIndentation(int indentMultiples)
{
string indentUnit = " ";
string indentation = string.Empty;
for (int i = 1; i <= indentMultiples; i++)
indentation += indentUnit;
return indentation;
}
}
}

View File

@@ -0,0 +1,588 @@
// **********************************************************************************************************
// XmlParser.cs
// 6/6/2022
// 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 System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
namespace Raytheon.Instruments.XmlUtilities
{
public class XmlParser
{
public class CommonXmlElements
{
public List<string> fileIncludes = new List<string>();
public string projectName = string.Empty;
public string classification = string.Empty;
public string fileHeader = string.Empty;
}
public class XmlConstant
{
public string nameSpace = string.Empty;
public List<string> comments = new List<string>();
public string name = string.Empty;
public string value = string.Empty;
public string description = string.Empty;
}
public class XmlEnumeration
{
public string nameSpace = string.Empty;
public string description = string.Empty;
public List<string> comments = new List<string>();
//public Dictionary<string, string> enumKeyAndValuePairs = new Dictionary<string, string>();
public List<XmlEnumItem> enumItems = new List<XmlEnumItem>();
}
public class XmlEnumItem
{
public List<string> comments = new List<string>();
public string name = string.Empty;
public string value = string.Empty;
}
public class XmlStructure
{
public string nameSpace = string.Empty;
public string name = string.Empty;
public List<string> comments = new List<string>();
public List<XmlStructureItem> structDataItems = new List<XmlStructureItem>();
}
public class XmlStructureItem
{
public string nameSpace = string.Empty;
public List<string> comments = new List<string>();
public string name = string.Empty;
public string description = string.Empty;
public string type = string.Empty;
public string defaultVal = string.Empty;
public string arrayLength = string.Empty;
public string bits = string.Empty;
}
public class XmlMbitMessage
{
public string nameSpace = string.Empty;
public string name = string.Empty;
public string label = string.Empty;
public string instruLabel = string.Empty;
public string description = string.Empty;
public List<string> comments = new List<string>();
public List<XmlParser.XmlStructureItem> dataItems = new List<XmlParser.XmlStructureItem>();
}
///===================================================================================
/// XmlParser.getCommonElementsFromXml
///===================================================================================
/// <summary>
/// Each XML file contains common elements such as header, includes, etc
/// We want to parse it and save the common elements
/// </summary>
/// <param name="nav">navigator object that points to the current XML node we are at</param>
/// <param name="commonElements">data structure that stores all the common elements of each XML file</param>
///===================================================================================
public static bool GetCommonElementsFromXml(XPathNavigator nav, CommonXmlElements commonElements)
{
bool isSuccessful = true;
if (string.Equals(nav.Name, "include", StringComparison.OrdinalIgnoreCase))
{
if (nav.MoveToFirstChild())
{
GetFileIncludes(nav, commonElements);
nav.MoveToParent();
}
}
else if (string.Equals(nav.Name, "project", StringComparison.OrdinalIgnoreCase))
{
commonElements.projectName = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "classification", StringComparison.OrdinalIgnoreCase))
{
commonElements.classification = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "fileheader", StringComparison.OrdinalIgnoreCase))
{
commonElements.fileHeader = nav.Value;
}
else if (string.Equals(nav.Name, "packing", StringComparison.OrdinalIgnoreCase))
{
}
else
isSuccessful = false;
return isSuccessful;
}
///===================================================================================
/// XmlParser.getFileIncludes
///===================================================================================
/// <summary>
/// Get the file includes specify by the XML file
/// </summary>
/// <param name="nav">navigator object that points to the current XML node we are at</param>
/// <param name="commonElements">data structure that stores all the common elements of each XML file</param>
///===================================================================================
public static void GetFileIncludes(XPathNavigator nav, CommonXmlElements commonElements)
{
do
{
commonElements.fileIncludes.Add(nav.Value.Trim());
} while (nav.MoveToNext());
}
///===================================================================================
/// XmlParser.getConstant
///===================================================================================
/// <summary>
/// Parse the symbolic constant defined by the XML
/// </summary>
/// <param name="nav">navigator object that points to the current XML node we are at</param>
/// <param name="nameSpace">the XML file name that defines this constant</param>
/// <param name="xmlConstants">the Dictionary that stores this constant information</param>
/// <param name="duplicateConstants">the Dictioanry that stores duplicate constant definitions</param>
///===================================================================================
public static void GetConstant(XPathNavigator nav, string nameSpace, List<XmlConstant> xmlConstants, Dictionary<string, List<string>> duplicateConstants)
{
XmlConstant tempXmlConstant = new XmlConstant();
if (nav.MoveToFirstChild())
{
do
{
if (string.Equals(nav.Name, "name", StringComparison.OrdinalIgnoreCase))
{
tempXmlConstant.name = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "description", StringComparison.OrdinalIgnoreCase))
{
tempXmlConstant.description = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "value", StringComparison.OrdinalIgnoreCase))
{
tempXmlConstant.value = nav.Value.Trim();
}
else if (nav.Name.Length > 0)
{
throw new XmlParsingException("Unknown element \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
} while (nav.MoveToNext());
nav.MoveToParent();
}
if (tempXmlConstant.name.Length > 0)
{
tempXmlConstant.nameSpace = nameSpace;
xmlConstants.Add(tempXmlConstant);
}
else
{
throw new XmlParsingException("Child element \"name\" not found for node \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
}
///===================================================================================
/// XmlParser.getEnumeration
///===================================================================================
/// <summary>
/// Parse the enumeration type defined by the XML
/// </summary>
/// <param name="nav">navigator object that points to the current XML node we are at</param>
/// <param name="nameSpace">the XML file name that defines this enumeration type</param>
/// <param name="xmlEnum">data structure that stores enumeration data</param>
/// <param name="duplicateEnums">the Dictioanry that stores duplicate enumeration type</param>
///===================================================================================
public static void GetEnumeration(XPathNavigator nav, string nameSpace, Dictionary<string, XmlEnumeration> xmlEnums, Dictionary<string, List<string>> duplicateEnums)
{
string enumTypeName = string.Empty;
string tempEnumTypeName = "temp";
Dictionary<string, XmlEnumeration> tempXmlEnums = new Dictionary<string, XmlEnumeration>
{
[tempEnumTypeName] = new XmlEnumeration()
};
tempXmlEnums[tempEnumTypeName].nameSpace = nameSpace;
if (nav.MoveToFirstChild())
{
do
{
if (string.Equals(nav.Name, "name", StringComparison.OrdinalIgnoreCase))
{
enumTypeName = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "description", StringComparison.OrdinalIgnoreCase))
{
tempXmlEnums[tempEnumTypeName].description = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "comment", StringComparison.OrdinalIgnoreCase))
{
tempXmlEnums[tempEnumTypeName].comments.Add(nav.Value.Trim());
}
else if (string.Equals(nav.Name, "item", StringComparison.OrdinalIgnoreCase) || string.Equals(nav.Name, "enum_item", StringComparison.OrdinalIgnoreCase))
{
if (nav.MoveToFirstChild())
{
GetEnumItem(nav, tempXmlEnums[tempEnumTypeName]);
nav.MoveToParent();
}
}
else if (nav.Name.Length > 0)
{
throw new XmlParsingException("Unknown element \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
} while (nav.MoveToNext());
nav.MoveToParent();
}
if (enumTypeName.Length > 0)
{
if (xmlEnums.ContainsKey(enumTypeName))
{
// save file name the defines this message that is a duplicate
if (!duplicateEnums.ContainsKey(enumTypeName))
{
duplicateEnums[enumTypeName] = new List<string>();
}
int index2 = duplicateEnums[enumTypeName].FindIndex(f => string.Equals(f, nameSpace + ".xml", StringComparison.OrdinalIgnoreCase));
if (index2 < 0)
duplicateEnums[enumTypeName].Add(nameSpace + ".xml");
// see if the official structure is already in the duplicate list
int index3 = duplicateEnums[enumTypeName].FindIndex(f => string.Equals(f, xmlEnums[enumTypeName].nameSpace + ".xml", StringComparison.OrdinalIgnoreCase));
// if the official structure is not in the duplicate list, we want to save it in the duplicate list
if (index3 < 0)
{
duplicateEnums[enumTypeName].Add(xmlEnums[enumTypeName].nameSpace + ".xml");
}
}
else
{
xmlEnums[enumTypeName] = tempXmlEnums[tempEnumTypeName];
}
}
else
{
throw new XmlParsingException("Child element \"name\" not found for node \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
}
///===================================================================================
/// XmlParser.getEnumItem
///===================================================================================
/// <summary>
/// Parse each enumerated key/value pair
/// </summary>
/// <param name="nav">navigator object that points to the current XML node we are at</param>
/// <param name="xmlEnum">data structure that stores enumeration data</param>
///===================================================================================
public static void GetEnumItem(XPathNavigator nav, XmlEnumeration xmlEnum)
{
XmlEnumItem enumItem = new XmlEnumItem();
do
{
if (string.Equals(nav.Name, "name", StringComparison.OrdinalIgnoreCase) || string.Equals(nav.Name, "item_name", StringComparison.OrdinalIgnoreCase))
{
enumItem.name = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "value", StringComparison.OrdinalIgnoreCase))
{
enumItem.value = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "comment", StringComparison.OrdinalIgnoreCase))
{
enumItem.comments.Add(nav.Value.Trim());
}
else if (nav.Name.Length > 0)
{
throw new XmlParsingException("Unknown element \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
} while (nav.MoveToNext());
xmlEnum.enumItems.Add(enumItem);
}
public static void GetStructure(XPathNavigator nav, string nameSpace, Dictionary<string, XmlStructure> xmlStructures, List<string> comments, Dictionary<string, List<string>> duplicateStructures)
{
string structureTypeName = string.Empty;
string tempStructureTypeName = "temp";
Dictionary<string, XmlStructure> tempXmlStructures = new Dictionary<string, XmlStructure>();
tempXmlStructures[tempStructureTypeName] = new XmlStructure();
tempXmlStructures[tempStructureTypeName].nameSpace = nameSpace;
if (nav.MoveToFirstChild())
{
do
{
if (string.Equals(nav.Name, "name", StringComparison.OrdinalIgnoreCase))
{
structureTypeName = nav.Value.Trim();
if (comments != null && comments.Count > 0)
{
tempXmlStructures[tempStructureTypeName].comments = new List<string>(comments);
}
}
else if (string.Equals(nav.Name, "comment", StringComparison.OrdinalIgnoreCase))
{
tempXmlStructures[tempStructureTypeName].comments.Add(nav.Value.Trim());
}
else if (string.Equals(nav.Name, "item", StringComparison.OrdinalIgnoreCase) || string.Equals(nav.Name, "struct_item", StringComparison.OrdinalIgnoreCase))
{
if (nav.MoveToFirstChild())
{
XmlStructureItem structureItem = new XmlStructureItem();
structureItem.nameSpace = nameSpace;
GetStructureItem(nav, structureItem);
tempXmlStructures[tempStructureTypeName].structDataItems.Add(structureItem);
nav.MoveToParent();
}
}
else if (nav.Name.Length > 0)
{
throw new XmlParsingException("Unknown element \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
} while (nav.MoveToNext());
nav.MoveToParent();
}
if (structureTypeName.Length > 0)
{
if (xmlStructures.ContainsKey(structureTypeName))
{
// save file name the defines this message that is a duplicate
if (!duplicateStructures.ContainsKey(structureTypeName))
{
duplicateStructures[structureTypeName] = new List<string>();
}
int index2 = duplicateStructures[structureTypeName].FindIndex(f => string.Equals(f, nameSpace + ".xml", StringComparison.OrdinalIgnoreCase));
if (index2 < 0)
duplicateStructures[structureTypeName].Add(nameSpace + ".xml");
// see if the official structure is already in the duplicate list
int index3 = duplicateStructures[structureTypeName].FindIndex(f => string.Equals(f, xmlStructures[structureTypeName].nameSpace + ".xml", StringComparison.OrdinalIgnoreCase));
// if the official structure is not in the duplicate list, we want to save it in the duplicate list
if (index3 < 0)
{
duplicateStructures[structureTypeName].Add(xmlStructures[structureTypeName].nameSpace + ".xml");
}
}
else
{
xmlStructures[structureTypeName] = tempXmlStructures[tempStructureTypeName];
xmlStructures[structureTypeName].name = structureTypeName;
}
}
else
{
throw new XmlParsingException("Child element \"name\" not found for node \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
}
///===================================================================================
/// XmlParser.getStructureItem
///===================================================================================
/// <summary>
/// Parse the data structure defined by the XML
/// </summary>
/// <param name="nav">navigator object that points to the current XML node we are at</param>
/// <param name="xmlStructureItem">data structure that stores all data members of the data structure</param>
///===================================================================================
public static void GetStructureItem(XPathNavigator nav, XmlStructureItem xmlStructureItem)
{
do
{
if (string.Equals(nav.Name, "name", StringComparison.OrdinalIgnoreCase) || string.Equals(nav.Name, "item_name", StringComparison.OrdinalIgnoreCase))
{
xmlStructureItem.name = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "type", StringComparison.OrdinalIgnoreCase))
{
xmlStructureItem.type = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "default", StringComparison.OrdinalIgnoreCase))
{
xmlStructureItem.defaultVal = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "arrayLength", StringComparison.OrdinalIgnoreCase))
{
xmlStructureItem.arrayLength = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "comment", StringComparison.OrdinalIgnoreCase))
{
xmlStructureItem.comments.Add(nav.Value.Trim());
}
else if (string.Equals(nav.Name, "description", StringComparison.OrdinalIgnoreCase))
{
xmlStructureItem.description = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "bits", StringComparison.OrdinalIgnoreCase))
{
xmlStructureItem.bits = nav.Value.Trim();
}
else if (nav.Name.Length > 0)
{
throw new XmlParsingException("Unknown element \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
} while (nav.MoveToNext());
}
///===================================================================================
/// XmlParser.getMbitMessage
///===================================================================================
/// <summary>
/// Parse the message defined by the XML
/// </summary>
/// <param name="nav">navigator object that points to the current XML node we are at</param>
/// <param name="nameSpace">the XML file name that defines this message</param>
/// <param name="mbitMessages">list of messages defined by XML</param>
/// <param name="duplicateMbitMessages">the Dictioanry that stores duplicate messages</param>
///===================================================================================
public static void GetMbitMessage(XPathNavigator nav, string nameSpace, List<XmlMbitMessage> mbitMessages, Dictionary<string, List<string>> duplicateMbitMessages)
{
var mbitMsg = new XmlMbitMessage()
{
nameSpace = nameSpace
};
if (nav.MoveToFirstChild())
{
do
{
if (string.Equals(nav.Name, "name", StringComparison.OrdinalIgnoreCase))
{
mbitMsg.name = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "label", StringComparison.OrdinalIgnoreCase))
{
mbitMsg.label = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "instrulabel", StringComparison.OrdinalIgnoreCase))
{
mbitMsg.instruLabel = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "description", StringComparison.OrdinalIgnoreCase))
{
mbitMsg.description = nav.Value.Trim();
}
else if (string.Equals(nav.Name, "comment", StringComparison.OrdinalIgnoreCase))
{
mbitMsg.comments.Add(nav.Value.Trim());
}
else if (string.Equals(nav.Name, "item", StringComparison.OrdinalIgnoreCase)
|| string.Equals(nav.Name, "struct_item", StringComparison.OrdinalIgnoreCase)
|| string.Equals(nav.Name, "msg_item", StringComparison.OrdinalIgnoreCase))
{
if (nav.MoveToFirstChild())
{
XmlStructureItem structureItem = new XmlStructureItem()
{
nameSpace = nameSpace
};
GetStructureItem(nav, structureItem);
mbitMsg.dataItems.Add(structureItem);
nav.MoveToParent();
}
}
else if (nav.Name.Length > 0)
{
throw new XmlParsingException("Unknown element \"" + nav.OuterXml.Substring(0, nav.OuterXml.IndexOf(">") + 1) + "\" on line " + ((IXmlLineInfo)nav).LineNumber.ToString());
}
} while (nav.MoveToNext());
nav.MoveToParent();
int index = mbitMessages.FindIndex(f => string.Equals(f.name, mbitMsg.name, StringComparison.OrdinalIgnoreCase));
if (index >= 0)
{
// save file name the defines this message that is a duplicate
if (!duplicateMbitMessages.ContainsKey(mbitMsg.name))
{
duplicateMbitMessages[mbitMsg.name] = new List<string>();
}
int index3 = duplicateMbitMessages[mbitMsg.name].FindIndex(f => string.Equals(f, nameSpace + ".xml", StringComparison.OrdinalIgnoreCase));
if (index3 < 0)
duplicateMbitMessages[mbitMsg.name].Add(nameSpace + ".xml");
// see if the official message is already in the duplicate list
int index2 = duplicateMbitMessages[mbitMsg.name].FindIndex(f => string.Equals(f, mbitMessages[index].nameSpace + ".xml", StringComparison.OrdinalIgnoreCase));
// if the official message is not in the duplicate list, we want to save it in the duplicate list
if (index2 < 0)
{
duplicateMbitMessages[mbitMsg.name].Add(mbitMessages[index].nameSpace + ".xml");
}
// the existing message is defined in an xml file other than MsgsMc.xml. At this time, we want the messages in MsgsMc.xml to take precedence over other xml files.
// Why is the same message being defined in multiple xml files?
if (!string.Equals(mbitMessages[index].nameSpace, "msgsmc", StringComparison.OrdinalIgnoreCase) && string.Equals(nameSpace, "msgsmc", StringComparison.OrdinalIgnoreCase))
{
mbitMessages.RemoveAt(index);
mbitMessages.Add(mbitMsg);
}
}
else
mbitMessages.Add(mbitMsg);
}
}
}
}

View File

@@ -0,0 +1,51 @@
// **********************************************************************************************************
// XmlParsingException.cs
// 6/6/2022
// 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 System;
namespace Raytheon.Instruments.XmlUtilities
{
class XmlParsingException : SystemException
{
///===================================================================================
/// CodeGenerator.XmlParsingException
///===================================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="message">description of the exception</param>
///===================================================================================
public XmlParsingException(string message)
: base(message)
{ }
}
}

View File

@@ -0,0 +1,123 @@
// **********************************************************************************************************
// CMessage.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
/// <summary>
/// Message: compatability option; This class provides a message object option that is compatible
/// with what was used in COE 3.x. This is also the format generated by CMAT.
/// </summary>
public abstract class CMessage : coeMessage, IDisposable
{
protected CMessage(uint size) : this(size, 0) { }
protected CMessage(uint size, uint label) : this(size, label, 0) { }
protected CMessage(uint size, uint label, int priority) : base((int)size, label, priority) { }
~CMessage()
{
Dispose(false);
}
new public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
new protected void Dispose(bool disposing)
{
base.Dispose(disposing);
}
abstract public byte[] serialize();
abstract public bool deserialize(byte[] stream);
override public void Serialize()
{
byte[] data = serialize();
if (data.Length > 0)
{
Marshal.Copy(data, 0, m_UnmanagedBuffer, data.Length);
Size = (uint)data.Length;
}
}
override public void Deserialize()
{
byte[] data = copyFromMessageBuffer();
deserialize(data);
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,138 @@
// **********************************************************************************************************
// coeDataInterchange.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct DataInterchangeManagedCodeFormatType
{
public DataInterchangeManagedCodeFormatType(coeDataInterchange.FormatType format)
{
m_Repetition = format.m_Repetition;
m_FormatLength = format.m_FormatLength;
m_Format = format.m_Format;
}
[MarshalAs(UnmanagedType.U4)]
internal uint m_Repetition;
[MarshalAs(UnmanagedType.U4)]
internal uint m_FormatLength;
[MarshalAs(UnmanagedType.U4)]
internal uint m_Format;
}
public class coeDataInterchange
{
public const int LABEL_SIZE = 40;
public class FormatType
{
public FormatType(string fieldName,
uint repetition,
uint length,
char format)
{
m_FieldName = fieldName;
m_Repetition = repetition;
m_FormatLength = length;
m_Format = format;
}
public string m_FieldName;
public uint m_Repetition;
public uint m_FormatLength;
public char m_Format;
}
public class FormatPacketType
{
public FormatPacketType(string name,
uint msgSize,
uint numItems,
FormatType[] format)
{
m_Name = name;
m_NumberItems = numItems;
m_DataByteSize = msgSize;
m_Format = format;
}
public string m_Name;
public uint m_NumberItems;
public uint m_DataByteSize;
public FormatType[] m_Format;
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,163 @@
// **********************************************************************************************************
// coeDataInterchangePackets.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Data Interchange Packet
//
//
//
public class coeDataInterchangePackets
{
private Dictionary<uint, IntPtr> _packets;
public coe.CallBackDelegate _delegate;
private GCHandle _GCdelegate;
internal coeDataInterchangePackets()
{
_packets = new Dictionary<uint, IntPtr>();
_delegate = new coe.CallBackDelegate(Find);
_GCdelegate = GCHandle.Alloc(_delegate);
}
~coeDataInterchangePackets()
{
foreach (KeyValuePair<uint, IntPtr> entry in _packets)
{
Marshal.FreeHGlobal(entry.Value);
}
_GCdelegate.Free();
}
internal IntPtr Find(uint Label)
{
_packets.TryGetValue(Label, out IntPtr packetArray);
return packetArray;
}
private void FormatString(byte[] dataBuffer, ref uint StartingIndex, string Name)
{
uint index;
for (index = 0; index < Name.Length && index < 39; index++)
{
dataBuffer[StartingIndex++] = (byte)Name[(int)index];
}
for (; index < 40; index++)
{
dataBuffer[StartingIndex++] = 0;
}
}
private void FormatUint(byte[] dataBuffer,
ref uint StartingIndex,
uint DataValue)
{
dataBuffer[StartingIndex++] = (byte)((DataValue) & 0xFF);
dataBuffer[StartingIndex++] = (byte)((DataValue >> 8) & 0xFF);
dataBuffer[StartingIndex++] = (byte)((DataValue >> 16) & 0xFF);
dataBuffer[StartingIndex++] = (byte)((DataValue >> 24) & 0xFF);
}
internal IntPtr Add(uint Label, coeDataInterchange.FormatPacketType packet)
{
IntPtr packetArray = IntPtr.Zero;
if ((packet.m_NumberItems > 0) && (!_packets.TryGetValue(Label, out packetArray)))
{
int sizeOfInterchangeStructure = (int)(52 + (packet.m_NumberItems * 52));
packetArray = Marshal.AllocHGlobal(sizeOfInterchangeStructure);
byte[] dataArray = new byte[sizeOfInterchangeStructure];
// Format the byte array with the data
uint dataArrayIndex = 0;
FormatString(dataArray, ref dataArrayIndex, packet.m_Name);
FormatUint(dataArray, ref dataArrayIndex, packet.m_NumberItems);
FormatUint(dataArray, ref dataArrayIndex, packet.m_DataByteSize);
FormatUint(dataArray, ref dataArrayIndex, (uint)((IntPtr)(packetArray.ToInt32() + 52)));
for (int count = 0; count < packet.m_NumberItems; count++)
{
FormatString(dataArray, ref dataArrayIndex, packet.m_Format[count].m_FieldName);
FormatUint(dataArray, ref dataArrayIndex, packet.m_Format[count].m_Repetition);
FormatUint(dataArray, ref dataArrayIndex, packet.m_Format[count].m_FormatLength);
FormatUint(dataArray, ref dataArrayIndex, packet.m_Format[count].m_Format);
}
Marshal.Copy(dataArray, 0, packetArray, sizeOfInterchangeStructure);
_packets.Add(Label, packetArray);
}
return packetArray;
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,309 @@
// **********************************************************************************************************
// coeEndpoint.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Endpoint
//
//
//
public class coeEndpoint : IDisposable
{
#region DLLImports
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Create_Dynamic_With_Domain")]
private static extern IntPtr OE_Endpoint_Create_Dynamic_With_Domain(IntPtr Name,
coe.ScopeType Scope,
IntPtr Router,
uint Domain,
uint MaximumTransmitMessages,
uint MaximumReceiveMessages,
uint MaximumTransmitMessageSize,
uint MaximumReceiveMessageSize,
IntPtr ApplicationContext,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Delete")]
private static extern coe.Status OE_Endpoint_Delete(IntPtr _obj);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Associate")]
private static extern coe.Status OE_Endpoint_Associate(IntPtr _obj,
IntPtr Event,
TriggerType Trigger);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Send_Labeled")]
private static extern coe.Status OE_Endpoint_Send_Labeled(IntPtr _obj,
IntPtr Message,
uint Options,
uint Handling_Policy);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Peek")]
private static extern coe.Status OE_Endpoint_Peek(IntPtr _obj,
out uint Message_Label,
out uint Message_Size,
out int Message_Priority);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Wait")]
private static extern coe.Status OE_Endpoint_Wait(IntPtr _obj,
int Timeout);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Receive")]
private static extern coe.Status OE_Endpoint_Receive(IntPtr _obj,
ref IntPtr Message,
uint Handling_Policy,
int Timeout,
IntPtr Source);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Register_Ex2")]
private static extern coe.Status OE_Endpoint_Register_Ex2(IntPtr _obj,
uint Label,
[MarshalAs(UnmanagedType.FunctionPtr)]
coe.CallBackDelegate callbackD);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Deregister")]
private static extern coe.Status OE_Endpoint_Deregister(IntPtr _obj,
uint Label);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Endpoint_Empty")]
private static extern coe.Status OE_Endpoint_Empty(IntPtr _obj);
#endregion
public enum TriggerType : int
{
DATA_RECEIVED = 0,
BUFFER_EMPTY = 1,
DATA_DISCARDED = 2
};
private bool _disposed;
private IntPtr _handle;
private readonly coeEvent[] _events;
private const int MaximumNumberOfEvents = 4;
private int _numberOfEvents;
// Constant to be used for a non-queued endpoint
public const uint NON_QUEUED_SIZE = 0;
public coeEndpoint(uint maxMessageSize, IntPtr router = default) : this(0, maxMessageSize, 0, router) { }
public coeEndpoint(uint maxMessageSize, uint maxBufferMessages, IntPtr router = default)
: this(0, maxMessageSize, maxBufferMessages, router) { }
public coeEndpoint(uint domain, uint maxMessageSize, uint maxBufferMessages, IntPtr router = default)
{
_handle = OE_Endpoint_Create_Dynamic_With_Domain(IntPtr.Zero, coe.ScopeType.OE_Local, router, domain,
maxBufferMessages, maxBufferMessages, maxMessageSize, maxMessageSize, IntPtr.Zero, out coe.Status oe_status);
if (oe_status != coe.Status.SUCCESS)
{
_handle = IntPtr.Zero;
throw new Exception("Unable to create OE_Endpoint. Error = " + oe_status);
}
else
{
_numberOfEvents = 0;
_events = new coeEvent[MaximumNumberOfEvents];
}
}
~coeEndpoint()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
}
if (_handle != IntPtr.Zero)
{
for (int index = 0; index < _numberOfEvents; index++)
{
_events[index].Disable();
}
OE_Endpoint_Delete(_handle);
_handle = IntPtr.Zero;
}
_disposed = true;
}
public IntPtr Handle
{
get { return _handle; }
}
public coe.Status Register(uint label)
{
coe.Status status = OE_Endpoint_Register_Ex2(_handle, label, null);
return status;
}
public coe.Status Register(uint label, coeDataInterchange.FormatPacketType packet)
{
coe._dataInterchangePackets.Add(label, packet);
coe.Status status = OE_Endpoint_Register_Ex2(_handle, label, coe._dataInterchangePackets._delegate);
return status;
}
public coe.Status Deregister(uint label)
{
coe.Status status = OE_Endpoint_Deregister(_handle, label);
return status;
}
public coe.Status Send(coeMessage message)
{
return Send(message, 0);
}
public coe.Status Send(coeMessage message, uint options)
{
message.Serialize();
return OE_Endpoint_Send_Labeled(_handle, message.Handle, options, 0);
}
public coe.Status Peek(out uint message_Label,
out uint message_Size,
out int message_Priority)
{
coe.Status status;
status = OE_Endpoint_Peek(_handle, out uint messageLabel, out uint messageSize, out int messagePriority);
message_Label = messageLabel;
message_Size = messageSize;
message_Priority = messagePriority;
return status;
}
public coe.Status Wait(int timeout)
{
return OE_Endpoint_Wait(_handle, timeout);
}
public coe.Status Clear()
{
return OE_Endpoint_Empty(_handle);
}
public coe.Status Receive(coeMessage message, int timeout)
{
coe.Status Status;
IntPtr coeMessageHandle = message != null ? message.Handle : IntPtr.Zero;
Status = OE_Endpoint_Receive(_handle, ref coeMessageHandle, 0, timeout, IntPtr.Zero);
if (Status == coe.Status.SUCCESS)
{
message.Deserialize();
}
return Status;
}
public coe.Status Receive(coeMessage message)
{
return Receive(message, coe.OE_Wait_Forever);
}
public coe.Status Associate(coeEventFlag eventFlag, uint mask, TriggerType trigger)
{
coe.Status status;
if (_numberOfEvents >= MaximumNumberOfEvents)
{
status = coe.Status.FAILED_INSUFFICIENT_RESOURCES;
}
else
{
_events[_numberOfEvents] = new coeEvent();
_events[_numberOfEvents].SetNotification(eventFlag, mask);
status = OE_Endpoint_Associate(_handle, _events[_numberOfEvents].Handle, trigger);
if (status == coe.Status.SUCCESS)
{
status = _events[_numberOfEvents].Enable();
_numberOfEvents++;
}
}
return status;
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,177 @@
// **********************************************************************************************************
// coeEvent.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Event
//
//
//
public class coeEvent : IDisposable
{
#region DLLImports
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Create_Dynamic")]
private static extern IntPtr OE_Event_Create_Dynamic(IntPtr Name,
PersistenceType Persistence,
int Priority,
IntPtr ApplicationContext,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Delete")]
public static extern coe.Status OE_Event_Delete(IntPtr _obj);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Enable")]
private static extern coe.Status OE_Event_Enable(IntPtr _obj);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Disable")]
private static extern coe.Status OE_Event_Disable(IntPtr _obj);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Set_Event_Flag_Notification")]
private static extern coe.Status OE_Event_Set_Event_Flag_Notification(IntPtr _obj,
IntPtr EventFlag,
uint Mask);
#endregion
public enum PersistenceType : int
{
ONE_SHOT = 0,
ENDURING = 1
}
private bool _disposed = false;
private IntPtr _handle = IntPtr.Zero;
public coeEvent() : this(PersistenceType.ENDURING, 0) { }
public coeEvent(PersistenceType persistence) : this(persistence, 0) { }
public coeEvent(int priority) : this(PersistenceType.ENDURING, priority) { }
public coeEvent(PersistenceType persistence, int priority)
{
_handle = OE_Event_Create_Dynamic(IntPtr.Zero, persistence, priority, IntPtr.Zero, out coe.Status oe_status);
if (oe_status != coe.Status.SUCCESS)
{
_handle = IntPtr.Zero;
throw new Exception("Unable to create OE_Event. Error = " + oe_status);
}
}
~coeEvent()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
}
if (_handle != IntPtr.Zero)
{
OE_Event_Delete(_handle);
_handle = IntPtr.Zero;
}
_disposed = true;
}
internal IntPtr Handle
{
get { return _handle; }
}
public coe.Status Enable()
{
return OE_Event_Enable(_handle);
}
public coe.Status Disable()
{
return OE_Event_Disable(_handle);
}
public coe.Status SetNotification(coeEventFlag eventFlag, uint mask)
{
return OE_Event_Set_Event_Flag_Notification(_handle, eventFlag.Handle, mask);
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,201 @@
// **********************************************************************************************************
// coeEventFlag.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Event Flag
//
//
//
public class coeEventFlag : IDisposable
{
#region DLLImports
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Flag_Create_Dynamic")]
private static extern IntPtr OE_Event_Flag_Create_Dynamic(IntPtr Name,
coe.ScopeType Scope,
uint InitialMask,
IntPtr ApplicationContext,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Flag_Delete")]
private static extern coe.Status OE_Event_Flag_Delete(IntPtr _obj);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Flag_Set")]
private static extern coe.Status OE_Event_Flag_Set(IntPtr _obj,
uint Mask);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Flag_Clear")]
private static extern coe.Status OE_Event_Flag_Clear(IntPtr _obj,
uint Mask);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Flag_Peek_Mask")]
private static extern coe.Status OE_Event_Flag_Peek_Mask(IntPtr _obj,
out uint Mask);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Event_Flag_Wait")]
private static extern coe.Status OE_Event_Flag_Wait(IntPtr _obj,
uint Mask,
uint ResetMask,
WaitPolicyType PolicyType,
int TimeInterval,
out uint CurrentMask);
#endregion
private bool _disposed = false;
private IntPtr _handle = IntPtr.Zero;
public enum WaitPolicyType : int
{
WAIT_FOR_ALL = 0,
WAIT_FOR_ANY = 1
}
public coeEventFlag()
{
_handle = OE_Event_Flag_Create_Dynamic(IntPtr.Zero, coe.ScopeType.OE_Local, 0, IntPtr.Zero, out coe.Status oe_status);
if (oe_status != coe.Status.SUCCESS)
{
_handle = IntPtr.Zero;
throw new Exception("Unable to create OE_Event_Flag. Error = " + oe_status);
}
}
~coeEventFlag()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
}
if (_handle != IntPtr.Zero)
{
OE_Event_Flag_Delete(_handle);
_handle = IntPtr.Zero;
}
_disposed = true;
}
internal IntPtr Handle
{
get { return _handle; }
}
public coe.Status Set(uint mask)
{
return OE_Event_Flag_Set(_handle, mask);
}
public coe.Status Clear(uint mask)
{
return OE_Event_Flag_Clear(_handle, mask);
}
public coe.Status Peek(out uint mask)
{
coe.Status status;
status = OE_Event_Flag_Peek_Mask(_handle, out uint currentMask);
mask = currentMask;
return status;
}
public coe.Status Wait(uint mask,
uint resetMask,
WaitPolicyType waitPolicy,
int timeout,
out uint currentMask)
{
coe.Status status;
status = OE_Event_Flag_Wait(_handle, mask, resetMask, waitPolicy, timeout, out uint returnedMask);
currentMask = returnedMask;
return status;
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,392 @@
// **********************************************************************************************************
// coeMessage.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
/// <summary>
/// Message Attributes
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public class MessageOffset : Attribute
{
readonly uint _bufferOffset;
public MessageOffset(uint bufferOffset)
{
_bufferOffset = bufferOffset;
}
public uint Offset
{
get { return _bufferOffset; }
}
}
[AttributeUsage(AttributeTargets.All)]
public class MessageSize : Attribute
{
readonly int _bufferSize;
public MessageSize(int bufferSize)
{
_bufferSize = bufferSize;
}
public int Size
{
get { return _bufferSize; }
}
}
/// <summary>
/// Message: base class
/// </summary>
public abstract class coeMessage : IDisposable
{
#region DLLImports
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_Create")]
private static extern IntPtr OE_Message_Create(IntPtr Buffer_Address,
uint Size,
int Create_Shared,
IntPtr ApplicationContext,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_Delete")]
private static extern coe.Status OE_Message_Delete(IntPtr Handle);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_set_Priority")]
private static extern coe.Status OE_Message_set_Priority(IntPtr Handle,
int Priority);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_get_Priority")]
private static extern int OE_Message_get_Priority(IntPtr Handle,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_set_Domain")]
private static extern coe.Status OE_Message_set_Domain(IntPtr Handle,
uint Domain);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_get_Domain")]
private static extern uint OE_Message_get_Domain(IntPtr Handle,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_set_Label")]
private static extern coe.Status OE_Message_set_Label(IntPtr Handle,
uint Label);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_get_Label")]
private static extern uint OE_Message_get_Label(IntPtr Handle,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_set_Data_Size")]
private static extern coe.Status OE_Message_set_Data_Size(IntPtr Handle,
uint Size);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_get_Data_Size")]
private static extern uint OE_Message_get_Data_Size(IntPtr Handle,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_get_Transmit_Timestamp")]
private static extern coe.Status OE_Message_get_Transmit_Timestamp(IntPtr Handle,
out ulong Seconds,
out uint Fraction_Of_Second);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Message_get_Receive_Timestamp")]
private static extern coe.Status OE_Message_get_Receive_Timestamp(IntPtr Handle,
out ulong Seconds,
out uint Fraction_Of_Second);
#endregion
private bool disposed = false;
protected IntPtr m_Handle = IntPtr.Zero;
protected IntPtr m_UnmanagedBuffer = IntPtr.Zero;
protected int m_UnmanagedBufferSize = 0;
protected int m_Size;
protected byte[] m_Buffer;
//
// The following routines are provided for testing and access purposes
//
public IntPtr GetUnmanagedBuffer() { return m_UnmanagedBuffer; }
public byte[] GetManagedBuffer() { return m_Buffer; }
protected coeMessage(int size) : this(size, 0) { }
protected coeMessage(int size, uint label) : this(size, label, 0) { }
protected coeMessage(int size, uint label, int priority)
{
if (size == 0)
{
size = getPayloadSize();
}
if (size > 0)
{
m_Buffer = new byte[size];
m_UnmanagedBuffer = Marshal.AllocHGlobal((int)size);
m_UnmanagedBufferSize = (int)size;
}
m_Handle = OE_Message_Create(m_UnmanagedBuffer, (uint)size, coe.OE_FALSE, IntPtr.Zero, out coe.Status oe_status);
if (oe_status != coe.Status.SUCCESS)
{
m_Handle = IntPtr.Zero;
throw new Exception("Unable to create OE_Message. Error = " + oe_status);
}
else
{
m_Size = size;
// The message was created successfully
oe_status = OE_Message_set_Priority(m_Handle, priority);
if (oe_status != coe.Status.SUCCESS)
{
throw new Exception("Unable to set message priority to " + priority + ". Error = " + oe_status);
}
oe_status = OE_Message_set_Label(m_Handle, label);
if (oe_status != coe.Status.SUCCESS)
{
throw new Exception("Unable to set message priority to " + label + ". Error = " + oe_status);
}
}
}
~coeMessage()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposed) return;
if (disposing)
{
}
if (m_UnmanagedBuffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(m_UnmanagedBuffer);
m_UnmanagedBuffer = IntPtr.Zero;
}
if (m_Handle != IntPtr.Zero)
{
OE_Message_Delete(m_Handle);
m_Handle = IntPtr.Zero;
}
disposed = true;
}
internal IntPtr Handle
{
get { return m_Handle; }
}
public uint Domain
{
get
{
return OE_Message_get_Domain(m_Handle, out coe.Status status);
}
set
{
coe.Status status = OE_Message_set_Domain(m_Handle, value);
}
}
public uint Label
{
get
{
return OE_Message_get_Label(m_Handle, out coe.Status status);
}
set
{
coe.Status status = OE_Message_set_Label(m_Handle, value);
}
}
public int Priority
{
get
{
return OE_Message_get_Priority(m_Handle, out coe.Status status);
}
set
{
coe.Status status = OE_Message_set_Priority(m_Handle, value);
}
}
public uint Size
{
get
{
return OE_Message_get_Data_Size(m_Handle, out coe.Status status);
}
set
{
coe.Status status = OE_Message_set_Data_Size(m_Handle, value);
}
}
public int BufferSize
{
get
{
return m_UnmanagedBufferSize;
}
set
{
if (value > m_UnmanagedBufferSize)
{
uint savedDomain = Domain;
uint savedLabel = Label;
int savedPriority = Priority;
uint savedSize = Size;
if (m_UnmanagedBuffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(m_UnmanagedBuffer);
m_UnmanagedBuffer = IntPtr.Zero;
}
if (m_Handle != IntPtr.Zero)
{
OE_Message_Delete(m_Handle);
m_Handle = IntPtr.Zero;
}
m_Buffer = new byte[value];
m_UnmanagedBuffer = Marshal.AllocHGlobal((int)value);
m_UnmanagedBufferSize = (int)value;
m_Handle = OE_Message_Create(m_UnmanagedBuffer, (uint)value, coe.OE_FALSE, IntPtr.Zero, out coe.Status oe_status);
m_Size = value;
Domain = savedDomain;
Label = savedLabel;
Priority = savedPriority;
Size = savedSize;
}
}
}
public void GetSendTime(out ulong Seconds, out uint FractionOfSecond)
{
var status = OE_Message_get_Transmit_Timestamp(m_Handle, out ulong seconds, out uint fractionOfSecond);
Seconds = seconds;
FractionOfSecond = fractionOfSecond;
}
public void GetReceiveTime(out ulong Seconds, out uint FractionOfSecond)
{
var status = OE_Message_get_Receive_Timestamp(m_Handle, out ulong seconds, out uint fractionOfSecond);
Seconds = seconds;
FractionOfSecond = fractionOfSecond;
}
abstract public void Serialize();
abstract public void Deserialize();
// Serialization/Deserialization support
private void alignIndex(ref int dataBufferIndex,
int alignment)
{
int indexMisalignment = dataBufferIndex % alignment;
if (indexMisalignment > 0)
{
dataBufferIndex += alignment - indexMisalignment;
}
}
public int getPayloadSize()
{
int size = 0;
return serializationSupport.getPayloadSize(this, GetType(), ref size);
}
protected void copyToMessageBuffer(byte[] data)
{
Marshal.Copy(data, 0, m_UnmanagedBuffer, data.Length);
}
protected byte[] copyFromMessageBuffer()
{
byte[] data = null;
uint dataSize = OE_Message_get_Data_Size(m_Handle, out coe.Status status);
if (dataSize > 0)
{
Marshal.Copy(m_UnmanagedBuffer, m_Buffer, 0, (int)dataSize);
data = m_Buffer;
}
return data;
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,102 @@
// **********************************************************************************************************
// coeMessageBasic.cs
// 7/8/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
namespace Raytheon.Instruments.coeCSharp
{
/// <summary>
/// The coeMessageBasic class is a template that can be used to create user messages
/// </summary>
internal class coeMessageBasic : coeMessage, IDisposable
{
public coeMessageBasic(uint size) : this(size, 0) { }
public coeMessageBasic(uint size, uint label) : this(size, label, 0) { }
public coeMessageBasic(uint size, uint label, int priority) : base((int)size, label, priority) { }
~coeMessageBasic()
{
Dispose(false);
}
new public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
new protected void Dispose(bool disposing)
{
base.Dispose(disposing);
}
override public void Serialize()
{
}
override public void Deserialize()
{
}
}
}

View File

@@ -0,0 +1,206 @@
// **********************************************************************************************************
// coeMessageFormatted.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Message: formatted option; This class provides automatic serialization
// of all defined public members with an attribute describing the order and
// placement in the binary buffer in which the message fields will be serialized.
// All members not defined as public or without a MessageOffset attribute will be
// ignored during serialization.
//
// Types currently supported include all scalar types and arrays of scalar types.
// Structures are also supported, which can contain single dimension arrays of scalar types.
// Structures can also be nested. The only restriction on all these elements is that arrays
// cannot contain structures, however, structures can contain arrays of scalar elements.
//
// Specifying a 0 size will cause the constructor to try to automatically size the
// message buffer, however since fields are individually specified, this may cause
// difficulties in assuming what is actually needed. It is recommended that this
// class be manually specified as to its internal buffer size.
//
// The same provision for arrays of classes that was described for the serialized option
// holds for the formatted option. All arrays of classes must have all objects in the array
// created with a new before sizing or serialization can be successfully done.
//
// Example:
//
// public class exampleMessage : coeMessageFormatted
// {
// [MessageOffset(0)]
// public uint field1;
// [MessageOffset(4)]
// public ushort field2;
// [MessageOffset(6)]
// public ushort field3;
// [MessageOffset(8)]
// public uint field4;
// [MessageOffset(12)]
// public uint field5;
// [MessageOffset(16)]
// public uint field6;
// public exampleMessage(uint size) : base(size) { }
// }
//
//
//
public abstract class coeMessageFormatted : coeMessage, IDisposable
{
protected coeMessageFormatted(uint size) : this(size, 0) { }
protected coeMessageFormatted(uint size, uint label) : this(size, label, 0) { }
protected coeMessageFormatted(uint size, uint label, int priority) : base((int)size, label, priority) { }
~coeMessageFormatted()
{
Dispose(false);
}
new public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
new protected void Dispose(bool disposing)
{
base.Dispose(disposing);
}
private bool SerializeGetOffset(FieldInfo field, out int dataIndex)
{
MessageOffset offsetAttribute = null;
dataIndex = 0;
//
// The following line is for .NET 4.5 or later
//
// MessageOffset offsetAttribute = (MessageOffset)field.GetCustomAttribute(typeof(MessageOffset));
//
// The following lines are for earlier versions of .NET
var attributes = field.GetCustomAttributes(typeof(MessageOffset), true);
if (attributes.Length > 0)
{
offsetAttribute = (MessageOffset)attributes[0];
}
//
//
if (offsetAttribute != null)
{
dataIndex = (int)offsetAttribute.Offset;
return true;
}
else
{
return false;
}
}
override public void Serialize()
{
uint dataSize = 0;
int dataIndex = 0;
FieldInfo[] fields = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (SerializeGetOffset(field, out dataIndex))
{
serializationSupport.serializeField(field, m_Buffer, ref dataIndex, this);
if (dataIndex > dataSize) dataSize = (uint)dataIndex;
}
}
Size = dataSize;
if (dataSize > 0)
{
Marshal.Copy(m_Buffer, 0, m_UnmanagedBuffer, (int)dataSize);
}
}
override public void Deserialize()
{
byte[] data = copyFromMessageBuffer();
int dataIndex = 0;
FieldInfo[] fields = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (SerializeGetOffset(field, out dataIndex))
{
serializationSupport.deserializeField(field, data, ref dataIndex, this);
}
}
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,197 @@
// **********************************************************************************************************
// coeMessageSerialized.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Message: serializable option; This class provides automatic serialization
// of all defined public members. All members not defined as public
// will be ignored during serialization.
//
// Types currently supported include all scalar types and arrays of scalar types.
// Structures are also supported, which can contain single dimension arrays of scalar types.
// Structures can also be nested. This message class does support arrays of structures.
//
// The presence of the constructor is optional, and can be used to force a particular size
// of a buffer. Omitting the size on the call to the base class, or providing a size value
// of 0 will cause the constructor to automatically size the data, as will omitting the
// constuctor declaration entirely.
//
// Example:
//
// public class exampleMessage : coeMessageSerialized
// {
// public uint field1;
// public ushort field2;
// public ushort field3;
// public uint field4;
// public uint field5;
// public uint field6;
//
// public exampleMessage() : base(SIZE) { }
// }
//
// Special care needs to be taken when using arrays in a message definition, or in any class
// that is used as a member of a message. Since C# arrays are dynamic, the array member must
// be initialized with a new directive to declare the specific size of the array. This must
// also be done for any sequences or strings used as message or class members. In addition,
// any objects in that array must be specifically created and added to the array in the
// constructor, if auto-sizing of the using message is being done. This initialization only
// needs to be done for classes, not for data types. However, before the message can be
// serialized for transmission, the array must be completely filled with the total number
// of objects for which it was created.
//
// Example:
//
// public class nestedStructure
// {
// public uint field1;
// }
//
// public class exampleStructure
// {
// public uint field1;
// public uint[] field2 = new uint[4];
// public nestedStructure[] field3 = new nestedStructure[3];
//
// public exampleStructure()
// {
// field3[0] = new nestedStructure();
// field3[1] = new nestedStructure();
// field3[2] = new nestedStructure();
// }
// }
//
// public class exampleMessage : coeMessageSerialized
// {
// public uint field1;
// public coeSequence<uint> mySequence = new coeSequence<uint>(8);
// public coeString myString = new coeString(12);
// public exampleStructure mystructure = new exampleStructure();
// }
//
//
//
public abstract class coeMessageSerialized : coeMessage, IDisposable
{
protected coeMessageSerialized() : this(0) { }
protected coeMessageSerialized(uint size) : this(size, 0) { }
protected coeMessageSerialized(uint size, uint label) : this(size, label, 0) { }
protected coeMessageSerialized(uint size, uint label, int priority) : base((int)size, label, priority) { }
~coeMessageSerialized()
{
Dispose(false);
}
new public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
new protected void Dispose(bool disposing)
{
base.Dispose(disposing);
}
override public void Serialize()
{
FieldInfo[] fields = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
int dataIndex = 0;
foreach (FieldInfo field in fields)
{
Type myType = field.GetType();
object myObject = field.GetValue(this);
serializationSupport.serializeField(field, m_Buffer, ref dataIndex, this);
}
Size = (uint)dataIndex;
Marshal.Copy(m_Buffer, 0, m_UnmanagedBuffer, m_Buffer.Length);
}
override public void Deserialize()
{
byte[] data = copyFromMessageBuffer();
int dataIndex = 0;
FieldInfo[] fields = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
serializationSupport.deserializeField(field, data, ref dataIndex, this);
}
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,150 @@
// **********************************************************************************************************
// coeSequence.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Sequences and Strings
//
//
//
public class coeSequence<T>
{
private ushort _numberOfElements;
private readonly ushort _maximumNumberOfElements;
private readonly ushort _sizeOfElement;
private readonly T[] _data;
public coeSequence(ushort length)
{
_maximumNumberOfElements = length;
_numberOfElements = 0;
_data = new T[length];
int mySize = 0;
serializationSupport.getPayloadSize(this, GetType(), ref mySize);
_sizeOfElement = (ushort)((mySize - 8) / length);
}
public Type ElementType
{
get
{
return typeof(T);
}
}
public void Clear()
{
_numberOfElements = 0;
}
public uint Count()
{
return _numberOfElements;
}
public uint MaximumCount()
{
return _maximumNumberOfElements;
}
public ushort SizeOfElement
{
get { return _sizeOfElement; }
}
public uint AddItem(T item)
{
if (_numberOfElements < _maximumNumberOfElements)
{
_data[_numberOfElements++] = item;
}
return _numberOfElements;
}
public T Get(ushort index)
{
if (index < _numberOfElements)
{
return _data[index];
}
else
{
throw new NullReferenceException("Index does not reference a valid value");
}
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,129 @@
// **********************************************************************************************************
// coeString.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System.Text;
namespace Raytheon.Instruments.coeCSharp
{
public class coeString
{
private ushort _numberOfElements;
private readonly ushort _maximumNumberOfElements;
private readonly ushort _sizeOfElement;
private readonly byte[] _data;
public coeString(ushort length)
{
_maximumNumberOfElements = length;
_numberOfElements = 0;
_sizeOfElement = 1;
_data = new byte[length + 2];
}
public void Clear()
{
_numberOfElements = 0;
}
public uint Count()
{
return _numberOfElements;
}
public uint MaximumCount()
{
return _maximumNumberOfElements;
}
public ushort SizeOfElement
{
get { return _sizeOfElement; }
}
public uint AddString(string item)
{
int index = 0;
while (_numberOfElements < _maximumNumberOfElements &&
index < item.Length)
{
_data[_numberOfElements++] = (byte)item[index++];
}
_data[_numberOfElements] = 0;
return _numberOfElements;
}
public string Get()
{
return Encoding.UTF8.GetString(_data, 0, _numberOfElements);
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,228 @@
// **********************************************************************************************************
// coeTimer.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Runtime.InteropServices;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Timer
//
//
//
public class coeTimer : IDisposable
{
#region DLLImports
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Timer_Create_Dynamic")]
private static extern IntPtr OE_Timer_Create_Dynamic(IntPtr Name,
coe.ScopeType Scope,
uint TimerFormat,
TimerType TimerKind,
IntPtr Clock,
IntPtr ApplicationContext,
out coe.Status Status);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Timer_Delete")]
public static extern coe.Status OE_Timer_Delete(IntPtr _obj);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Timer_Associate")]
private static extern coe.Status OE_Timer_Associate(IntPtr _obj,
IntPtr Event,
TriggerType Trigger);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Timer_Set_Relative")]
private static extern coe.Status OE_Timer_Set_Relative(IntPtr _obj,
uint TimeInterval);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Timer_Resume")]
private static extern coe.Status OE_Timer_Resume(IntPtr _obj);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Timer_Cancel")]
private static extern coe.Status OE_Timer_Cancel(IntPtr _obj);
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Environment_get_The_System_Clock_Handler")]
private static extern IntPtr OE_Environment_get_The_System_Clock_Handler();
[DllImport(coe.coeDLL, CallingConvention = CallingConvention.Cdecl, EntryPoint = "OE_Clock_Handler_Convert_To_Time_Interval")]
private static extern IntPtr OE_Clock_Handler_Convert_To_Time_Interval(IntPtr _obj,
uint Interval,
TimerResolutionType Resolution,
out uint TimeInterval);
#endregion
public enum TriggerType : int
{
TIMER_EXPIRED = 1
};
public enum TimerType : int
{
PERIODIC = 0,
ONE_SHOT = 1
};
public enum TimerResolutionType : int
{
MINUTE = 0,
SECOND = 1,
MILLISECOND = 2,
MICROSECOND = 3,
FRAME = 4
};
private bool _disposed = false;
private IntPtr _handle = IntPtr.Zero;
private const uint _timerRelative = 1;
private readonly coeEvent _timerEvent;
public coeTimer(TimerType Type)
{
_handle = OE_Timer_Create_Dynamic(IntPtr.Zero, coe.ScopeType.OE_Local, _timerRelative, Type, OE_Environment_get_The_System_Clock_Handler(), IntPtr.Zero, out coe.Status oe_status);
if (oe_status != coe.Status.SUCCESS)
{
_handle = IntPtr.Zero;
throw new Exception("Unable to create OE_Timer. Error = " + oe_status);
}
else
{
_timerEvent = new coeEvent();
}
}
~coeTimer()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
}
if (_handle != IntPtr.Zero)
{
_timerEvent.Disable();
OE_Timer_Delete(_handle);
_handle = IntPtr.Zero;
}
_disposed = true;
}
internal IntPtr Handle
{
get { return _handle; }
}
public coe.Status Set(uint interval, TimerResolutionType resolution)
{
OE_Clock_Handler_Convert_To_Time_Interval(OE_Environment_get_The_System_Clock_Handler(), interval, resolution, out uint timerInterval);
return OE_Timer_Set_Relative(_handle, timerInterval);
}
public coe.Status Set(uint Interval)
{
return Set(Interval, TimerResolutionType.MILLISECOND);
}
public coe.Status Resume()
{
return OE_Timer_Resume(_handle);
}
public coe.Status Cancel()
{
return OE_Timer_Cancel(_handle);
}
public coe.Status Associate(coeEventFlag eventFlag, uint mask, TriggerType trigger)
{
coe.Status Status;
_timerEvent.SetNotification(eventFlag, mask);
Status = OE_Timer_Associate(_handle, _timerEvent.Handle, trigger);
_timerEvent.Enable();
return Status;
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,647 @@
// **********************************************************************************************************
// serializationSupport.cs
// 6/1/2022
// 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)
// **********************************************************************************************************
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>
//\\<UnlimitedRights>
//----------------------------------------------------------------------------//
// Copyright %(copyright)s Raytheon Company. //
// This software was developed pursuant to Contract Number %(contractNumber)s //
// with the U.S. government. The U.S. government's rights in and to this //
// copyrighted software are as specified in DFARS 252.227-7014 which was made //
// part of the above contract. //
//----------------------------------------------------------------------------//
//\\<\UnlimitedRights>
//\\<EximUndetermined>
//----------------------------------------------------------------------------//
// WARNING - This document contains technical data and / or technology whose //
// export or disclosure to Non-U.S. Persons, wherever located, is restricted //
// by the International Traffic in Arms Regulations (ITAR) (22 C.F.R. //
// Section 120-130) or the Export Administration Regulations (EAR) (15 C.F.R. //
// Section 730-774). This document CANNOT be exported (e.g., provided to a //
// supplier outside of the United States) or disclosed to a Non-U.S. Person, //
// wherever located, until a final jurisdiction and classification //
// determination has been completed and approved by Raytheon, and any //
// required U.S. Government approvals have been obtained. Violations are //
// subject to severe criminal penalties. //
//----------------------------------------------------------------------------//
//\\<\EximUndetermined>
using System;
using System.Reflection;
namespace Raytheon.Instruments.coeCSharp
{
//
//
//
// Serialization Support
//
//
//
public class serializationSupport
{
public static int getPayloadSize(object target, Type targetType, ref int size)
{
FieldInfo[] fields = targetType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
getFieldSize(field, target, ref size);
}
return size;
}
public static int getFieldSize(FieldInfo field, object target, ref int size)
{
if (field.FieldType == typeof(char) ||
field.FieldType == typeof(byte) ||
field.FieldType == typeof(byte) ||
field.FieldType == typeof(sbyte))
{
size += 1;
}
else if (field.FieldType == typeof(char[]) ||
field.FieldType == typeof(byte[]) ||
field.FieldType == typeof(byte[]) ||
field.FieldType == typeof(sbyte[]))
{
byte[] values = (byte[])field.GetValue(target);
size += 1 * ((Array)field.GetValue(target)).Length;
}
else if (field.FieldType == typeof(short) ||
field.FieldType == typeof(ushort) ||
field.FieldType == typeof(short) ||
field.FieldType == typeof(ushort))
{
alignIndex(ref size, 2);
size += 2;
}
else if (field.FieldType == typeof(short[]) ||
field.FieldType == typeof(ushort[]) ||
field.FieldType == typeof(short[]) ||
field.FieldType == typeof(ushort[]))
{
alignIndex(ref size, 2);
size += 2 * ((Array)field.GetValue(target)).Length;
}
else if (field.FieldType == typeof(int) ||
field.FieldType == typeof(uint) ||
field.FieldType == typeof(int) ||
field.FieldType == typeof(uint) ||
field.FieldType == typeof(float))
{
alignIndex(ref size, 4);
size += 4;
}
else if (field.FieldType == typeof(int[]) ||
field.FieldType == typeof(uint[]) ||
field.FieldType == typeof(int[]) ||
field.FieldType == typeof(uint[]) ||
field.FieldType == typeof(float[]))
{
alignIndex(ref size, 4);
size += 4 * ((Array)field.GetValue(target)).Length;
}
else if (field.FieldType == typeof(long) ||
field.FieldType == typeof(ulong) ||
field.FieldType == typeof(long) ||
field.FieldType == typeof(ulong) ||
field.FieldType == typeof(double))
{
alignIndex(ref size, 8);
size += 8;
}
else if (field.FieldType == typeof(long[]) ||
field.FieldType == typeof(ulong[]) ||
field.FieldType == typeof(long[]) ||
field.FieldType == typeof(ulong[]) ||
field.FieldType == typeof(double[]))
{
alignIndex(ref size, 8);
size += 8 * ((Array)field.GetValue(target)).Length;
}
else if (field.FieldType.IsArray) // Array of classes
{
alignIndex(ref size, 4);
Array targetArray = (Array)field.GetValue(target);
int arraySize = targetArray.Length;
object[] objectArray = (object[])field.GetValue(target);
var arrayElementType = objectArray.GetType().GetElementType();
for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++)
{
object arrayItem = objectArray[arrayIndex];
Type arrayItemType = arrayItem.GetType();
FieldInfo[] subfields = arrayItemType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo subfield in subfields)
{
Type subfieldType = subfield.GetType();
Type elementType = subfield.FieldType.GetElementType();
getFieldSize(subfield, arrayItem, ref size);
}
}
}
else // Class
{
alignIndex(ref size, 4);
object objectItem = field.GetValue(target);
FieldInfo[] subfields = field.FieldType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo subfield in subfields)
{
Type subfieldType = subfield.GetType();
Type elementType = subfield.FieldType.GetElementType();
getFieldSize(subfield, objectItem, ref size);
}
}
return size;
}
public static void alignIndex(ref int dataBufferIndex, int alignment)
{
int indexMisalignment = dataBufferIndex % alignment;
if (indexMisalignment > 0)
{
dataBufferIndex += alignment - indexMisalignment;
}
}
public static void serializeField(FieldInfo field,
byte[] dataBuffer,
ref int dataBufferIndex,
object target)
{
Type fieldType = field.GetType();
object fieldObject = field.GetValue(target);
if (field.FieldType == typeof(char) ||
field.FieldType == typeof(byte) ||
field.FieldType == typeof(byte) ||
field.FieldType == typeof(sbyte))
{
byte value = Convert.ToByte(field.GetValue(target));
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
}
else if (field.FieldType == typeof(char[]))
{
char[] values = (char[])field.GetValue(target);
foreach (char value in values)
{
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
}
}
else if (field.FieldType == typeof(byte[]) ||
field.FieldType == typeof(byte[]) ||
field.FieldType == typeof(sbyte[]))
{
byte[] values = (byte[])field.GetValue(target);
foreach (byte value in values)
{
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
}
}
else if (field.FieldType == typeof(short) ||
field.FieldType == typeof(ushort) ||
field.FieldType == typeof(short) ||
field.FieldType == typeof(ushort))
{
alignIndex(ref dataBufferIndex, 2);
ushort value = Convert.ToUInt16(field.GetValue(target));
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 8 & 0xFF);
}
else if (field.FieldType == typeof(short[]) ||
field.FieldType == typeof(ushort[]) ||
field.FieldType == typeof(short[]) ||
field.FieldType == typeof(ushort[]))
{
alignIndex(ref dataBufferIndex, 2);
ushort[] values = (ushort[])field.GetValue(target);
foreach (char value in values)
{
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 8 & 0xFF);
}
}
else if (field.FieldType == typeof(int) ||
field.FieldType == typeof(uint) ||
field.FieldType == typeof(int) ||
field.FieldType == typeof(uint))
{
alignIndex(ref dataBufferIndex, 4);
uint value = Convert.ToUInt32(field.GetValue(target));
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 8 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 16 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 24 & 0xFF);
}
else if (field.FieldType == typeof(float))
{
alignIndex(ref dataBufferIndex, 4);
float floatValue = (float)field.GetValue(target);
byte[] valueArray = BitConverter.GetBytes(floatValue);
dataBuffer[dataBufferIndex++] = valueArray[0];
dataBuffer[dataBufferIndex++] = valueArray[1];
dataBuffer[dataBufferIndex++] = valueArray[2];
dataBuffer[dataBufferIndex++] = valueArray[3];
}
else if (field.FieldType == typeof(int[]) ||
field.FieldType == typeof(uint[]) ||
field.FieldType == typeof(int[]) ||
field.FieldType == typeof(uint[]))
{
alignIndex(ref dataBufferIndex, 4);
uint[] values = (uint[])field.GetValue(target);
foreach (uint value in values)
{
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 8 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 16 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 24 & 0xFF);
}
}
else if (field.FieldType == typeof(float[]))
{
alignIndex(ref dataBufferIndex, 4);
float[] values = (float[])field.GetValue(target);
foreach (float floatValue in values)
{
byte[] valueArray = BitConverter.GetBytes(floatValue);
dataBuffer[dataBufferIndex++] = valueArray[0];
dataBuffer[dataBufferIndex++] = valueArray[1];
dataBuffer[dataBufferIndex++] = valueArray[2];
dataBuffer[dataBufferIndex++] = valueArray[3];
}
}
else if (field.FieldType == typeof(long) ||
field.FieldType == typeof(ulong) ||
field.FieldType == typeof(long) ||
field.FieldType == typeof(ulong))
{
alignIndex(ref dataBufferIndex, 8);
ulong value = Convert.ToUInt64(field.GetValue(target));
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 8 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 16 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 24 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 32 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 40 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 48 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 56 & 0xFF);
}
else if (field.FieldType == typeof(double))
{
alignIndex(ref dataBufferIndex, 8);
double doubleValue = (double)field.GetValue(target);
byte[] valueArray = BitConverter.GetBytes(doubleValue);
dataBuffer[dataBufferIndex++] = valueArray[0];
dataBuffer[dataBufferIndex++] = valueArray[1];
dataBuffer[dataBufferIndex++] = valueArray[2];
dataBuffer[dataBufferIndex++] = valueArray[3];
dataBuffer[dataBufferIndex++] = valueArray[4];
dataBuffer[dataBufferIndex++] = valueArray[5];
dataBuffer[dataBufferIndex++] = valueArray[6];
dataBuffer[dataBufferIndex++] = valueArray[7];
}
else if (field.FieldType == typeof(long[]) ||
field.FieldType == typeof(ulong[]) ||
field.FieldType == typeof(long[]) ||
field.FieldType == typeof(ulong[]))
{
alignIndex(ref dataBufferIndex, 8);
ulong[] values = (ulong[])field.GetValue(target);
foreach (ulong value in values)
{
dataBuffer[dataBufferIndex++] = (byte)(value & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 8 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 16 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 24 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 32 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 40 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 48 & 0xFF);
dataBuffer[dataBufferIndex++] = (byte)(value >> 56 & 0xFF);
}
}
else if (field.FieldType == typeof(double[]))
{
alignIndex(ref dataBufferIndex, 8);
double[] values = (double[])field.GetValue(target);
foreach (double doubleValue in values)
{
byte[] valueArray = BitConverter.GetBytes(doubleValue);
dataBuffer[dataBufferIndex++] = valueArray[0];
dataBuffer[dataBufferIndex++] = valueArray[1];
dataBuffer[dataBufferIndex++] = valueArray[2];
dataBuffer[dataBufferIndex++] = valueArray[3];
dataBuffer[dataBufferIndex++] = valueArray[4];
dataBuffer[dataBufferIndex++] = valueArray[5];
dataBuffer[dataBufferIndex++] = valueArray[6];
dataBuffer[dataBufferIndex++] = valueArray[7];
}
}
else if (field.FieldType.IsArray) // Array of classes
{
alignIndex(ref dataBufferIndex, 4);
Array targetArray = (Array)field.GetValue(target);
int arraySize = targetArray.Length;
object[] objectArray = (object[])field.GetValue(target);
Type arrayElementType = objectArray.GetType().GetElementType();
for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++)
{
object arrayItem = objectArray[arrayIndex];
Type arrayItemType = arrayItem.GetType();
FieldInfo[] subfields = arrayItemType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo subfield in subfields)
{
Type subfieldType = subfield.GetType();
Type elementType = subfield.FieldType.GetElementType();
serializeField(subfield, dataBuffer, ref dataBufferIndex, arrayItem);
}
}
}
else // Class
{
alignIndex(ref dataBufferIndex, 4);
FieldInfo[] subfields = fieldObject.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo subfield in subfields)
{
Type subfieldType = subfield.GetType();
Type elementType = subfield.FieldType.GetElementType();
serializeField(subfield, dataBuffer, ref dataBufferIndex, fieldObject);
}
}
}
public static void deserializeField(FieldInfo field,
byte[] dataBuffer,
ref int dataBufferIndex,
object target)
{
Type fieldType = field.GetType();
object fieldObject = field.GetValue(target);
if (field.FieldType == typeof(char))
{
char value = Convert.ToChar(dataBuffer[dataBufferIndex++]);
field.SetValue(target, value);
}
else if (field.FieldType == typeof(byte) ||
field.FieldType == typeof(byte))
{
byte value = dataBuffer[dataBufferIndex++];
field.SetValue(target, value);
}
else if (field.FieldType == typeof(sbyte))
{
sbyte value = Convert.ToSByte(dataBuffer[dataBufferIndex++]);
field.SetValue(target, value);
}
else if (field.FieldType == typeof(char[]))
{
char[] values = (char[])field.GetValue(target);
for (int index = 0; index < values.Length; index++)
{
values[index] = (char)dataBuffer[dataBufferIndex++];
}
field.SetValue(target, values);
}
else if (field.FieldType == typeof(byte[]) ||
field.FieldType == typeof(byte[]))
{
byte[] values = (byte[])field.GetValue(target);
for (int index = 0; index < values.Length; index++)
{
values[index] = dataBuffer[dataBufferIndex++];
}
field.SetValue(target, values);
}
else if (field.FieldType == typeof(sbyte[]))
{
sbyte[] values = (sbyte[])field.GetValue(target);
for (int index = 0; index < values.Length; index++)
{
values[index] = (sbyte)dataBuffer[dataBufferIndex++];
}
field.SetValue(target, values);
}
else if (field.FieldType == typeof(short) ||
field.FieldType == typeof(ushort) ||
field.FieldType == typeof(short) ||
field.FieldType == typeof(ushort))
{
alignIndex(ref dataBufferIndex, 2);
ushort value = (ushort)(dataBuffer[dataBufferIndex++] +
(ushort)(dataBuffer[dataBufferIndex++] << 8));
if (field.FieldType == typeof(short) ||
field.FieldType == typeof(short))
{
field.SetValue(target, Convert.ToInt16(value));
}
else
{
field.SetValue(target, value);
}
}
else if (field.FieldType == typeof(short[]) ||
field.FieldType == typeof(ushort[]) ||
field.FieldType == typeof(short[]) ||
field.FieldType == typeof(ushort[]))
{
alignIndex(ref dataBufferIndex, 2);
ushort[] values = (ushort[])field.GetValue(target);
for (int index = 0; index < values.Length; index++)
{
values[index] = (ushort)(dataBuffer[dataBufferIndex++] +
(ushort)(dataBuffer[dataBufferIndex++] << 8));
}
field.SetValue(target, values);
}
else if (field.FieldType == typeof(int) ||
field.FieldType == typeof(uint) ||
field.FieldType == typeof(int) ||
field.FieldType == typeof(uint))
{
alignIndex(ref dataBufferIndex, 4);
uint value = dataBuffer[dataBufferIndex++] +
((uint)dataBuffer[dataBufferIndex++] << 8) +
((uint)dataBuffer[dataBufferIndex++] << 16) +
((uint)dataBuffer[dataBufferIndex++] << 24);
if (field.FieldType == typeof(int) ||
field.FieldType == typeof(int))
{
field.SetValue(target, Convert.ToInt32(value));
}
else
{
field.SetValue(target, value);
}
}
else if (field.FieldType == typeof(int[]) ||
field.FieldType == typeof(uint[]) ||
field.FieldType == typeof(int[]) ||
field.FieldType == typeof(uint[]))
{
alignIndex(ref dataBufferIndex, 4);
uint[] values = (uint[])field.GetValue(target);
for (int index = 0; index < values.Length; index++)
{
values[index] = dataBuffer[dataBufferIndex++] +
((uint)dataBuffer[dataBufferIndex++] << 8) +
((uint)dataBuffer[dataBufferIndex++] << 16) +
((uint)dataBuffer[dataBufferIndex++] << 24);
}
field.SetValue(target, values);
}
else if (field.FieldType == typeof(float))
{
alignIndex(ref dataBufferIndex, 4);
float singleValue = BitConverter.ToSingle(dataBuffer, dataBufferIndex);
dataBufferIndex += 4;
field.SetValue(target, singleValue);
}
else if (field.FieldType == typeof(float[]))
{
alignIndex(ref dataBufferIndex, 4);
float[] values = (float[])field.GetValue(target);
for (int index = 0; index < values.Length; index++)
{
values[index] = BitConverter.ToSingle(dataBuffer, dataBufferIndex);
dataBufferIndex += 4;
}
field.SetValue(target, values);
}
else if (field.FieldType == typeof(long) ||
field.FieldType == typeof(ulong) ||
field.FieldType == typeof(long) ||
field.FieldType == typeof(ulong))
{
alignIndex(ref dataBufferIndex, 8);
uint value = dataBuffer[dataBufferIndex++] +
((uint)dataBuffer[dataBufferIndex++] << 8) +
((uint)dataBuffer[dataBufferIndex++] << 16) +
((uint)dataBuffer[dataBufferIndex++] << 24) +
((uint)dataBuffer[dataBufferIndex++] << 32) +
((uint)dataBuffer[dataBufferIndex++] << 40) +
((uint)dataBuffer[dataBufferIndex++] << 48) +
((uint)dataBuffer[dataBufferIndex++] << 56);
if (field.FieldType == typeof(long) ||
field.FieldType == typeof(long))
{
field.SetValue(target, Convert.ToInt64(value));
}
else
{
field.SetValue(target, value);
}
}
else if (field.FieldType == typeof(long[]) ||
field.FieldType == typeof(ulong[]) ||
field.FieldType == typeof(long[]) ||
field.FieldType == typeof(ulong[]))
{
alignIndex(ref dataBufferIndex, 8);
ulong[] values = (ulong[])field.GetValue(target);
for (int index = 0; index < values.Length; index++)
{
values[index] = dataBuffer[dataBufferIndex++] +
((uint)dataBuffer[dataBufferIndex++] << 8) +
((uint)dataBuffer[dataBufferIndex++] << 16) +
((uint)dataBuffer[dataBufferIndex++] << 24) +
((uint)dataBuffer[dataBufferIndex++] << 32) +
((uint)dataBuffer[dataBufferIndex++] << 40) +
((uint)dataBuffer[dataBufferIndex++] << 48) +
((uint)dataBuffer[dataBufferIndex++] << 56);
}
field.SetValue(target, values);
}
else if (field.FieldType == typeof(double))
{
alignIndex(ref dataBufferIndex, 8);
field.SetValue(target, BitConverter.ToDouble(dataBuffer, dataBufferIndex));
dataBufferIndex += 8;
}
else if (field.FieldType == typeof(double[]))
{
alignIndex(ref dataBufferIndex, 8);
double[] values = (double[])field.GetValue(target);
for (int index = 0; index < values.Length; index++)
{
values[index] = BitConverter.ToDouble(dataBuffer, dataBufferIndex);
dataBufferIndex += 8;
}
field.SetValue(target, values);
}
else if (field.FieldType.IsArray)
{
alignIndex(ref dataBufferIndex, 4);
Array targetArray = (Array)field.GetValue(target);
int arraySize = targetArray.Length;
object[] objectArray = (object[])field.GetValue(target);
Type arrayElementType = objectArray.GetType().GetElementType();
for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++)
{
object arrayItem = objectArray[arrayIndex];
Type arrayItemType = arrayItem.GetType();
FieldInfo[] subfields = arrayItemType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo subfield in subfields)
{
Type subfieldType = subfield.GetType();
Type elementType = subfield.FieldType.GetElementType();
deserializeField(subfield, dataBuffer, ref dataBufferIndex, arrayItem);
}
}
}
else
{
alignIndex(ref dataBufferIndex, 4);
FieldInfo[] subfields = fieldObject.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo subfield in subfields)
{
Type subfieldType = subfield.GetType();
object subfieldObject = subfield.GetValue(fieldObject);
Type elementType = subfield.FieldType.GetElementType();
deserializeField(subfield, dataBuffer, ref dataBufferIndex, fieldObject);
}
}
}
}
}
//\\<Unclassified>
//----------------------------------------------------------------------------//
// UNCLASSIFIED //
//----------------------------------------------------------------------------//
//\\<\Unclassified>

View File

@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(SolutionDir)Solution.props" />
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<AssemblyName>Raytheon.Instruments.COECommDevice</AssemblyName>
<Description>Specialized instrument for running real time Build In Tests via COE implementing ICommDevice interface</Description>
<!-- Static versioning (Suitable for Development) -->
<!-- Disable the line below for dynamic versioning -->
<Version>1.0.0</Version>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog" Version="5.0.0" />
<PackageReference Include="Raytheon.Common" Version="1.0.0" />
<PackageReference Include="Raytheon.Instruments.BIT.Contracts" Version="1.4.0" />
<PackageReference Include="Raytheon.Instruments.CommDevice.Contracts" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\COEComm\COEComm.csproj" />
</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>

View File

@@ -0,0 +1,859 @@
// **********************************************************************************************************
// COECommDeviceInstrument.cs
// 7/11/2022
// 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 System;
using Raytheon.Instruments.MessagingUtilities;
using System.Xml.XPath;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.Threading;
using Raytheon.Common;
using Raytheon.Instruments.coeCSharp;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Globalization;
using NLog;
namespace Raytheon.Instruments
{
/// <summary>
/// This device supports different ways of communicating with other COE nodes
/// TCP
/// UDP
/// Serial
/// </summary>
public enum DriverType
{
Undefined,
TCP,
UDP,
Serial
};
public class COECommDeviceInstrument : ICommDevice
{
/// <summary>
/// Nlog Logger
/// </summary>
readonly ILogger _logger;
/// <summary>
/// Cancellation token to stop reading incoming messages
/// </summary>
private CancellationTokenSource _cancellationTokenSource = null;
/// <summary>
/// collection of the messages received
/// </summary>
private readonly Dictionary<Tuple<string, DateTime>, OeMessage> _messages;
/// <summary>
/// Raytheon configuration
/// </summary>
private readonly IConfigurationManager _configurationManager;
private readonly IConfiguration _configuration;
/// <summary>
/// UDP, TCP, Serial or Undefined
/// </summary>
private DriverType _driverType;
/// <summary>
/// dictionary of options when initializing COE endpoint and router
/// </summary>
private readonly Dictionary<string, List<KeyValuePair<string, string>>> _options = new Dictionary<string, List<KeyValuePair<string, string>>>();
/// <summary>
/// reference to the main wrapper class for Common Operating Environment
/// </summary>
private readonly coe _coe;
/// <summary>
/// COE endpoint
/// </summary>
private coeEndpoint _endpoint;
/// <summary>
/// used for initialization of the endpoint
/// </summary>
private uint _maxMessageSize;
private uint _epQueueDepth;
/// <summary>
/// collection of all labels with message names per every XML file
/// </summary>
private readonly Dictionary<string, Dictionary<uint, string>> _icds = new Dictionary<string, Dictionary<uint, string>>();
/// <summary>
/// timeout can be set for the reader in a separate call
/// </summary>
private uint _receiverTimeout;
/// <summary>
/// Number of milliseconds to wake up and check the message when receiving
/// </summary>
private int _checkForMessageIntervalMs;
/// <summary>
/// collection of response labels or messages that COE endpoint should be registered for
/// </summary>
private List<uint> _responseLabels = new List<uint>();
/// <summary>
/// collection of message XML documents (processed XML files) used in COE communications
/// </summary>
private readonly Dictionary<string, MessageXmlDocument> _xmlDocs = new Dictionary<string, MessageXmlDocument>();
/// <summary>
/// instrument constructor
/// </summary>
public COECommDeviceInstrument(string name, IConfigurationManager configurationManager, DriverType driverType = DriverType.Undefined, ILogger logger = null)
{
Info = new InstrumentMetadata
{
ModelNumber = "COECommDevice"
};
if(logger == null)
logger = LogManager.GetCurrentClassLogger();
_logger = logger;
Status = State.Uninitialized;
DetailedStatus = "COE Uninitialized";
Name = name;
if (LogManager.Configuration == null)
{
var assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(assemblyFolder + "\\nlog.config");
}
if (configurationManager == null)
{
_logger.Error($"Cannot create {Name} without a configuration manager");
return;
}
_configurationManager = configurationManager;
_configuration = _configurationManager.GetConfiguration(Name);
_messages = new Dictionary<Tuple<string, DateTime>, OeMessage>();
_driverType = driverType;
_coe = new coe();
}
public string DetailedStatus { get; protected set; }
public bool DisplayEnabled { get => false; set => throw new NotImplementedException(); }
public bool FrontPanelEnabled { get => false; set => throw new NotImplementedException(); }
public InstrumentMetadata Info { get; set; }
public string Name { get; protected set; }
public SelfTestResult SelfTestResult => PerformSelfTest();
public State Status { get; set; }
public bool ClearErrors()
{
return true;
}
/// <summary>
/// Initializes COE instrument
/// </summary>
public void Initialize()
{
_logger.Trace($"{Name}({_driverType}) Initializing...");
if (_driverType == DriverType.Undefined)
_driverType = _configuration.GetConfigurationValue<DriverType>("Parameters", "DriverType", "TCP");
_options.Clear();
_options.Add("ROUTER_CONFIG", new List<KeyValuePair<string, string>>
{
{ new KeyValuePair<string, string>("NODE_ID", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "NODE_ID", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_STATE", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "DISPLAY_DEBUG_STATE", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_LABEL_MESSAGE", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "DISPLAY_DEBUG_LABEL_MESSAGE", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_BRIDGE_REGISTRATION", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "DISPLAY_DEBUG_BRIDGE_REGISTRATION", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_ROUTER_DATABASE", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "DISPLAY_DEBUG_ROUTER_DATABASE", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_SEND", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "DISPLAY_DEBUG_SEND", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_RECV", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "DISPLAY_DEBUG_RECV", "0")) },
{ new KeyValuePair<string, string>("BUFFER_SIZE", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "BUFFER_SIZE", "256")) },
{ new KeyValuePair<string, string>("ENABLE_REGISTRATION_MESSAGES", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "ENABLE_REGISTRATION_MESSAGES", "1")) },
{ new KeyValuePair<string, string>("THREAD_STACK_SIZE", _configuration.GetConfigurationValue<string>("ROUTER_CONFIG", "THREAD_STACK_SIZE", "16384")) },
});
_options.Add("ROUTER_PROTOCOL_CONFIG", new List<KeyValuePair<string, string>>
{
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_SEND", _configuration.GetConfigurationValue<string>("ROUTER_PROTOCOL_CONFIG", "DISPLAY_DEBUG_SEND", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_RECV", _configuration.GetConfigurationValue<string>("ROUTER_PROTOCOL_CONFIG", "DISPLAY_DEBUG_RECV", "0")) },
{ new KeyValuePair<string, string>("THREAD_STACK_SIZE", _configuration.GetConfigurationValue<string>("ROUTER_PROTOCOL_CONFIG", "THREAD_STACK_SIZE", "16384")) },
});
var poolEntry = _configuration.GetConfigurationValue<string>("ROUTER_BUFFER_POOLS", "POOL_ENTRY", "100,32|50,128|100,384|150,1536|10,65535");
if (!string.IsNullOrEmpty(poolEntry))
{
var poolEntries = poolEntry.Split('|');
if (poolEntries.Any())
{
var entries = new List<KeyValuePair<string, string>>();
foreach (var entry in poolEntries)
{
entries.Add(new KeyValuePair<string, string>("POOL_ENTRY", entry));
}
_options.Add("ROUTER_BUFFER_POOLS", entries);
}
}
_options.Add("BASIC_REGISTRATION_CONFIG", new List<KeyValuePair<string, string>>
{
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_SEND", _configuration.GetConfigurationValue<string>("BASIC_REGISTRATION_CONFIG", "DISPLAY_DEBUG_SEND", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_SEND_BUFFER", _configuration.GetConfigurationValue<string>("BASIC_REGISTRATION_CONFIG", "DISPLAY_DEBUG_SEND_BUFFER", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_RECV", _configuration.GetConfigurationValue<string>("BASIC_REGISTRATION_CONFIG", "DISPLAY_DEBUG_RECV", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_RECV_BUFFER", _configuration.GetConfigurationValue<string>("BASIC_REGISTRATION_CONFIG", "DISPLAY_DEBUG_RECV_BUFFER", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_STATE", _configuration.GetConfigurationValue<string>("BASIC_REGISTRATION_CONFIG", "DISPLAY_DEBUG_STATE", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_PING_SEND", _configuration.GetConfigurationValue<string>("BASIC_REGISTRATION_CONFIG", "DISPLAY_DEBUG_PING_SEND", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_PING_RECV", _configuration.GetConfigurationValue<string>("BASIC_REGISTRATION_CONFIG", "DISPLAY_DEBUG_PING_RECV", "0")) },
{ new KeyValuePair<string, string>("THREAD_STACK_SIZE", _configuration.GetConfigurationValue<string>("BASIC_REGISTRATION_CONFIG", "THREAD_STACK_SIZE", "16384")) },
});
switch (_driverType)
{
case DriverType.UDP:
_options.Add("UDP_MEDIA_BINDING_CONFIG", new List<KeyValuePair<string, string>>
{
{ new KeyValuePair<string, string>("LOCAL_IP_ADDRESS", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "LOCAL_IP_ADDRESS", "127.0.0.1")) },
{ new KeyValuePair<string, string>("REMOTE_IP_ADDRESS", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "REMOTE_IP_ADDRESS", "127.0.0.1")) },
{ new KeyValuePair<string, string>("LOCAL_SEND_PORT", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "LOCAL_SEND_PORT", "32010")) },
{ new KeyValuePair<string, string>("LOCAL_RECV_PORT", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "LOCAL_RECV_PORT", "32020")) },
{ new KeyValuePair<string, string>("REMOTE_SEND_PORT", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "REMOTE_SEND_PORT", "32011")) },
{ new KeyValuePair<string, string>("REMOTE_RECV_PORT", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "REMOTE_RECV_PORT", "32021")) },
{ new KeyValuePair<string, string>("RECV_TIMEOUT", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "RECV_TIMEOUT", "200")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_SEND", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_SEND", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_RECV", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_RECV", "0")) },
{ new KeyValuePair<string, string>("MTU_SIZE", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "MTU_SIZE", "1472")) },
{ new KeyValuePair<string, string>("THREAD_STACK_SIZE", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "THREAD_STACK_SIZE", "16384")) },
{ new KeyValuePair<string, string>("THREAD_NAME", _configuration.GetConfigurationValue<string>("UDP_MEDIA_BINDING_CONFIG", "THREAD_NAME", "UDP_MB_RCV")) },
});
break;
case DriverType.TCP:
_options.Add("TCP_MEDIA_BINDING_CONFIG", new List<KeyValuePair<string, string>>
{
{ new KeyValuePair<string, string>("LOCAL_PORT", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "LOCAL_PORT", "9990")) },
{ new KeyValuePair<string, string>("NUM_PORTS", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "NUM_PORTS", "32")) },
{ new KeyValuePair<string, string>("NUM_DYNAMIC_NODES", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "NUM_DYNAMIC_NODES", "32")) },
{ new KeyValuePair<string, string>("SERVER_ADDRESS", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "SERVER_ADDRESS", "127.0.0.1:9990")) },
{ new KeyValuePair<string, string>("UDP_TX_BUFFER_SIZE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "UDP_TX_BUFFER_SIZE", "5000")) },
{ new KeyValuePair<string, string>("UDP_RX_BUFFER_SIZE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "UDP_RX_BUFFER_SIZE", "32768")) },
{ new KeyValuePair<string, string>("TCP_TX_BUFFER_SIZE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "TCP_TX_BUFFER_SIZE", "5000")) },
{ new KeyValuePair<string, string>("TCP_RX_BUFFER_SIZE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "TCP_RX_BUFFER_SIZE", "4096")) },
{ new KeyValuePair<string, string>("PACKET_SIZE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "PACKET_SIZE", "5128")) },
{ new KeyValuePair<string, string>("TCP_SELECT_VALUE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "TCP_SELECT_VALUE", "1")) },
{ new KeyValuePair<string, string>("DISABLE_NAG_DELAY", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISABLE_NAG_DELAY", "1")) },
{ new KeyValuePair<string, string>("TIMER_RATE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "TIMER_RATE", "1000")) },
{ new KeyValuePair<string, string>("CONNECT_KA_RATE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "CONNECT_KA_RATE", "1")) },
{ new KeyValuePair<string, string>("RECV_KA_RATE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "RECV_KA_RATE", "1")) },
{ new KeyValuePair<string, string>("SERVER_CONNECT_RATE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "SERVER_CONNECT_RATE", "1")) },
{ new KeyValuePair<string, string>("RECV_THREAD_STACK_SIZE", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "RECV_THREAD_STACK_SIZE", "4096")) },
{ new KeyValuePair<string, string>("RECV_THREAD_PRIORITY", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "RECV_THREAD_PRIORITY", "0")) },
{ new KeyValuePair<string, string>("RECV_THREAD_AFFINITY", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "RECV_THREAD_AFFINITY", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_SEND", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_SEND", "1")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_SEND_BUFFER", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_SEND_BUFFER", "1")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_UDP_RECV", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_UDP_RECV", "1")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_UDP_RECV_BUFFER", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_UDP_RECV_BUFFER", "1")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_TCP_RECV", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_TCP_RECV", "1")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_TCP_RECV_BUFFER", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_TCP_RECV_BUFFER", "1")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_RECV", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_RECV", "1")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_RECV_BUFFER", _configuration.GetConfigurationValue<string>("TCP_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_RECV_BUFFER", "1")) },
});
break;
case DriverType.Serial:
_options.Add("SERIAL_MEDIA_BINDING_CONFIG", new List<KeyValuePair<string, string>>
{
{ new KeyValuePair<string, string>("DEVICE_NAME", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "DEVICE_NAME", "\\\\.\\COM1")) },
{ new KeyValuePair<string, string>("BAUD_RATE", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "BAUD_RATE", "9600")) },
{ new KeyValuePair<string, string>("DATA_BITS", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "DATA_BITS", "8")) },
{ new KeyValuePair<string, string>("STOP_BITS", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "STOP_BITS", "1")) },
{ new KeyValuePair<string, string>("PARITY", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "PARITY", "0")) },
{ new KeyValuePair<string, string>("FLOW_CONTROL", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "FLOW_CONTROL", "0")) },
{ new KeyValuePair<string, string>("MTU_SIZE", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "MTU_SIZE", "256")) },
{ new KeyValuePair<string, string>("RECV_PROCESSING_DELAY", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "RECV_PROCESSING_DELAY", "100")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_SEND", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_SEND", "0")) },
{ new KeyValuePair<string, string>("DISPLAY_DEBUG_RECV", _configuration.GetConfigurationValue<string>("SERIAL_MEDIA_BINDING_CONFIG", "DISPLAY_DEBUG_RECV", "0")) },
});
break;
default:
_logger.Error($"{Name}({_driverType}) Configured driver type not valid");
break;
}
_maxMessageSize = _configuration.GetConfigurationValue<uint>("Parameters", "MaxMessageSize", "5000");
_epQueueDepth = _configuration.GetConfigurationValue<uint>("Parameters", "EPQueueDepth", "5000");
_checkForMessageIntervalMs = _configuration.GetConfigurationValue<int>("Parameters", "CheckForMessageIntervalMs", "100");
var responseLabels = _configuration.GetConfigurationListValue("ResponseMessageIds", "ResponseLabel", new List<string> { "1", "2" });
var bitFilePaths = _configuration.GetConfigurationListValue("BitFilePaths", "FilePath", new List<string> { "File1", "File2" });
_xmlDocs.Clear();
foreach (var path in bitFilePaths)
{
_xmlDocs.Add(path, new MessageXmlDocument(path, _logger));
}
_icds.Clear();
foreach (var path in bitFilePaths)
{
_icds.Add(path, ProcessFileForNamesAndLabels(path));
}
foreach (var strLabel in responseLabels)
{
uint label = GetLabelFromMessageId(strLabel);
if(label > 0)
_responseLabels.Add(label);
}
DetailedStatus = "COE Initialized";
Status = State.Ready;
}
/// <summary>
/// performs self-test
/// </summary>
/// <returns></returns>
public SelfTestResult PerformSelfTest()
{
_logger.Trace($"{Name}({_driverType}) Performing Self Test...");
// TODO implement method
return SelfTestResult.Pass;
}
/// <summary>
/// Resets COE device comms
/// </summary>
/// <exception cref="NotImplementedException"></exception>
public void Reset()
{
_logger.Trace($"{Name}({_driverType}) Resetting...");
Close();
Open();
}
/// <summary>
/// Shuts down COE device
/// </summary>
public void Shutdown()
{
_logger.Trace($"{Name}({_driverType}) Shutting Down...");
try
{
Close();
//coe.UnloadImportedDll("coeWindows-shared.dll");
}
catch (Exception ex)
{
_logger.Error(ex, $"{Name}({_driverType}) Error while closing");
}
}
#region ICommDevice functions
/// <summary>
/// Opens COE connection
/// </summary>
/// <exception cref="NotImplementedException"></exception>
public void Open()
{
_logger.Trace($"{Name}({_driverType}) Opening...");
try
{
switch (_driverType)
{
case DriverType.TCP:
if (_coe.tcp_media_binding_configure(_options, _logger) != coe.Status.SUCCESS)
{
_logger.Error($"{Name}({_driverType}) COE TCP media binding initialization failure.\nTry checking your connection configuration.\nYou could have a port collision.");
Status = State.CommunicationFailure;
throw new Exception($"{Name}({_driverType}) COE TCP media binding initialization failure");
}
_logger.Trace($"{Name}({_driverType}) COE TCP media binding initialization, {_coe.ProtocolCmitName}");
break;
case DriverType.UDP:
if (_coe.udp_media_binding_configure(_options, _logger) != coe.Status.SUCCESS)
{
_logger.Error($"{Name}({_driverType}) COE UDP media binding initialization failure.\nTry checking your connection configuration.\nYou could have a port collision.");
Status = State.CommunicationFailure;
throw new Exception($"{Name}({_driverType}) COE UDP media binding initialization failure");
}
_logger.Trace($"{Name}({_driverType}) COE UDP media binding initialization, Local: {_coe.ProtocolCmitName} Remote: {_coe.ProtocolName}");
break;
case DriverType.Serial:
if (_coe.serial_media_binding_configure(_options, _logger) != coe.Status.SUCCESS)
{
_logger.Error($"{Name}({_driverType}) COE Serial media binding initialization failure.\nTry checking your connection configuration.\nYou could have a port collision.");
Status = State.CommunicationFailure;
throw new Exception($"{Name}({_driverType}) COE Serial media binding initialization failure");
}
_logger.Trace($"{Name}({_driverType}) COE Serial media binding initialization, {_coe.ProtocolCmitName}");
break;
default:
_logger.Error($"{Name}({_driverType}) Configured driver type not valid");
throw new Exception($"{Name}({_driverType}) Configured driver type not valid");
}
foreach (var item in _options)
{
_logger.Trace($"{item.Key}:");
foreach (var pair in item.Value)
{
_logger.Trace(string.Format("{0,-50} {1, -40}", pair.Key, pair.Value));
}
}
}
catch (Exception ex)
{
_logger.Error(ex);
Status = State.CommunicationFailure;
DetailedStatus = "Unable to Open";
throw;
}
try
{
_coe.SetConnected(true);
//_endpoint = new coeEndpoint(_maxMessageSize, _epQueueDepth, coe.Router);
_endpoint = new coeEndpoint(_maxMessageSize, _epQueueDepth);
_logger.Info($"{Name}({_driverType}) Endpoint Created, Max Message Size: {_maxMessageSize}, Queue Depth: {_epQueueDepth}");
foreach (var item in _responseLabels)
{
var fileName = WhichFileContainsTheLabel(item);
if (!string.IsNullOrEmpty(fileName))
{
var msgName = _icds[fileName][item];
if (!string.IsNullOrEmpty(msgName))
{
_endpoint.Register(item);
_logger.Debug($"{Name}({_driverType}) Registering new message with the endpoint, {item}: {msgName}");
}
else
{
_logger.Warn($"{Name}({_driverType}) Message with label {item} is not located in file {fileName}");
}
}
else
{
_logger.Warn($"{Name}({_driverType}) Unable to locate label {item} in any of the XML files registered for COE device");
}
}
_cancellationTokenSource = new CancellationTokenSource();
Task.Run(() => ReadMessages(_cancellationTokenSource.Token));
DetailedStatus = "Opened";
}
catch (Exception ex)
{
Status = State.CommunicationFailure;
DetailedStatus = "Unable to Open";
_logger.Error(ex);
throw;
}
}
/// <summary>
/// Close COE endpoint
/// </summary>
/// <exception cref="NotImplementedException"></exception>
public void Close()
{
_logger.Trace($"{Name}({_driverType}) Closing ...");
_cancellationTokenSource?.Cancel();
Thread.Sleep(1000);
lock (this)
{
_messages.Clear();
}
_coe.SetConnected(false);
var status = _driverType == DriverType.TCP ?
_coe.TCP_media_binding_shutdown(_logger) : _driverType == DriverType.UDP ?
_coe.UDP_media_binding_shutdown(_logger) : _coe.SERIAL_media_binding_shutdown(_logger);
if (status != coe.Status.SUCCESS)
{
_logger.Error($"{_driverType} media binding shutdown failure, status {status}");
}
else
{
_logger.Debug($"{_driverType} shutdown was successful");
}
_endpoint?.Dispose();
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = null;
Status = State.Uninitialized;
DetailedStatus = "COE Closed";
}
/// <summary>
/// sets the timeout value for COE reading operation
/// </summary>
/// <param name="timeout"></param>
/// <exception cref="NotImplementedException"></exception>
public void SetReadTimeout(uint timeout)
{
_logger.Trace($"{Name}({_driverType}) Setting read timeout {timeout} ms ...");
_receiverTimeout = timeout;
}
/// <summary>
/// reads COE message either based on the label or just top message
/// </summary>
/// <param name="dataRead">
/// might contain a COE label
/// </param>
/// <returns></returns>
public uint Read(ref byte[] dataRead)
{
_logger.Trace($"{Name}({_driverType}) Reading ...");
if (!_coe.IsConnected)
{
_logger.Error("Error reading COE message, COE not connected");
return 0;
}
// if the label was provided in the byte array use it to locate the first message with that name
// else just fetch the top message
var label = FromByteArrayToXml(dataRead);
KeyValuePair<Tuple<string, DateTime>, OeMessage> message;
lock (this)
{
message = string.IsNullOrEmpty(label) ? _messages.FirstOrDefault() : _messages.FirstOrDefault(m => m.Key.Item1 == label);
}
if (message.Value != null)
{
// make a copy of the buffer
var buffer = message.Value.GetManagedBuffer();
if(buffer != null)
{
Array.Copy(buffer, 0, dataRead, 0, buffer.Length);
lock (this)
{
if (!_messages.Remove(message.Key))
_logger.Warn($"{Name}({_driverType}) Unable to remove a message from the dictionary, label = {message.Key}");
}
}
else
{
_logger.Error($"{Name}({_driverType}) Found a message with label {label}, but the Buffer is empty");
return 0;
}
}
else
{
_logger.Error(string.IsNullOrEmpty(label) ? $"{Name}({_driverType}) No messages available to read at this time" : $"{Name}({_driverType}) Unable to find message with label {label}");
return 0;
}
return (uint)dataRead.Length;
}
/// <summary>
/// keep reading messages and stash them in _messages dictionary with label and timestamp as a key
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private void ReadMessages(CancellationToken cancellationToken)
{
_logger.Debug($"{Name}({_driverType}) Starting to read messages.");
try
{
while (!cancellationToken.IsCancellationRequested)
{
_logger.Debug($"{Name}({_driverType}) Checking for messages...");
var status = _endpoint.Wait(1000);
if (status == coe.Status.SUCCESS)
{
_logger.Debug($"{Name}({_driverType}) Message Received...");
while (_endpoint.Peek(out uint label, out uint size, out int priority) == coe.Status.SUCCESS)
{
_logger.Debug($"{Name}({_driverType}) Identified message by peeking...");
var xmlDoc = WhichFileContainsTheLabel(label);
var message = new OeMessage((int)size + 1)
{
XmlMessage = new Message(_xmlDocs[xmlDoc], label.ToString())
};
status = _endpoint.Receive(message);
if (status == coe.Status.SUCCESS)
{
_logger.Debug($"{Name}({_driverType}) Successfully read message...");
lock (this)
{
_messages.Add(new Tuple<string, DateTime>(message.Label, DateTime.Now), message);
}
}
else
{
_logger.Error($"{Name}({_driverType}) Endpoint Receive Failed. Status = {status}");
}
}
}
// If not timeout and no cancellation requested
else if (status != coe.Status.FAILED_TIMEOUT && !cancellationToken.IsCancellationRequested)
{
_logger.Error($"{Name}({_driverType}) Event Flag Wait Failed. Status = {status}");
}
}
_logger.Debug($"{Name}({_driverType}) Stopping to read messages. Cancellation was requested.");
}
catch (Exception ex)
{
_logger.Error(ex);
}
}
/// <summary>
/// Writes COE message
/// </summary>
/// <param name="data"></param>
/// <param name="numBytesToWrite"></param>
/// <returns></returns>
public uint Write(byte[] data, uint numBytesToWrite)
{
_logger.Debug($"{Name}({_driverType}) Starting to write messages.");
if (!_coe.IsConnected)
{
_logger.Error($"{Name}({_driverType}) Error sending COE message, COE not connected");
return (uint)coe.Status.FAILED_NOT_ENABLED;
}
try
{
var xmlData = FromByteArrayToXml(data);
var messageName = GetMessageNameFromXml(xmlData);
var message = new OeMessage(new Message(messageName, new MessageXmlDocument(xmlData, _logger)));
//var status = _endpoint.Send(message, (uint)(_driverType == DriverType.TCP ? 0x01 : 0));
var status = _endpoint.Send(message);
if (status != coe.Status.SUCCESS)
{
_logger.Error($"{Name}({_driverType}) Error sending COE message, error code: {status}");
}
return status == coe.Status.ERROR ? (uint)coe.Status.FAILED_INTERNAL_ERROR : (uint)status;
}
catch (Exception ex)
{
_logger.Error(ex, $"{Name}({_driverType}) Error while writing a message");
return (uint)coe.Status.FAILED_INTERNAL_ERROR;
}
}
#endregion
/// <summary>
/// if byte array contains byte representation of XML then returns XML string
/// else returns empty string
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private static string FromByteArrayToXml(byte[] data) => System.Text.Encoding.Default.GetString(data);
private static byte[] FromStringToByteArray(string data) => System.Text.Encoding.UTF8.GetBytes(data);
/// <summary>
/// Extract message node from XML for the OeMessage class
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
private string GetMessageNameFromXml(string xmlData)
{
var doc = new XPathDocument(xmlData);
XPathNavigator navigator = doc.CreateNavigator();
var nodeset = navigator.Select("//@Message");
nodeset.MoveNext();
return nodeset.Current.InnerXml;
}
/// <summary>
/// if message id can be converted to uint returns the value
/// otherwise returns the related label from the message id by dictionary lookup
/// </summary>
/// <param name="label"></param>
/// <returns></returns>
private uint GetLabelFromMessageId(string messageId)
{
uint labelId = FromStringToUint(messageId);
if (labelId == 0)
{
foreach (var file in _icds)
{
var item = file.Value.FirstOrDefault(l => l.Value == messageId);
if (!string.IsNullOrEmpty(item.Value))
return item.Key;
}
}
return labelId;
}
/// <summary>
/// return file path for the file that contains the label
/// </summary>
/// <param name="label"></param>
/// <returns></returns>
private string WhichFileContainsTheLabel(uint label)
{
foreach (var item in _icds)
{
if (item.Value.Keys.Contains(label))
{
return item.Key;
}
}
return string.Empty;
}
/// <summary>
/// reads xml file and extracts all message names with associated labels
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private Dictionary<uint, string> ProcessFileForNamesAndLabels(string filePath)
{
var doc = new XPathDocument(filePath);
XPathNavigator node = doc.CreateNavigator();
XPathNodeIterator nodeset = node.Select("interface/message");
var result = new Dictionary<uint, string>();
while (nodeset.MoveNext())
{
var children = nodeset.Current.SelectChildren(XPathNodeType.Element);
if (children.Count > 0)
{
string strName = string.Empty;
string strLabel = string.Empty;
while (children.MoveNext())
{
if (children.Current.Name == "name")
{
strName = children.Current.Value;
if (!string.IsNullOrEmpty(strName))
strName = strName.Trim();
}
else if (children.Current.Name == "label")
{
strLabel = children.Current.Value;
if (!string.IsNullOrEmpty(strLabel))
strLabel = strLabel.Trim();
}
}
uint iLabel = FromStringToUint(strLabel);
if (!string.IsNullOrEmpty(strName) && iLabel > 0)
{
result.Add(iLabel, strName);
}
}
}
return result;
}
/// <summary>
/// converts from string representation of a label to uint value
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private uint FromStringToUint(string data)
{
if(!string.IsNullOrEmpty(data))
{
if (data.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase) || data.StartsWith("&H", StringComparison.CurrentCultureIgnoreCase))
{
if (uint.TryParse(data.Substring(2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out uint uiValue))
return uiValue;
}
else
{
if (uint.TryParse(data, out uint uiValuel))
return uiValuel;
}
}
return 0;
}
}
}

View File

@@ -0,0 +1,144 @@
// **********************************************************************************************************
// COECommDeviceInstrumentFactory.cs
// 5/18/2022
// 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 = "COECommDeviceInstrumentFactory")]
public class COECommDeviceInstrumentFactory : IInstrumentFactory
{
/// <summary>
///
/// </summary>
private ILogger _logger;
/// <summary>
/// The supported interfaces
/// </summary>
private readonly List<Type> _supportedInterfaces = new List<Type>();
private readonly IConfigurationManager _configurationManager;
private const string DefaultConfigPath = @"C:\ProgramData\Raytheon\InstrumentManagerService";
private static string DefaultPath;
private readonly DriverType _driverType;
public COECommDeviceInstrumentFactory(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 COECommDeviceInstrumentFactory([Import(AllowDefault = false)] IConfigurationManager configManager,
[Import(AllowDefault = true)] string defaultConfigPath = null,
[Import(AllowDefault = true)] DriverType driverType = DriverType.TCP)
{
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();
_driverType = driverType;
_supportedInterfaces.Add(typeof(ICommDevice));
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public IInstrument GetInstrument(string name)
{
try
{
_logger = LogManager.GetLogger(name);
return new COECommDeviceInstrument(name, _configurationManager, _driverType);
}
catch (Exception ex)
{
_logger.Error(ex, $"Unable to construct {name} instrument instance");
return null;
}
}
/// <summary>
/// Gets the instrument
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public object GetInstrument(string name, bool simulateHw)
{
try
{
_logger = LogManager.GetLogger(name);
return new COECommDeviceInstrument(name, _configurationManager, _driverType, _logger);
}
catch (Exception)
{
throw;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ICollection<Type> GetSupportedInterfaces()
{
return _supportedInterfaces.ToArray();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static IConfigurationManager GetConfigurationManager()
{
return string.IsNullOrEmpty(DefaultPath) ? new RaytheonConfigurationManager() : new RaytheonConfigurationManager(DefaultPath);
}
}
}

View File

@@ -0,0 +1,135 @@
// **********************************************************************************************************
// ConfigurationHelper.cs
// 7/5/2022
// 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 Raytheon.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Raytheon.Instruments
{
/// <summary>
/// type conversion utility with a special case for enums
/// </summary>
public static class TypeConverter
{
public static T ChangeType<T>(object value)
{
return typeof(T).IsEnum ? (T)Enum.Parse(typeof(T), value.ToString()) : (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
System.ComponentModel.TypeConverter tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : System.ComponentModel.TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
/// <summary>
/// Helper class contains extension fictions for reading types other than strings from configuration,
/// as well as reading lists of values
/// </summary>
public static class ConfigurationHelper
{
/// <summary>
/// template function for reading different types from configuration
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static T GetConfigurationValue<T>(this IConfiguration configuration, string section, string key, string defaultValue)
{
var tmpResult = configuration.GetConfigurationValue(section, key, defaultValue);
return !string.IsNullOrEmpty(tmpResult) ? TypeConverter.ChangeType<T>(tmpResult) : default;
}
/// <summary>
/// returns multi-value result (list of T) from configuration
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static List<T> GetConfigurationListValue<T>(this IConfiguration configuration, string section, string key, List<T> defaultValue)
{
var tmpResult = configuration.GetXmlConfiguration(section);
if (string.IsNullOrEmpty(tmpResult))
{
var xmlStr = new StringBuilder();
xmlStr.Append($"<{key}s>");
foreach (var item in defaultValue)
{
xmlStr.Append($"<{key}>");
xmlStr.Append(item.ToString());
xmlStr.Append($"</{key}>");
}
xmlStr.Append($"</{key}s>");
configuration.SetXmlConfiguration(section, xmlStr.ToString());
return defaultValue;
}
else
{
var stringRes = BuildElementListFromXml(tmpResult, key);
return new List<T>(stringRes.Select(x => TypeConverter.ChangeType<T>(x)));
}
}
/// <summary>
/// returns values from XML section converted to string list
/// </summary>
/// <param name="data"></param>
/// <param name="key"></param>
/// <returns></returns>
private static List<string> BuildElementListFromXml(string data, string key)
{
XElement doc = XElement.Parse(data);
IEnumerable<XElement> xmlMessages = from m
in doc.Elements($"{key}s").Elements(key)
select m;
var messages = xmlMessages.Select(x => x.Value);
return messages?.ToList();
}
}
}