This commit is contained in:
2026-04-17 14:55:32 -04:00
commit bc3ac1d4c9
18017 changed files with 4371742 additions and 0 deletions

View File

@@ -0,0 +1 @@
12

View File

@@ -0,0 +1 @@
12

View File

@@ -0,0 +1,379 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace DTS.SensorDB
{
public class SensorGroup : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, String propertyName)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _groupName;
public string GroupName
{
get { return _groupName; }
set{ SetProperty(ref _groupName, value, "GroupName");}
}
private string _groupDescription;
public string GroupDescription
{
get { return _groupDescription; }
set { SetProperty(ref _groupDescription, value, "GroupDescription"); }
}
private string _category = "";
public string Category
{
get { return _category; }
set { SetProperty(ref _category, value, "Category"); }
}
private string _uuid = "";
public string UUID
{
get { return _uuid; }
set { SetProperty(ref _uuid, value, "UUID"); }
}
private List<SensorData> _sensors = new List<SensorData>();
public SensorData[] Sensors
{
get { return _sensors.ToArray(); }
set { SetProperty(ref _sensors, new List<SensorData>(value), "Sensors"); }
}
public SensorCalibration[] Calibrations
{
get { return _sensorCalibrations.ToArray(); }
set { SetProperty(ref _sensorCalibrations, new List<SensorCalibration>(value), "Calibrations"); }
}
public SensorCalibration GetCalibrationForSensor(int index)
{
if (index >= _sensorCalibrations.Count) { return null; }
else { return _sensorCalibrations[index]; }
}
public void SetCalibrationForSensor(int index, SensorCalibration sc)
{
_sensorCalibrations[index] = sc;
}
private List<SensorCalibration> _sensorCalibrations = new List<SensorCalibration>();
private List<SensorGroup> _groups = new List<SensorGroup>();
public SensorGroup[] Groups
{
get { return _groups.ToArray(); }
set { SetProperty(ref _groups, new List<SensorGroup>(value), "Groups"); }
}
internal void WriteToXML(System.Xml.XmlWriter writer)
{
writer.WriteStartElement("Group");
writer.WriteStartElement("GroupName");
writer.WriteValue(GroupName);
writer.WriteEndElement();
writer.WriteStartElement("GroupDescription");
writer.WriteValue(GroupDescription);
writer.WriteEndElement();
writer.WriteStartElement("Category");
writer.WriteValue(Category);
writer.WriteEndElement();
writer.WriteStartElement("UUID");
writer.WriteValue(UUID);
writer.WriteEndElement();
writer.WriteStartElement("Sensors");
foreach (var sd in _sensors)
{
var element = sd.ToXElement();
element.WriteTo(writer);
}
writer.WriteEndElement();
writer.WriteStartElement("CalibrationData");
foreach (SensorCalibration sc in _sensorCalibrations.ToArray())
{
var element = sc.ToXElement();
element.WriteTo(writer);
}
writer.WriteEndElement();
writer.WriteStartElement("Groups");
foreach (var sg in _groups)
{
sg.WriteToXML(writer);
}
writer.WriteEndElement();
writer.WriteEndElement();
}
public SensorGroup()
{
}
public void RemoveGroupAt(int index)
{
_groups.RemoveAt(index);
OnPropertyChanged("Groups");
}
public void RemoveSensorAt(int index)
{
if (index < _sensorCalibrations.Count)
{
_sensorCalibrations.RemoveAt(index);
}
_sensors.RemoveAt(index);
OnPropertyChanged("Sensors");
OnPropertyChanged("Calibrations");
}
public SensorGroup(System.Xml.XmlElement node)
{
foreach (var childNode in node.ChildNodes)
{
System.Xml.XmlElement elem = childNode as System.Xml.XmlElement;
if (null == elem) { continue; }
try
{
switch (elem.Name)
{
case "GroupName":
GroupName = elem.InnerText;
break;
case "GroupDescription":
GroupDescription = elem.InnerText;
break;
case "Category":
Category = elem.InnerText;
break;
case "UUID":
UUID = elem.InnerText;
break;
case "Sensors":
{
var nodes = elem.GetElementsByTagName("Sensor");
foreach (var node2 in nodes)
{
System.Xml.XmlElement element = node2 as System.Xml.XmlElement;
if (null == element) { continue; }
try
{
_sensors.Add(new SensorData(System.Xml.Linq.XElement.Parse(element.OuterXml)));
}
catch (System.Exception ex2)
{
DTS.Utilities.Logging.APILogger.Log("Failed to parse xml", ex2, element.Name, element.InnerXml);
}
}
}
break;
case "Groups":
{
//var nodes = elem.GetElementsByTagName("Group");
var nodes = elem.ChildNodes;
foreach (var node2 in nodes)
{
System.Xml.XmlElement element = node2 as System.Xml.XmlElement;
if (null == element) { continue; }
try
{
System.Diagnostics.Trace.WriteLine("adding subgroup");
_groups.Add(new SensorGroup(element));
System.Diagnostics.Trace.WriteLine("we have " + _groups.Count.ToString() + " subgroups");
}
catch (System.Exception ex2)
{
DTS.Utilities.Logging.APILogger.Log("Failed to parse xml", ex2, element.Name, element.InnerXml);
}
}
}
break;
case "CalibrationData":
{
var nodes = elem.GetElementsByTagName("Calibration");
foreach (var node2 in nodes)
{
System.Xml.XmlElement element = node2 as System.Xml.XmlElement;
if (null == element) { continue; }
try
{
SensorCalibration sc = new SensorCalibration(System.Xml.Linq.XElement.Parse(element.OuterXml));
_sensorCalibrations.Add(sc);
}
catch (System.Exception ex2)
{
DTS.Utilities.Logging.APILogger.Log("Failed to parse xml", ex2, element.Name, element.InnerXml);
}
}
}
break;
}
}
catch (System.Exception ex)
{
DTS.Utilities.Logging.APILogger.Log("failed to parse xml", ex, elem.Name, elem.Value);
}
}
}
}
public class SensorGroupList: INotifyPropertyChanged
{
private Dictionary<string, SensorGroup> _sensorGroupLookup = new Dictionary<string, SensorGroup>();
public SensorGroup[] GetMasterGroups()
{
return _sensorGroupLookup.Values.ToArray();
}
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, String propertyName)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
private static SensorGroupList _list;
private static object MyLock = new object();
public static SensorGroupList GetList()
{
lock (MyLock)
{
if (null == _list)
{
_list = new SensorGroupList();
}
return _list;
}
}
/*private List<SensorGroup> _groups = new List<SensorGroup>();
public SensorGroup[] Groups
{
get { lock(MyLock){return _groups.ToArray(); }}
set { lock(MyLock){SetProperty(ref _groups, new List<SensorGroup>(value), "Groups"); }}
}*/
private SensorGroupList()
{
LoadAllGroups();
}
private void LoadAllGroups()
{
if (System.IO.File.Exists("Groups.xml"))
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
string xml = System.IO.File.ReadAllText("Groups.xml");
doc.LoadXml(xml);
var nodes = doc.GetElementsByTagName("Groups");
foreach (var node in nodes)
{
System.Xml.XmlElement element = node as System.Xml.XmlElement;
if (null == element) { continue; }
foreach (var childNode in element.GetElementsByTagName("Group"))
{
System.Xml.XmlElement elem = childNode as System.Xml.XmlElement;
if (null == elem) { continue; }
LoadGroup(elem);
}
}
}
}
private void LoadGroup(System.Xml.XmlElement node)
{
try
{
SensorGroup group = new SensorGroup(node);
if (!_sensorGroupLookup.ContainsKey(group.GroupName)) { _sensorGroupLookup.Add(group.GroupName, group); }
//if (!_groups.Contains(group)) { _groups.Add(group); }
}
catch (System.Exception ex)
{
DTS.Utilities.Logging.APILogger.Log("failed to load node", ex);
}
}
public void AddGroup(SensorGroup sg)
{
lock (MyLock)
{
//if (!_groups.Contains(sg)) { _groups.Add(sg); }
if (!_sensorGroupLookup.ContainsKey(sg.GroupName)) { _sensorGroupLookup.Add(sg.GroupName, sg); }
else { _sensorGroupLookup[sg.GroupName] = sg; }
foreach (var subgroup in sg.Groups)
{
if (!_sensorGroupLookup.ContainsKey(subgroup.GroupName)) { _sensorGroupLookup.Add(subgroup.GroupName, subgroup); }
}
}
OnPropertyChanged("Groups");
}
public void RemoveGroup(SensorGroup sg)
{
lock (MyLock)
{
_sensorGroupLookup.Remove(sg.GroupName);
//_groups.Remove(sg);
}
OnPropertyChanged("Groups");
}
public void Commit()
{
if (System.IO.File.Exists("Groups.bak"))
{
System.IO.File.Delete("Groups.bak");
}
if (System.IO.File.Exists("Groups.xml"))
{
System.IO.File.Copy("Groups.xml", "Groups.bak");
}
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("Groups.xml", new System.Xml.XmlWriterSettings()
{
Indent = true,
NewLineChars = "\r\n",
NewLineHandling = System.Xml.NewLineHandling.Replace,
NewLineOnAttributes = true
}))
{
writer.WriteStartDocument();
writer.WriteStartElement("Groups");
foreach (var group in GetMasterGroups())
{
group.WriteToXML(writer);
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
}
}
}

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// handles the TCF section of the TSF
/// note that the TCF is not used in Datapro yet.
/// </summary>
public class TSFTCFSection
{
private const string SECTION_START_HEADER = "---- TCF Info Begin ----";
private const string SECTION_END_HEADER = "---- TCF Info End ----";
private string _tcfPath = "";
public string TCFPath
{
get { return _tcfPath; }
set { _tcfPath = value; }
}
/// <summary>
/// reads the section from the TSF
/// assumes currentline points to the start of the section
/// </summary>
/// <param name="lines"></param>
/// <param name="currentLine"></param>
/// <param name="errors"></param>
public void ReadFrom(List<string> lines, ref int currentLine, ref List<ReadTSFError> errors)
{
if (currentLine == lines.Count)
{
//errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string sectionStart = lines[currentLine++];
if (sectionStart != SECTION_START_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TCF_INVALID_STARTSECTIONHEADER, currentLine, sectionStart));
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
TCFPath = lines[currentLine++];
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string sectionEnd = lines[currentLine++];
if (sectionEnd != SECTION_END_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_TCF_INVALID_SECTIONENDHEADER, currentLine, sectionEnd));
}
}
}
}

View File

@@ -0,0 +1,237 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{444EF10C-046E-47AD-A9A5-17318D488723}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DTS.SensorDB</RootNamespace>
<AssemblyName>SensorDB</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkProfile />
<SccProjectName>
</SccProjectName>
<SccLocalPath>
</SccLocalPath>
<SccAuxPath>
</SccAuxPath>
<SccProvider>
</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Xaml.Behaviors">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Microsoft.Xaml.Behaviors.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="Prism">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Prism.dll</HintPath>
</Reference>
<Reference Include="Prism.Unity.Wpf">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Prism.Unity.Wpf.dll</HintPath>
</Reference>
<Reference Include="Prism.Wpf">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Prism.Wpf.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Windows" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Unity.Abstractions">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Unity.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Unity.Container">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Unity.Container.dll</HintPath>
</Reference>
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="AnalogSettingDefaults.cs" />
<Compile Include="CalibrationPolicy.cs" />
<Compile Include="DigitalInputSensorDefault.cs" />
<Compile Include="DigitalInputSetting.cs" />
<Compile Include="DigitalOutputDefaults.cs" />
<Compile Include="FactorySensorModel.cs" />
<Compile Include="IEPESensorDefault.cs" />
<Compile Include="OffsetToleranceChange.cs" />
<Compile Include="SensorCalibrationList.cs" />
<Compile Include="SensorInformationFile.cs" />
<Compile Include="SensorMerge.cs" />
<Compile Include="SoftwareFilter.cs" />
<Compile Include="SquibSettingDefaults.cs" />
<Compile Include="StreamInputSetting.cs" />
<Compile Include="StreamInputSettingDefaults.cs" />
<Compile Include="StreamOutputSetting.cs" />
<Compile Include="StreamOutputSettingDefaults.cs" />
<Compile Include="StringResources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>StringResources.resx</DependentUpon>
</Compile>
<Compile Include="TDCINI\INIDataZeroTimeWindowSeconds.cs" />
<Compile Include="TDCINI\INIIIHSExport.cs" />
<Compile Include="TDCINI\INIISOExportParameters.cs" />
<Compile Include="TDCINI\INIRackInventory.cs" />
<Compile Include="TDCINI\INISmartBatteryThresholds.cs" />
<Compile Include="TDCINI\INIViewerROI.cs" />
<Compile Include="TDCINI\TDCINIError.cs" />
<Compile Include="TDCINI\TDCINIRS232Info.cs" />
<Compile Include="TDCINI\TSFINIRegionOfInterest.cs" />
<Compile Include="TDM\TDMCSVImport.cs" />
<Compile Include="ThermocouplerSetting.cs" />
<Compile Include="TSF\G5DigitalInputChannelTSFEntry.cs" />
<Compile Include="TSF\ReadTSFError.cs" />
<Compile Include="TSF\TOMChannelInformationSection.cs" />
<Compile Include="TSF\TSFCalculatedChannelEntry.cs" />
<Compile Include="TSF\TSFCalculatedChannelInformationSection.cs" />
<Compile Include="TSF\TSFChannel.cs" />
<Compile Include="TSF\TSFDigitalChannel.cs" />
<Compile Include="TSF\TSFDIMEntry.cs" />
<Compile Include="TSF\TSFDIMSection.cs" />
<Compile Include="TSF\TSFFile.cs" />
<Compile Include="TSF\TSFG5DigitalInputSection.cs" />
<Compile Include="TDCINI\TDCINIFile.cs" />
<Compile Include="TSF\TSFInputChannelDescription.cs" />
<Compile Include="IsoCode.cs" />
<Compile Include="MeasurementUnit.cs" />
<Compile Include="SensorCalibration.cs" />
<Compile Include="SensorData.cs" />
<Compile Include="SensorDB.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SensorDBBase.cs" />
<Compile Include="SensorModel.cs" />
<Compile Include="SensorRange.cs" />
<Compile Include="SensorsCollection.cs" />
<Compile Include="SquibSetting.cs" />
<Compile Include="Strings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Strings.resx</DependentUpon>
</Compile>
<Compile Include="DigitalOutputSetting.cs" />
<Compile Include="TSF\TSFCalibrationInformation.cs" />
<Compile Include="TSF\TSFChannelDescription.cs" />
<Compile Include="TSF\TSFModuleDescription.cs" />
<Compile Include="TSF\TSFModuleInformationSection.cs" />
<Compile Include="TSF\TSFOutputChannelDescription.cs" />
<Compile Include="TSF\TSFRackDescription.cs" />
<Compile Include="TSF\TSFRackInformationSection.cs" />
<Compile Include="TSF\TSFSamplingInformationSection.cs" />
<Compile Include="TSF\TSFSensorChannelInformationSection.cs" />
<Compile Include="TSF\TSFSensorEntry.cs" />
<Compile Include="TSF\TSFSquibFireEntry.cs" />
<Compile Include="TSF\TSFSystemDescription.cs" />
<Compile Include="TSF\TSFTCFSection.cs" />
<Compile Include="UartSetting.cs" />
<Compile Include="UartSettingDefaults.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="StringResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>StringResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Include="Strings.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Strings.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\DTS.Common.DAS.Concepts\DTS.Common.DAS.Concepts.csproj">
<Project>{ae3987f7-c4c6-40fb-a353-1a2dadef7a9a}</Project>
<Name>DTS.Common.DAS.Concepts</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\DTS.Common.SettingsDB\DTS.Common.Settings.csproj">
<Project>{61017104-d8ee-41d1-b9ca-dad863ff78b2}</Project>
<Name>DTS.Common.Settings</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\DTS.Common.Storage\DTS.Common.Storage.csproj">
<Project>{e3be457c-0ac7-4a9c-bc81-eafeb3217878}</Project>
<Name>DTS.Common.Storage</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\DTS.Common.Utilities\DTS.Common.Utilities.csproj">
<Project>{d6da1b74-c711-43c2-91b1-1908a8d04dbf}</Project>
<Name>DTS.Common.Utilities</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\DTS.Common\DTS.Common.csproj">
<Project>{f7a0804f-61a4-40ae-83d0-f1137622b592}</Project>
<Name>DTS.Common</Name>
</ProjectReference>
<ProjectReference Include="..\IService\IService.csproj">
<Project>{C9C45B72-05A3-4962-BC13-A78B1F4B1925}</Project>
<Name>IService</Name>
<Private>False</Private>
</ProjectReference>
<ProjectReference Include="..\Users\Users.csproj">
<Project>{be8d217d-6da9-4bca-b62a-a82325b33979}</Project>
<Name>Users</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="Design\SensorDBClassDiagram.cd" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,332 @@
using System;
using System.Collections.Generic;
using System.Linq;
using DTS.Common.Classes.Sensors;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// handles the sensor channel information section of the TSF
/// can contain
/// datachan,rack,mod,chan,descrip,s/n,offsetlow,offsethigh,calmode,calstep(ohm/volt),shuntval(eu),proptoext,sens(mv/eu or mv/v/eu),gain,extvolt,EU,filter,invert,zeroref,desiredmaxrange,commentfield,caldate,Offset?,InitialEU,sensorID,ISOcode,IRTRACC exponent,sensor category,desired max range scaling,C0,C1,C2,C3,C4,C5
/// these appear to be only analog sensors
/// </summary>
public class TSFSensorChannelInformationSection
{
private const string SECTION_START_HEADER = "---- Start Sensor Channel Information ----";
private const string COLUMNS_HEADER = "datachan,rack,mod,chan,descrip,s/n,offsetlow,offsethigh,calmode,calstep(ohm/volt),shuntval(eu),proptoext,sens(mv/eu or mv/v/eu),gain,extvolt,EU,filter,invert,zeroref,desiredmaxrange,commentfield,caldate,Offset?,InitialEU,sensorID";
private const string COLUMNS_HEADER_POLY = "C0,C1,C2,C3,C4,C5";
private const string SECTION_END_HEADER = "---- End Sensor Channel Information ----";
private List<TSFSensorEntry> _entries = new List<TSFSensorEntry>();
public TSFSensorEntry[] Entries
{
get => _entries.ToArray();
set => _entries = new List<TSFSensorEntry>(value);
}
public TSFSensorChannelInformationSection() { }
/// <summary>
/// reads the section from the TSF
/// assumes currentline points to the start of the section
/// </summary>
/// <param name="lines"></param>
/// <param name="currentLine"></param>
/// <param name="errors"></param>
public void ReadFrom(List<string> lines, ref int currentLine, ref List<ReadTSFError> errors)
{
// READ IN SENSOR CHANNEL VALUES
if (currentLine == lines.Count) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine)); return; }
var sectionHeader = lines[currentLine++];
if (sectionHeader != SECTION_START_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.SENSORCHANNELSECTION_INVALIDHEADER, currentLine, sectionHeader));
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
var columnHeader = lines[currentLine++];
var hasPolynomials = false;
if (columnHeader.Contains(COLUMNS_HEADER))
{
// Valid header
hasPolynomials = columnHeader.Contains(COLUMNS_HEADER_POLY);
}
else
{
// Invalid Header
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.SENSORCHANNELSECTION_INVALIDCOLUMNHEADER, currentLine, columnHeader));
return;
}
var done = false;
var sensorEntries = new List<TSFSensorEntry>();
var invariant = System.Globalization.CultureInfo.InvariantCulture;
#region Process entries
while (!done)
{
if (currentLine == lines.Count) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine)); return; }
var line = lines[currentLine++];
if (!line.Contains("End Sensor Channel Information"))
{
var tokens = line.Split(',');
var entry = new TSFSensorEntry();
for (var iCurField = 0; iCurField < tokens.Length; iCurField++)
{
var s = tokens[iCurField];
try
{
var field = (TSFSensorEntry.Fields)iCurField;
switch (field)
{
case TSFSensorEntry.Fields.caldate:
try
{
var dateTokens = s.Split('_');
entry.CalDate = new DateTime(Convert.ToInt32(dateTokens[2], invariant), Convert.ToInt32(dateTokens[0], invariant), Convert.ToInt32(dateTokens[1], invariant));
}
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_CALDATE, currentLine, s)); }
break;
case TSFSensorEntry.Fields.calmode:
{
entry.CalMode = new CalMode(s);
}
break;
case TSFSensorEntry.Fields.calstep:
try { entry.CalStep = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_CALSTEP, currentLine, s)); }
break;
case TSFSensorEntry.Fields.chan:
try { entry.Chan = Convert.ToInt32(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_CHAN, currentLine, s)); }
break;
case TSFSensorEntry.Fields.commentfield: entry.CommentField = s; break;
case TSFSensorEntry.Fields.datachan:
try { entry.DataChan = Convert.ToInt32(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_DATACHAN, currentLine, s)); }
break;
case TSFSensorEntry.Fields.descrip:
entry.Description = s;
break;
case TSFSensorEntry.Fields.desiredmaxrange:
try { entry.DesiredMaxRange = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_DESIREDMAXRANGE, currentLine, s)); }
break;
case TSFSensorEntry.Fields.desiredmaxrangescaling:
try { entry.DesiredMaxRangeScaling = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_DESIREDMAXRANGESCALING, currentLine, s)); }
break;
case TSFSensorEntry.Fields.EU: entry.EU = s; break;
case TSFSensorEntry.Fields.extvolt:
try { entry.ExtVolt = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_EXTVOLT, currentLine, s)); }
break;
case TSFSensorEntry.Fields.filter:
{
double d;
if (!double.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_FILTER, currentLine, s));
}
else { entry.Filter = d; }
}
break;
case TSFSensorEntry.Fields.gain:
try { entry.Gain = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_GAIN, currentLine, s)); }
break;
case TSFSensorEntry.Fields.InitialEU:
try { entry.InitialEU = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_INITIALEU, currentLine, s)); }
break;
case TSFSensorEntry.Fields.invert: entry.Invert = !(s == "0" || s == "N" || s == "F"); break;
case TSFSensorEntry.Fields.IRTRACCexponent:
try { entry.IRTRACCexponent = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_IRTRACCEXPONENT, currentLine, s)); }
break;
case TSFSensorEntry.Fields.ISOcode:
// The TDC SIF ISOcode feild is notoriously abused with holding non-iso information and cannot be trusted to be unique
// This if statement catches some easy to identify signs of abuse and an empty ISO code
if (s.Count() != (new IsoCode(string.Empty)).StringRepresentation.Count() // http://fogbugz/fogbugz/default.asp?9254
|| s.Equals("0000000000000000"))
{
// Stomp on the incorrect ISO Code from the import because we cant trust it.
s = string.Empty;
}
entry.ISOCode = s;
break;
case TSFSensorEntry.Fields.mod:
try { entry.Module = Convert.ToInt32(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_MODULE, currentLine, s)); }
break;
case TSFSensorEntry.Fields.Offset:
{
switch (s)
{
case "0":
case "F":
case "N": entry.RemoveOffset = false; break;
case "1":
case "T":
case "Y": entry.RemoveOffset = true; break;
default:
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_OFFSET, currentLine, s));
}
break;
}
}
break;
case TSFSensorEntry.Fields.offsethigh:
try { entry.OffsetHigh = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_OFFSETHIGH, currentLine, s)); }
break;
case TSFSensorEntry.Fields.offsetlow:
try { entry.OffsetLow = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_OFFSETLOW, currentLine, s)); }
break;
case TSFSensorEntry.Fields.proptoext: entry.ProportionalToExcitation = !(s == "0" || s == "N" || s == "F"); break;
case TSFSensorEntry.Fields.rack:
try { entry.Rack = Convert.ToInt32(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_RACK, currentLine, s)); }
break;
case TSFSensorEntry.Fields.sens:
try { entry.Sensitivity = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_SENSITIVITY, currentLine, s)); }
break;
case TSFSensorEntry.Fields.sensorcategory:
{
switch (s)
{
case "0": entry.SensorCategory = SensorInformationFile.TDCSensorCategory.Normal; break;
case "1": entry.SensorCategory = SensorInformationFile.TDCSensorCategory.POT; break;
case "2": entry.SensorCategory = SensorInformationFile.TDCSensorCategory.IRTracc; break;
case "3": entry.SensorCategory = SensorInformationFile.TDCSensorCategory.Polynomial; break;
default:
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_SENSORCATEGORY, currentLine, s));
break;
}
}
}
break;
case TSFSensorEntry.Fields.sensorID:
if (s.Equals("NONE")) { s = string.Empty; }
entry.SensorId = s;
break;
case TSFSensorEntry.Fields.serialNumber:
if (sensorEntries.Select(x => x.SerialNumber).Contains(s))
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_DUPLICATESERIALNUMBER, currentLine, s));
}
if (string.IsNullOrEmpty(entry.Description))
{
entry.Description = s;
}
entry.SerialNumber = s;
break;
case TSFSensorEntry.Fields.shuntval:
try { entry.ShuntValue = Convert.ToDouble(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_SHUNTVALUE, currentLine, s)); }
break;
case TSFSensorEntry.Fields.zeroref:
try
{
entry.ZeroRef = new ZeroRef(s);
}
catch (Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALID_ZEROREF, currentLine, s));
}
break;
case TSFSensorEntry.Fields.C0:
case TSFSensorEntry.Fields.C1:
case TSFSensorEntry.Fields.C2:
case TSFSensorEntry.Fields.C3:
case TSFSensorEntry.Fields.C4:
case TSFSensorEntry.Fields.C5:
// Nothing to do yet.
break;
default:
throw new NotSupportedException("TSFFile::ReadTSF unknown field: " + field);
}
if (true == hasPolynomials)
{
switch (field)
{
case TSFSensorEntry.Fields.C0:
try { entry.C0 = double.Parse(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_C0, currentLine, s)); }
break;
case TSFSensorEntry.Fields.C1:
try { entry.C1 = double.Parse(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_C1, currentLine, s)); }
break;
case TSFSensorEntry.Fields.C2:
try { entry.C2 = double.Parse(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_C2, currentLine, s)); }
break;
case TSFSensorEntry.Fields.C3:
try { entry.C3 = double.Parse(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_C3, currentLine, s)); }
break;
case TSFSensorEntry.Fields.C4:
try { entry.C4 = double.Parse(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_C4, currentLine, s)); }
break;
case TSFSensorEntry.Fields.C5:
try { entry.C5 = double.Parse(s, invariant); }
catch (Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSORCHANNEL_INVALID_C5, currentLine, s)); }
break;
}
}
}
catch (Exception)
{
//errors.Add("TSF_INVALID_SENSOR_CHANNEL_INFO_FIELD" + iCurField.ToString());
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SENSOR_CHANNEL_INVALIDFIELD, currentLine, iCurField.ToString()));
continue;
}
}
sensorEntries.Add(entry);
//tdc has some additional logic to do some scaling over what the desired max range is ... we don't do that yet ...
/*
// Store unscaled desired max range values, and then scale.
Sensor_UnscaledDesiredMaxRange[r][m][c] = Sensor_DesiredMaxRange[r][m][c];
Sensor_DesiredMaxRange[r][m][c] *= Sensor_DesiredMaxRangeScaling;
if (0.0 == Sensor_IRTRACC_Exponent[r][m][c])
{
Sensor_IRTRACC_Exponent[r][m][c] = IRTRACC_DEFAULT_EXPONENT;
}
// DETERMINE GAIN BASED ON DESIRED MAX RANGE
DetermineMaxRangeandGain(r, m, c, Sensor_DesiredMaxRange[r][m][c], &gain[3], &gain[5], &range[3], &range[5]);
if(IsG5 (Rack_SN[r])) //G5
{
Sensor_Gain[r][m][c]=gain[5];
}
else //PRO
{
Sensor_Gain[r][m][c]=gain[3];
}
*/
}
else { done = true; }
}
#endregion
Entries = sensorEntries.ToArray();
}
}
}

View File

@@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Data.SqlClient;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
namespace DTS.SensorDB
{
public class SoftwareFilter : Common.Base.BasePropertyChanged, ISoftwareFilter
{
public int Id { get; set; } = -1;
private char _isoCode;
public char ISOCode { get => _isoCode; set => SetProperty(ref _isoCode, value, "ISOCode"); }
private string _description = "";
public string Description { get => _description; set => SetProperty(ref _description, value, "Description"); }
private double _frequency = 0D;
public double Frequency { get => _frequency; set => SetProperty(ref _frequency, value, "Frequency"); }
//FB 13120 property to define wich filter is default
private bool _isDefault = false;
public bool IsDefault { get => _isDefault; set => SetProperty(ref _isDefault, value, "IsDefault"); }
private DateTime _lastModified = DateTime.Today;
public DateTime LastModified { get => _lastModified; set => SetProperty(ref _lastModified, value, "LastModified"); }
private string _lastModifiedBy = "";
public string LastModifiedBy { get => _lastModifiedBy; set => SetProperty(ref _lastModifiedBy, value, "LastModifiedBy"); }
public void Commit(bool updateDateTime = true, string user = "")
{
if (updateDateTime)
{
LastModifiedBy = user;
LastModified = DateTime.Now;
}
if (Id <= 0)
{
var filters = GetSoftwareFilters();
if (filters.Where(p => p.Frequency == Frequency).Any())
return;
Insert();
}
else
{
Update();
}
}
private void Insert()
{
using (var sql = DbOperations.GetSQLCommand(true))
{
try
{
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_SoftwareFiltersInsert";
sql.Parameters.Add(new SqlParameter("@ISOCode", SqlDbType.Char) { Value = ISOCode });
sql.Parameters.Add(new SqlParameter("@Description", SqlDbType.NVarChar, 255) { Value = Description });
sql.Parameters.Add(new SqlParameter("@Frequency", SqlDbType.Float) { Value = Frequency });
sql.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = LastModified });
sql.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 255) { Value = LastModifiedBy });
sql.Parameters.Add(new SqlParameter("@IsDefault", SqlDbType.Bit) { Value = IsDefault });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
sql.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
sql.Parameters.Add(errorMessage);
var newId = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
sql.Parameters.Add(newId);
sql.ExecuteNonQuery();
if (null != errorNumber.Value && !DBNull.Value.Equals(errorNumber.Value))
{
if (0 != Convert.ToInt32(errorNumber.Value))
{
throw new Exception((string)errorMessage.Value);
}
}
Id = Convert.ToInt32(newId.Value);
}
finally
{
sql.Connection.Dispose();
}
}
}
private void Update()
{
using (var sql = DbOperations.GetSQLCommand(true))
{
try
{
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_SoftwareFiltersUpdate";
sql.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = Id });
sql.Parameters.Add(new SqlParameter("@ISOCode", SqlDbType.Char) { Value = ISOCode });
sql.Parameters.Add(new SqlParameter("@Description", SqlDbType.NVarChar, 255) { Value = Description });
sql.Parameters.Add(new SqlParameter("@Frequency", SqlDbType.Float) { Value = Frequency });
sql.Parameters.Add(new SqlParameter("@LastModified", SqlDbType.DateTime) { Value = LastModified });
sql.Parameters.Add(new SqlParameter("@LastModifiedBy", SqlDbType.NVarChar, 255) { Value = LastModifiedBy });
sql.Parameters.Add(new SqlParameter("@IsDefault", SqlDbType.Bit) { Value = IsDefault });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
sql.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
sql.Parameters.Add(errorMessage);
sql.ExecuteNonQuery();
if (null != errorNumber.Value && !DBNull.Value.Equals(errorNumber.Value))
{
if (0 != Convert.ToInt32(errorNumber.Value))
{
throw new Exception((string)errorMessage.Value);
}
}
}
finally
{
sql.Connection.Dispose();
}
}
}
public void Delete()
{
if (Id <= 0) { return; }
using (var sql = DbOperations.GetSQLCommand(true))
{
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_SoftwareFiltersDelete";
sql.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = Id });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int) { Direction = ParameterDirection.Output };
sql.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255) { Direction = ParameterDirection.Output };
sql.Parameters.Add(errorMessage);
sql.ExecuteNonQuery();
if (null != errorNumber.Value && !DBNull.Value.Equals(errorNumber.Value))
{
if (0 != Convert.ToInt32(errorNumber.Value))
{
throw new Exception((string)errorMessage.Value);
}
}
}
}
public SoftwareFilter() { }
public SoftwareFilter(int id, string description, char isoCode, DateTime lastModified, string lastModifiedBy, double frequency, bool isDefault)
{
Id = id;
Description = description;
ISOCode = isoCode;
LastModified = lastModified;
LastModifiedBy = lastModifiedBy;
Frequency = frequency;
IsDefault = isDefault;
}
public bool IsBlank()
{
if (Id > 0) { return false; }
if (!string.IsNullOrWhiteSpace(Description)) { return false; }
if (Frequency != 0D) { return false; }
return true;
}
public static ISoftwareFilter[] GetSoftwareFilters()
{
var filters = new List<ISoftwareFilter>();
using (var sql = DbOperations.GetSQLCommand(true))
{
try
{
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_SoftwareFiltersGet";
sql.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = null });
sql.Parameters.Add(new SqlParameter("@Description", SqlDbType.NVarChar, 255) { Value = null });
sql.Parameters.Add(new SqlParameter("@ISOCode", SqlDbType.Char, 1) { Value = null });
var reader = sql.ExecuteReader();
while (reader.Read())
{
var id = Convert.ToInt32(reader["Id"]);
var description = Convert.ToString(reader["Description"]);
var isoCode = Convert.ToChar(reader["ISOCode"]);
var frequency = Convert.ToDouble(reader["Frequency"]);
var lastModified = Convert.ToDateTime(reader["LastModified"]);
var lastModifiedBy = Convert.ToString(reader["LastModifiedBy"]);
var isDefault = Convert.ToBoolean(reader["IsDefault"]);
filters.Add(new SoftwareFilter(id, description, isoCode, lastModified, lastModifiedBy, frequency, isDefault));
}
}
finally
{
sql.Connection.Dispose();
}
}
return filters.ToArray();
}
}
}

View File

@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// handles the module information section of a TSF
/// </summary>
public class TSFModuleInformationSection
{
private const string SECTION_START_HEADER = "---- Start Module Information ----";
private const string COLUMN_HEADER = "rack,module,trigmode,trigchan,trigdir,triglevel,moduletype";
private const string SECTION_END_HEADER = "---- End Module Information ----";
/// <summary>
/// reads the section from a TSF
/// assumes currentline is the start of the section
/// </summary>
/// <param name="lines"></param>
/// <param name="currentLine"></param>
/// <param name="errors"></param>
/// <param name="system"></param>
/// <param name="rackSection"></param>
public void ReadFrom(List<string> lines, ref int currentLine, ref List<ReadTSFError> errors, TSFSystemDescription system, TSFRackInformationSection rackSection)
{
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string sectionHeader = lines[currentLine++];
if (sectionHeader != SECTION_START_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.MODULEINFORMATIONSECTION_BADHEADER, currentLine, sectionHeader));
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string columnHeader = lines[currentLine++];
if (columnHeader != COLUMN_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.MODULEINFORMATIONSECTION_BADCOLUMHEADER, currentLine, columnHeader));
return;
}
var invariant = System.Globalization.CultureInfo.InvariantCulture;
bool done = false;
while (!done)
{
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string line = lines[currentLine++];
if (!line.Contains("End Module Information"))
{
string[] tokens = line.Split(new char[] { ',' });
if (tokens.Length < 7)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SKIPPING_MODULE_TOO_FEW_TOKENS, currentLine));
continue;
}
int r;
try { r = int.Parse(tokens[0], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_MODULE_INVALID_RACK_FIELD, currentLine, tokens[0]));
continue;
}
int m;
try { m = int.Parse(tokens[1], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_MODULE_INVALID_MODULE_FIELD, currentLine, tokens[1]));
continue;
}
int trigMode;
try { trigMode = int.Parse(tokens[2], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_MODULE_INVALID_TRIGGERMODE_FIELD, currentLine, tokens[2]));
continue;
}
int trigChan;
try { trigChan = int.Parse(tokens[3], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_MODULE_INVALID_TRIGGERCHAN_FIELD, currentLine, tokens[3]));
continue;
}
int trigDir;
try { trigDir = int.Parse(tokens[4], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_MODULE_INVALID_TRIGGERDIR_FIELD, currentLine, tokens[4]));
continue;
}
double trigLevel;
try { trigLevel = double.Parse(tokens[5], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_MODULE_INVALID_TRIGGERLEVEL_FIELD, currentLine, tokens[5]));
continue;
}
int moduleType;
try { moduleType = int.Parse(tokens[6], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_MODULE_INVALID_MODULETYPE_FIELD, currentLine, tokens[6]));
continue;
}
//var rackHW = system.HWRack[r];
bool bFound = false;
foreach (var curRack in rackSection.Racks)
{
if (curRack.Number == r)
{
curRack.SetModule(m, trigMode, trigChan, trigDir, trigLevel, moduleType);
bFound = true;
break;
}
}
if (!bFound)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_MODULE_SKIPPED_RACKNOTFOUND, currentLine));
continue;
}
}
else { done = true; }
}
}
}
}

View File

@@ -0,0 +1,53 @@
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Slice.Users.UserSettings;
using System;
namespace DTS.SensorDB
{
public class StreamInputSettingDefaults : DTS.Common.Base.BasePropertyChanged, IStreamInputSettingDefaults
{
private ISensorData _defaultStreamInput;
public string UDPAddress { get => _defaultStreamInput.StreamInUDPAddress; set => _defaultStreamInput.StreamInUDPAddress = value; }
public bool Validate()
{
if (!UDPAddress.ToLower().StartsWith("udp") || !Uri.IsWellFormedUriString(UDPAddress, UriKind.Absolute))
{
return false;
}
return true;
}
public static void CommitChange(StreamInputSettingDefaults settingDefaults, int userID)
{
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUDPStreamAddress, settingDefaults.UDPAddress);
}
public static StreamInputSettingDefaults GetStreamInputSettingsDefault(int userID)
{
var sd = new SensorData()
{
StreamInUDPAddress = TestSetupDefaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultUDPStreamAddress),
};
return new StreamInputSettingDefaults(sd);
}
public static StreamInputSettingDefaults GetStreamInputSettingsDefault(string user)
{
var sd = DTS.SensorDB.SensorsCollection.SensorsList.GetSensorBySerialNumber(SensorConstants.TEST_SPECIFIC_STREAM_IN_SERIAL);
return new StreamInputSettingDefaults(sd);
}
private StreamInputSettingDefaults(SensorData sd)
{
_defaultStreamInput = sd;
}
}
}

View File

@@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// encapsulates all possible errors reading INI file, including section, line number, and a message or extra information
/// </summary>
public class TDCINIError
{
public enum INIErrors
{
INI_FILE_NOT_FOUND,
INI_FILE_INCOMPLETE,
INI_COMINFO_INVALID,
INI_FILE_SIGNALTONOISERATIO_INVALID,
INI_FILE_CALPULSETOLERANCE_INVALID,
INI_FILE_COMPORTForSoftwareExportTODAS_INVALID,
INI_PLOTFILLTYPE_INVALID,
INI_SHUNTCHECKOPTIONS_INVALID,
INI_DefaultSoftwareZeroReference_INVALID,
INI_DataZeroTimeWindow_INVALID,
INI_CurrentFirmwareVersion,
INI_GRAPHBACKGROUNDANDTRACE_INVALID,
INI_PROANDG5AAF_INVALID,
INI_USERACCESSTOQUICKMODIFY_INVALID,
INI_SAMPLERATES_INVALID,
INI_CORRESPONDING_VARIABLE_FCS_INVALID,
INI_CALIBRATION_INTERVALINMONTHS_INVALID,
INI_RACKINVENTORY_INVALID,
INI_COMPORTMODE_INVALID,
INI_DUPLICATESENSORSALLOWED_INVALID,
INI_ENABLESENSORID_INVALID,
INI_POSTCALWAITTIME_INVALID,
INI_TSFReadSIFProtocol,
INI_VALIDCUSTOMERDATACOLLECTIONS,
INI_DefaultDataCollectionMode,
INI_DefaultRealtimeMode,
INI_RealtimeBeforeDataCollection,
INI_ExportToASCIIOptions,
INI_SensorWarmupTimeSeconds_INVALID,
INI_SIMConnectorType_INVALID,
INI_TOMEVENT_INVALID,
INI_TOMRecording_INVALID,
INI_TOMACFrequency,
INI_TOMFireTypeDefault_INVALID,
INI_TOMCurrentDefault_INVALID,
INI_ROI_INVALID,
INI_MakeAllDataChannelNumbersSequential_INVALID,
INI_PercentOverRange_INVALID,
INI_DefaultAndBackupSIFDirectories_INVALID,
INI_DefaultAndBackupTSFDirectories_INVALID,
INI_DefaultAndBackupDataDirectories_INVALID,
INI_PerformAutomaticRackDiscovery_INVALID,
INI_ChannelDescriptionFilters,
INI_CurrentRS232,
INI_CheckHardwareTriggerDuringDataCollection_INVALID,
INI_FIREINTOTOMDUMMYLOADS_INVALID,
INI_CreateDIAdemHeaderOnDownload_INVALID,
INI_DIAdemChannelNameOption,
INI_DIAdemChannelCommentOption,
INI_MinimizeTOMSafetySwitchMessages_INVALID,
INI_EnableSoftwareStartTrigger_INVALID,
INI_EnableLowPowerModeForG5_INVALID,
INI_MeterModeChannelOrder_INVALID,
INI_AutomaticallyStartDownloadAfterSequencerComplete_INVALID,
INI_AutomaticallyStartDownloadAfterTestComplete_INVALID,
INI_G5DockingStationConnectorPanelOption_INVALID,
INI_MultipleTestMode_Invalid,
INI_MultipleTestModeDelayBetweenTests_INVALID,
INI_MultipleTestCalibrationInterval_INVALID,
INI_EnableACModeForSquibChannels_INVALID,
INI_OperatingMode,
INI_ViewerROI_INVALID,
INI_SmartBatteryStatusThresholds,
INI_SensorDatabaseDataSourceName_INVALID,
INI_MaximumGainForForcedExcitationMode_INVALID,
INI_ISOEXPORTPARAMETERS_INVALID,
INI_CheckForUndownloadedDataBeforeRealtime_INVALID,
INI_IIHSExport_INVALID,
INI_RealtimeLoggingEnabled_INVALID,
INI_ForceOldTestTrigger,
INI_DefaultExportFolder_INVALID,
INI_ExcitationVoltage_INVALID,
INI_PROGainOptions,
INI_MemorySize_INVALID,
INI_LastDataSet_INVALID,
INI_G5GainOptions_INVALID,
INI_ShuntValueOptions_INVALID
}
private INIErrors _error;
public INIErrors Error { get { return _error; } }
private int _line = -1;
public int Line { get { return _line; } set { _line = value; } }
private string _extraInfo;
public string ExtraInfo { get { return _extraInfo; } }
public TDCINIError(INIErrors error) { _error = error; }
public TDCINIError(INIErrors error, string extraInfo)
{
_error = error;
_extraInfo = extraInfo;
}
public TDCINIError(INIErrors error, string extraInfo, int currentLine)
{
_line = currentLine;
_extraInfo = extraInfo;
_error = error;
}
}
}

View File

@@ -0,0 +1,99 @@
using DTS.Common.Interface.Sensors;
using DTS.Common.Settings;
namespace DTS.SensorDB
{
public class DigitalInputSensorDefault : DTS.Common.Base.BasePropertyChanged, IDigitalInputDefaults
{
private double _constantCurrentBreakpoint;
/// <summary>
/// breakpoint in ADC where transition is made from active state to default state or vice versa
/// only valid for Constant Current Normally Open (CCNO) or Normally Closed (CCNC)
/// </summary>
public double ConstantCurrentBreakpointADC
{
get => _constantCurrentBreakpoint;
set => SetProperty(ref _constantCurrentBreakpoint, value, "ConstantCurrentBreakpointADC");
}
private double _voltageBreakpoint;
/// <summary>
/// breakpoint in ADC where transition is made from active state to default state or vice versa
/// only valid for Transition High to Low (THL) or (TLH)
/// </summary>
public double VoltageBreakpointADC
{
get => _voltageBreakpoint;
set => SetProperty(ref _voltageBreakpoint, value, "VoltageBreakpointADC");
}
private bool _displaySPDADC;
/// <summary>
/// whether to display analog SLICE PRO DIGITAL ADC data
/// </summary>
public bool DisplaySPDADC
{
get => _displaySPDADC;
set => SetProperty(ref _displaySPDADC, value, "DisplaySPDADC");
}
/// <summary>
/// returns true if properties are valid
/// </summary>
/// <returns></returns>
public bool Validate()
{
return true;
}
private const string VOLTAGE_INPUT_KEY = "VoltageInputBreakpoint";
private const string CONSTANT_CURRENT_KEY = "ConstantCurrentInputBreakpoint";
private const string DISPLAY_SPD_ADC_KEY = "DisplaySPDADC";
/// <summary>
/// returns the defaults for digital inputs
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public static IDigitalInputDefaults GetDigitalInputDefaults(string user)
{
var ccDefault = SettingsDB.GetGlobalValueDouble(CONSTANT_CURRENT_KEY,
DTS.Common.Constant.DigitalInputs.ConstantCurrentBreakPointDefault);
var voltageDefault = SettingsDB.GetGlobalValueDouble(VOLTAGE_INPUT_KEY,
DTS.Common.Constant.DigitalInputs.VoltageInputBreakPointDefault);
var displaySPDADC = SettingsDB.GetGlobalValueBool(DISPLAY_SPD_ADC_KEY,
DTS.Common.Constant.DigitalInputs.DisplaySPDADCDefault);
return new DigitalInputSensorDefault()
{
ConstantCurrentBreakpointADC = ccDefault,
VoltageBreakpointADC = voltageDefault,
DisplaySPDADC = displaySPDADC
};
}
/// <summary>
/// commits digital inputs to storage
/// </summary>
/// <param name="defaults"></param>
public static void Save(IDigitalInputDefaults defaults)
{
SettingsDB.SetGlobalValueDouble(CONSTANT_CURRENT_KEY, defaults.ConstantCurrentBreakpointADC);
SettingsDB.SetGlobalValueDouble(VOLTAGE_INPUT_KEY, defaults.VoltageBreakpointADC);
SettingsDB.SetGlobalValueBoolean(DISPLAY_SPD_ADC_KEY, defaults.DisplaySPDADC);
DTS.Common.Constant.DigitalInputs.ConstantCurrentBreakPoint = defaults.ConstantCurrentBreakpointADC;
DTS.Common.Constant.DigitalInputs.VoltageInputBreakPoint = defaults.VoltageBreakpointADC;
DTS.Common.Constant.DigitalInputs.DisplaySPDADC = defaults.DisplaySPDADC;
}
/// <summary>
/// restores digital input settings to defaults
/// </summary>
/// <param name="sensorDefaults"></param>
public static void RestoreDefaults(IDigitalInputDefaults sensorDefaults)
{
sensorDefaults.ConstantCurrentBreakpointADC = DTS.Common.Constant.DigitalInputs.ConstantCurrentBreakPointDefault;
sensorDefaults.VoltageBreakpointADC = DTS.Common.Constant.DigitalInputs.VoltageInputBreakPointDefault;
sensorDefaults.DisplaySPDADC = DTS.Common.Constant.DigitalInputs.DisplaySPDADC;
}
}
}

View File

@@ -0,0 +1,131 @@
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
namespace DTS.SensorDB
{
/// <summary>
/// this class handles the updating the default squib settings
/// </summary>
public sealed class SquibSettingDefaults : DTS.Common.Base.BasePropertyChanged, ISquibSettingDefaults
{
private ISensorData _defaultSquib;
public double ToleranceLowDefault
{
get => _defaultSquib.SquibToleranceLow;
set
{
_defaultSquib.SquibToleranceLow = value;
OnPropertyChanged("ToleranceLowDefault");
OnPropertyChanged("ToleranceValid");
}
}
public double ToleranceHighDefault
{
get => _defaultSquib.SquibToleranceHigh;
set
{
_defaultSquib.SquibToleranceHigh = value;
OnPropertyChanged("ToleranceHighDefault");
OnPropertyChanged("ToleranceValid");
}
}
public double OutputCurrentDefault
{
get => _defaultSquib.SquibOutputCurrent;
set
{
_defaultSquib.SquibOutputCurrent = value;
OnPropertyChanged("OutputCurrentDefault");
}
}
public SquibMeasurementType MeasurementTypeDefault
{
get => _defaultSquib.SquibMeasurementType;
set
{
_defaultSquib.SquibMeasurementType = value;
OnPropertyChanged("MeasurementTypeDefault");
}
}
public SquibFireMode FireModeDefault
{
get => _defaultSquib.SquibFireMode;
set
{
_defaultSquib.SquibFireMode = value;
OnPropertyChanged("FireModeDefault");
OnPropertyChanged("IsConstantCurrent");
}
}
private static SquibFireMode[] _availableModes = new SquibFireMode[] { SquibFireMode.CAP, SquibFireMode.CONSTANT };
public SquibFireMode[] AvailableModes
{
get => _availableModes;
}
public bool IsConstantCurrent { get => FireModeDefault == SquibFireMode.CONSTANT; }
public bool LimitDurationDefault
{
get => _defaultSquib.LimitSquibFireDuration;
set
{
_defaultSquib.LimitSquibFireDuration = value;
OnPropertyChanged("LimitDurationDefault");
}
}
public double FireDurationMS
{
get => _defaultSquib.SquibFireDurationMS;
set
{
_defaultSquib.SquibFireDurationMS = value;
OnPropertyChanged("FireDurationMS");
}
}
public double FireDelayMS
{
get => _defaultSquib.SquibFireDelayMS;
set
{
_defaultSquib.SquibFireDelayMS = value;
OnPropertyChanged("FireDelayMS");
}
}
/// <summary>
/// commits the changes to the db
/// </summary>
/// <param name="settingDefaults"></param>
/// <param name="user"></param>
public static void CommitChange(SquibSettingDefaults settingDefaults, string user)
{
SensorsCollection.SensorsList.Commit(user, (SensorData)settingDefaults._defaultSquib, false);
}
/// <summary>
/// returns the defaults for squibs
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public static SquibSettingDefaults GetSquibSettingsDefault(string user)
{
var sd = DTS.SensorDB.SensorsCollection.SensorsList.GetSensorBySerialNumber(SensorConstants.TEST_SPECIFIC_SQUIB_SERIAL);
return new SquibSettingDefaults(sd);
}
private SquibSettingDefaults(ISensorData defaultSquib)
{
_defaultSquib = defaultSquib;
}
public bool ToleranceValid
{
get
{
return ToleranceLowDefault < ToleranceHighDefault;
}
}
public bool Validate()
{
return ToleranceValid;
}
}
}

View File

@@ -0,0 +1,314 @@
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
namespace DTS.SensorDB
{
/// <summary>
/// represents a change to the offset tolerance in the db
/// it implements ISensorChange so can be easily commited and read
/// </summary>
public class OffsetToleranceChange : IOffsetToleranceChange
{
public int SensorId { get; set; }
public double LowMvValue
{
get => double.Parse(Value1, NumberStyles.Any, CultureInfo.InvariantCulture);
set => Value1 = value.ToString(CultureInfo.InvariantCulture);
}
public double HighMvValue
{
get => double.Parse(Value2, NumberStyles.Any, CultureInfo.InvariantCulture);
set => Value2 = value.ToString(CultureInfo.InvariantCulture);
}
public double LowEUValue
{
get => double.Parse(Value3, NumberStyles.Any, CultureInfo.InvariantCulture);
set => Value3 = value.ToString(CultureInfo.InvariantCulture);
}
public double HighEUValue
{
get => double.Parse(Value4, NumberStyles.Any, CultureInfo.InvariantCulture);
set => Value4 = value.ToString(CultureInfo.InvariantCulture);
}
public SensorChangeTypes ChangeType => SensorChangeTypes.OffsetTolerance;
public string Value1 { get; private set; } = 0D.ToString(CultureInfo.InvariantCulture);
public string Value2 { get; private set; } = 0D.ToString(CultureInfo.InvariantCulture);
public string Value3 { get; private set; } = 0D.ToString(CultureInfo.InvariantCulture);
public string Value4 { get; private set; } = 0D.ToString(CultureInfo.InvariantCulture);
public const int NEW_RECORD = -1;
public int RecordId { get; set; } = NEW_RECORD;
public DateTime TimeStamp { get; set; }
public string UserName { get; set; }
public OffsetToleranceChange() { }
public OffsetToleranceChange(string value1, string value2, string value3, string value4)
{
Value1 = value1;
Value2 = value2;
Value3 = value3;
Value4 = value4;
}
}
/// <summary>
/// this class simplifies sensor change histories and types in the db
/// </summary>
public abstract class SensorChangeTypeHelper
{
private static Dictionary<SensorChangeTypes, int> _mappingCache = null;
private static object MyLock = new object();
public static void Commit(ISensorData sensor, ISensorChange[] changes)
{
using (var sql = DbOperations.GetSQLCommand(true))
{
try
{
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_SensorsChangeHistoryDelete";
sql.Parameters.Add(new SqlParameter("@RecordId", SqlDbType.Int) { Value = DBNull.Value });
sql.Parameters.Add(new SqlParameter("@SensorId", SqlDbType.Int) { Value = sensor.DatabaseId });
sql.ExecuteNonQuery();
}
finally
{
sql.Connection.Dispose();
}
}
if (changes.Any())
{
foreach (var change in changes)
{
using (var sql = DbOperations.GetSQLCommand(true))
{
try
{
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_SensorsChangeHistoryInsert";
sql.Parameters.Add(new SqlParameter("@SensorId", SqlDbType.Int)
{ Value = sensor.DatabaseId });
sql.Parameters.Add(new SqlParameter("@ChangeType", SqlDbType.Int)
{ Value = GetAllSensorChangeTypes()[change.ChangeType] });
sql.Parameters.Add(new SqlParameter("@Timestamp", SqlDbType.DateTime)
{ Value = change.TimeStamp });
sql.Parameters.Add(new SqlParameter("@Username", SqlDbType.NVarChar)
{ Value = change.UserName });
sql.Parameters.Add(new SqlParameter("@Value1", SqlDbType.NVarChar) { Value = change.Value1 });
sql.Parameters.Add(new SqlParameter("@Value2", SqlDbType.NVarChar) { Value = change.Value2 });
sql.Parameters.Add(new SqlParameter("@Value3", SqlDbType.NVarChar) { Value = change.Value3 });
sql.Parameters.Add(new SqlParameter("@Value4", SqlDbType.NVarChar) { Value = change.Value4 });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int)
{ Direction = ParameterDirection.Output };
sql.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255)
{ Direction = ParameterDirection.Output };
sql.Parameters.Add(errorMessage);
var new_id = new SqlParameter("@new_id", SqlDbType.Int)
{ Direction = ParameterDirection.Output };
sql.Parameters.Add(new_id);
sql.ExecuteNonQuery();
if (null != errorNumber.Value && !DBNull.Value.Equals(errorNumber.Value))
{
if (0 != Convert.ToInt32(errorNumber.Value))
{
throw new Exception((string)errorMessage.Value);
}
}
}
finally
{
sql.Connection.Dispose();
}
}
}
}
}
/// <summary>
/// writes a single change to the db
/// </summary>
/// <param name="change"></param>
public static void Commit(ISensorChange change)
{
//can't commit when id < 0...
if (change.SensorId < 0)
{
return;
}
using (var sql = DbOperations.GetSQLCommand(true))
{
try
{
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_SensorsChangeHistoryInsert";
sql.Parameters.Add(new SqlParameter("@SensorId", SqlDbType.Int) { Value = change.SensorId });
sql.Parameters.Add(new SqlParameter("@UserName", SqlDbType.NVarChar) { Value = change.UserName });
sql.Parameters.Add(new SqlParameter("@Timestamp", SqlDbType.DateTime) { Value = change.TimeStamp });
sql.Parameters.Add(new SqlParameter("@ChangeType", SqlDbType.Int) { Value = GetAllSensorChangeTypes()[SensorChangeTypes.OffsetTolerance] });
sql.Parameters.Add(new SqlParameter("@Value1", SqlDbType.NVarChar) { Value = change.Value1 });
sql.Parameters.Add(new SqlParameter("@Value2", SqlDbType.NVarChar) { Value = change.Value2 });
sql.Parameters.Add(new SqlParameter("@Value3", SqlDbType.NVarChar) { Value = change.Value3 });
sql.Parameters.Add(new SqlParameter("@Value4", SqlDbType.NVarChar) { Value = change.Value4 });
var errorNumber = new SqlParameter("@errorNumber", SqlDbType.Int)
{ Direction = ParameterDirection.Output };
sql.Parameters.Add(errorNumber);
var errorMessage = new SqlParameter("@errorMessage", SqlDbType.NVarChar, 255)
{ Direction = ParameterDirection.Output };
sql.Parameters.Add(errorMessage);
var newId = new SqlParameter("@new_id", SqlDbType.Int) { Direction = ParameterDirection.Output };
sql.Parameters.Add(newId);
sql.ExecuteNonQuery();
if (null != errorNumber.Value && !DBNull.Value.Equals(errorNumber.Value))
{
if (0 != Convert.ToInt32(errorNumber.Value))
{
throw new Exception((string)errorMessage.Value);
}
}
}
finally
{
sql.Connection.Dispose();
}
}
}
/// <summary>
/// returns all sensor change history for sensor
/// </summary>
/// <param name="sensor"></param>
/// <returns></returns>
public static ISensorChange[] GetAllSensorChanges(ISensorData sensor)
{
var list = new List<ISensorChange>();
var lookup = SensorChangeTypeHelper.GetAllSensorChangeTypes();
var intToType = new Dictionary<int, SensorChangeTypes>();
using (var e = lookup.GetEnumerator())
{
while (e.MoveNext())
{
intToType[e.Current.Value] = e.Current.Key;
}
}
using (var sql = DbOperations.GetSQLCommand(true))
{
try
{
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_SensorsChangeHistoryGet";
sql.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = sensor.DatabaseId });
sql.Parameters.Add(new SqlParameter("@SerialNumber", SqlDbType.NVarChar)
{ Value = sensor.SerialNumber });
var reader = sql.ExecuteReader();
while (reader.Read())
{
var recordId = Convert.ToInt32(reader["RecordId"]);
var sensorId = Convert.ToInt32(reader["SensorId"]);
var ichangeType = Convert.ToInt32(reader["ChangeType"]);
var userName = (string)reader["UserName"];
var timeStamp = Convert.ToDateTime(reader["Timestamp"]);
var value1 = (string)reader["Value1"];
var value2 = (string)reader["Value2"];
var value3 = (string)reader["Value3"];
var value4 = (string)reader["Value4"];
if (!intToType.ContainsKey(ichangeType))
{
throw new NotImplementedException($"unknown change type: {ichangeType}");
}
switch (intToType[ichangeType])
{
case SensorChangeTypes.OffsetTolerance:
list.Add(new OffsetToleranceChange(value1, value2, value3, value4)
{
RecordId = recordId,
SensorId = sensorId,
TimeStamp = timeStamp,
UserName = userName
});
break;
default:
throw new NotImplementedException(
$"Unknown change type: {intToType[ichangeType].ToString()}");
}
}
}
finally
{
sql.Connection.Dispose();
}
}
return list.ToArray();
}
/// <summary>
/// returns a lookup table keyed by change type with corresponding change id in db
/// this is designed to reduce db hits when there are many sensors to commit by allowing
/// caching the sensor change type lookup
/// </summary>
/// <param name="UseCache"></param>
/// <returns></returns>
public static Dictionary<SensorChangeTypes, int> GetAllSensorChangeTypes(bool UseCache = true)
{
lock (MyLock)
{
if (!UseCache || null == _mappingCache)
{
_mappingCache = new Dictionary<SensorChangeTypes, int>();
using (var cmd = DbOperations.GetSQLCommand(true))
{
try
{
cmd.CommandText = "sp_SensorsChangeTypesGet";
cmd.CommandType = CommandType.StoredProcedure;
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var id = Convert.ToInt32(reader["Id"]);
var sType = Convert.ToString(reader["Name"]);
if (Enum.TryParse(sType, out SensorChangeTypes changeType))
{
_mappingCache[changeType] = id;
}
}
}
finally
{
cmd.Connection.Dispose();
}
}
}
return _mappingCache;
}
}
}
}

View File

@@ -0,0 +1,399 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// helper class for TOM Channel Information section of the TSF
/// </summary>
public class TSFTOMChannelInformationSection
{
private const string START_SECTION_HEADER = "---- Start TOM Channel Information ----";
private const string TOM_SQUIBFIRE_CHANNELS_HEADER = "---- TOM Squib Fire Channels ----";
private const string TOM_SQUIBFIRE_COLUMNS_HEADER = "rack,module,chan,descrip,id,type,current,delay,durationON,duration,OhmLow,OhmHigh";
private const string TOM_DIGITALCHANNELS_HEADER = "---- TOM Digital Channels ----";
private const string TOM_DIGITALCHANNELS_COLUMNS = "rack,module,chan,type,delay,durationON,duration";
private const string END_SECTION_HEADER = "---- End TOM Channel Information ----";
/// <summary>
/// squib fire entries in the section
/// </summary>
private List<TSFSquibFireEntry> _squibFireEntries = new List<TSFSquibFireEntry>();
public TSFSquibFireEntry[] SquibFireEntries
{
get { return _squibFireEntries.ToArray(); }
set { _squibFireEntries = new List<TSFSquibFireEntry>(value); }
}
/// <summary>
/// digital output channels in the section
/// </summary>
private List<TSFTOMDigitalOutputChannel> _digitalChannelEntries = new List<TSFTOMDigitalOutputChannel>();
public TSFTOMDigitalOutputChannel[] DigitalChannelEntries
{
get { return _digitalChannelEntries.ToArray(); }
set { _digitalChannelEntries = new List<TSFTOMDigitalOutputChannel>(value); }
}
/// <summary>
/// reads the section a TSF file
/// assumes currentline is the start of the section
/// </summary>
/// <param name="lines"></param>
/// <param name="currentLine"></param>
/// <param name="errors"></param>
public void ReadFrom(List<string> lines, ref int currentLine, ref List<ReadTSFError> errors)
{
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string startSection = lines[currentLine++];
if (startSection != START_SECTION_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_TOMCHANNEL_INVALID_SECTIONSTART, currentLine, startSection));
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string squibFireChannelsHeader = lines[currentLine++];
if (squibFireChannelsHeader != TOM_SQUIBFIRE_CHANNELS_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_TOMCHANNEL_INVALID_SQUIBFIREHEADER, currentLine, squibFireChannelsHeader));
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string columnsHeader = lines[currentLine++];
if (false == columnsHeader.Contains(TOM_SQUIBFIRE_COLUMNS_HEADER))
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIRECHANNELS_INVALID_COLUMNSHEADER, currentLine, columnsHeader));
return;
}
bool done = false;
List<TSFSquibFireEntry> squibFireEntries = new List<TSFSquibFireEntry>();
while (!done)
{
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string line = lines[currentLine++];
if (!line.Contains("TOM Digital Channels"))
{
string[] tokens = line.Split(new char[] { ',' });
TSFSquibFireEntry squib = new TSFSquibFireEntry();
for (int iCurField = 0; iCurField < tokens.Length; iCurField++)
{
TSFSquibFireEntry.Fields field = (TSFSquibFireEntry.Fields)iCurField;
string s = tokens[iCurField];
switch (field)
{
case TSFSquibFireEntry.Fields.chan:
try { squib.Chan = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_CHAN, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.current:
try { squib.Current = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_CURRENT, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.delay:
try { squib.Delay = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_DELAY, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.descrip:
{
if (string.IsNullOrEmpty(s)) { s = "Squib"; }
squib.Description = s;
}
break;
case TSFSquibFireEntry.Fields.duration:
try { squib.Duration = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_DURATION, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.durationON:
try
{
switch (s)
{
case "0":
case "F":
case "N": squib.DurationOn = false; break;
case "1":
case "T":
case "Y": squib.DurationOn = true; break;
default:
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_DURATIONON, currentLine, s));
break;
}
}
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_DURATIONON, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.id: squib.Id = s; break;
case TSFSquibFireEntry.Fields.ISOcode: squib.ISOcode = s; break;
case TSFSquibFireEntry.Fields.module:
try { squib.Module = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_MODULE, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.OhmHigh:
try { squib.OhmHigh = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_OHMHIGH, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.OhmLow:
try { squib.OhmLow = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_INVALID_OHMLOW, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.rack:
try { squib.Rack = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_RACK, currentLine, s)); }
break;
case TSFSquibFireEntry.Fields.type:
try { squib.Type = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SQUIBFIREENTRY_TYPE, currentLine, s)); }
break;
default: throw new NotSupportedException("TSFFile::ReadTSF unsupported squib field: " + field.ToString());
}
}
squibFireEntries.Add(squib);
// Some code from TDC and HLAPI
// doesn't seem to be needed for datapro, but preserved here
/*
// IF THIS IS A NEW MODULE THEN RESET THE TOM CHANNEL COUNTER
if(r!=tomr || m!=tomm)
{
tomc=0;
}
tomr=r;
tomm=m;
// SET ALL TOM DATA CHANNEL DEFAULTS
for(k=0;k<2;k++)
{
static char firetype[32];
tomc = (c-1)*2+k+1;
TOMDataChannel++;
Sensor_DataChan[r][m][tomc]=TOMDataChannel;
// DETERMINE FIRE TYPE
FillBytes(firetype, 0, sizeof(firetype), 0);
if (TOM_Squib_FireType[r][m][c]==1)
{
strcpy(firetype, "DC Cap Discharge");
}
if (TOM_Squib_FireType[r][m][c]==2)
{
strcpy(firetype, "DC Constant Current");
}
if (TOM_Squib_FireType[r][m][c]==3)
{
strcpy(firetype, "AC Cap Discharge");
}
FillBytes(Sensor_ChanDescription[r][m][tomc], 0, sizeof(Sensor_ChanDescription[r][m][tomc]), 0);
FillBytes(Sensor_EngUnit[r][m][tomc], 0, sizeof(Sensor_EngUnit[r][m][tomc]), 0);
if(k==0)
{
// DESCRIPTION AND ENG UNIT
if(TOM_Recording==0)
{
Fmt(Sensor_ChanDescription[r][m][tomc],"%s<%s - Fire Voltage (%s)", TOM_Squib_Description[r][m][c], firetype);
strcpy(Sensor_EngUnit[r][m][tomc], ( 0 == stricmp (CustomerName, "gm daewoo") ) ? "V" : "Volts");
}
else
{
Fmt(Sensor_ChanDescription[r][m][tomc],"%s<%s - Initiation Pulse (%s)", TOM_Squib_Description[r][m][c], firetype);
strcpy(Sensor_EngUnit[r][m][tomc], "Initiation");
}
}
else
{
// DESCRIPTION AND ENG UNIT
Fmt(Sensor_ChanDescription[r][m][tomc],"%s<%s - Fire Current (%s)", TOM_Squib_Description[r][m][c], firetype);
strcpy(Sensor_EngUnit[r][m][tomc], ( 0 == stricmp (CustomerName, "gm daewoo") ) ? "A" : "Amps" );
}
// ISO CODE
if(k==0)
{
FillBytes(Sensor_ISOCode[r][m][tomc], 0, sizeof(Sensor_ISOCode[r][m][tomc]), 0);
strcpy(Sensor_ISOCode[r][m][tomc], TOM_ISOCode[r][m][c]);
}
else
{
FillBytes(Sensor_ISOCode[r][m][tomc], 0, sizeof(Sensor_ISOCode[r][m][tomc]), 0);
CopyBytes (Sensor_ISOCode[r][m][tomc], 0, TOM_ISOCode[r][m][c], 0, 12);
strcat(Sensor_ISOCode[r][m][tomc], "CU");
FillBytes(dummy, 0, sizeof(dummy), 0);
CopyBytes (dummy, 0, TOM_ISOCode[r][m][c], 14, 2);
strcat(Sensor_ISOCode[r][m][tomc], dummy);
}
Sensor_Sensitivity[r][m][tomc]=1.0;
Sensor_Gain[r][m][tomc]=1.0;
if(SampleRate>8000.)
{
Sensor_Filter[r][m][tomc]=1650;
}
else
{
Sensor_Filter[r][m][tomc]= (int)floor(SampleRate/5.);
}
Sensor_InvertData[r][m][tomc]=0;
Sensor_ZeroRef[r][m][tomc]=1;
Sensor_DesiredMaxRange[r][m][tomc]=20.0;
Sensor_SNRatio[r][m][tomc]=80.0;
}
if(n!=14)
{
ReadError=3;
}*/
}
else { done = true; }
}
SquibFireEntries = squibFireEntries.ToArray();
// READ TOM DIGITAL CHANNELS
List<TSFTOMDigitalOutputChannel> digitalChannels = new List<TSFTOMDigitalOutputChannel>();
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string digitalColumns = lines[currentLine++];
if (digitalColumns != TOM_DIGITALCHANNELS_COLUMNS)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_TOMCHANNEL_INVALID_DIGITALCOLUMNSHEADER, currentLine, digitalColumns));
return;
}
done = false;
while (!done)
{
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string line = lines[currentLine++];
if (!line.Contains("End TOM Channel Information"))
{
string[] tokens = line.Split(new char[] { ',' });
TSFTOMDigitalOutputChannel digital = new TSFTOMDigitalOutputChannel();
for (int iCurField = 0; iCurField < tokens.Length; iCurField++)
{
string s = tokens[iCurField];
TSFTOMDigitalOutputChannel.Fields field = (TSFTOMDigitalOutputChannel.Fields)iCurField;
switch (field)
{
case TSFTOMDigitalOutputChannel.Fields.chan:
try { digital.Chan = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_CHAN, currentLine, s)); }
break;
case TSFTOMDigitalOutputChannel.Fields.delay:
try { digital.Delay = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_DELAY, currentLine, s)); }
break;
case TSFTOMDigitalOutputChannel.Fields.duration:
try { digital.Duration = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_DURATION, currentLine, s)); }
break;
case TSFTOMDigitalOutputChannel.Fields.durationON:
try
{
switch (s)
{
case "0":
case "N":
case "F":
digital.DurationOn = false; break;
case "1":
case "T":
case "Y":
digital.DurationOn = true; break;
default:
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_DURATIONON, currentLine, s));
}
break;
}
}
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_DURATIONON, currentLine, s)); }
break;
case TSFTOMDigitalOutputChannel.Fields.module:
try { digital.Module = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_MODULE, currentLine, s)); }
break;
case TSFTOMDigitalOutputChannel.Fields.rack:
try { digital.Rack = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_RACK, currentLine, s)); }
break;
case TSFTOMDigitalOutputChannel.Fields.type:
try
{
switch (s)
{
case "0": digital.Type = TSFTOMDigitalOutputChannel.DigitalOutputTypes.NONE; break;
case "1":
case "5VLH":
digital.Type = TSFTOMDigitalOutputChannel.DigitalOutputTypes.FiveVLH; break;
case "2":
case "5VHL":
digital.Type = TSFTOMDigitalOutputChannel.DigitalOutputTypes.FiveVHL; break;
case "3":
case "CCNO":
digital.Type = TSFTOMDigitalOutputChannel.DigitalOutputTypes.CCNO; break;
case "4":
case "CCNC":
digital.Type = TSFTOMDigitalOutputChannel.DigitalOutputTypes.CCNC; break;
default:
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_TYPE, currentLine, s));
}
break;
}
}
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIGITALCHANNEL_INVALID_TYPE, currentLine, s)); }
break;
default: throw new NotSupportedException("TSFFile::ReadTSF unknown digital channel field: " + field.ToString());
}
}
digitalChannels.Add(digital);
}
else { done = true; }
}
DigitalChannelEntries = digitalChannels.ToArray();
}
}
}

View File

@@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// this class is stolen from HLAPI I imported it hoping to steal some of the code from HLAPI
/// however it's only sparsely used right now ...
/// </summary>
public class TSFChannelDescription
{
private int _version;
public int Version { get { return _version; } set { _version = value; } }
/// <summary>
/// See HLAPI_CHANNEL_TYPE_
/// </summary>
private int _type;
public int Type { get { return _type; } set { _type = value; } }
private TSFModuleDescription _parent;
public TSFModuleDescription Parent { get { return _parent; } set { _parent = value; } }
private int _source;
public int Source { get { return _source; } set { _source = value; } }
private ulong _crc32;
public ulong CRC32 { get { return _crc32; } set { _crc32 = value; } }
private bool _sensorInfoValid = false;
public bool SensorInfoValid { get { return _sensorInfoValid; } set { _sensorInfoValid = value; } }
private TSFInputChannelDescription _inputChannel;
public TSFInputChannelDescription InputChannel { get { return _inputChannel; } set { _inputChannel = value; } }
private TSFOutputChannelDescription _outputChannel;
public TSFOutputChannelDescription OutputChannel { get { return _outputChannel; } set { _outputChannel = value; } }
private string _userChannelNumber = "";
public string SensorUserChannelNumber { get { return _userChannelNumber; } set { _userChannelNumber = value; } }
private string _sensorUserChannelDescription = "";
public string SensorUserChannelDescription { get { return _sensorUserChannelDescription; } set { _sensorUserChannelDescription = value; } }
private string _sensorEID = "";
public string SensorEID { get { return _sensorEID; } set { _sensorEID = value; } }
private List<string> _sensorEIDs = new List<string>();
public string[] SensorEIDs { get { return _sensorEIDs.ToArray(); } set { _sensorEIDs = new List<string>(value); } }
private int _numSensorEIDs;
public int NumSensorEIDs { get { return _numSensorEIDs; } set { _numSensorEIDs = value; } }
// Pre-cal results
/// <summary>
/// Is PreCalResults valid?
/// </summary>
private bool _preCalibrationInfoValid;
public bool PreCalibrationInfoValid { get { return _preCalibrationInfoValid; } set { _preCalibrationInfoValid = value; ; } }
/// <summary>
/// The pre-calibration results.
/// </summary>
private TSFCalibrationInformation _preCalResults;
public TSFCalibrationInformation PreCalResults { get { return _preCalResults; } set { _preCalResults = value; } }
/// <summary>
/// When a unit is powered down,
/// this is our saved copy of PreCalResults.
/// It's not NULL if it's valid.
/// </summary>
private TSFCalibrationInformation _savedPreCalResults;
public TSFCalibrationInformation SavedPreCalResults { get { return _savedPreCalResults; } set { _savedPreCalResults = value; } }
// Post-cal results
/// <summary>
/// Is PostCalResults valid?
/// </summary>
private bool _postCalibrationInfoValid;
public bool PostCalibrationInfoValid { get { return _postCalibrationInfoValid; } set { _postCalibrationInfoValid = value; } }
/// <summary>
/// The post-calibration results.
/// </summary>
private TSFCalibrationInformation _postCalResults;
public TSFCalibrationInformation PostCalResults { get { return _postCalResults; } set { _postCalResults = value; } }
/// <summary>
/// Is the Download* variables valid?
/// </summary>
private bool _downloadDataValid;
public bool DownloadDataValid { get { return _downloadDataValid; } set { _downloadDataValid = value; } }
/// <summary>
/// The downloaded data is from this many seconds before t=0
/// </summary>
private double _downloadBeginSeconds;
public double DownloadBeginSeconds { get { return _downloadBeginSeconds; } set { _downloadBeginSeconds = value; } }
/// <summary>
/// The downloaded data is to this many seconds after t=0
/// </summary>
private double _downloadEndSeconds;
public double DownloadEndSeconds { get { return _downloadEndSeconds; } set { _downloadEndSeconds = value; } }
/// <summary>
/// How many elements in DownloadDataADC
/// </summary>
private int _downloadDataCount;
public int DownloadDataCount { get { return _downloadDataCount; } set { _downloadDataCount = value; } }
/// <summary>
/// The filename where the downloaded data is stored
/// </summary>
private string _downloadDataFileName;
public string DownloadDataFileName { get { return _downloadDataFileName; } set { _downloadDataFileName = value; } }
public TSFChannelDescription() { }
public TSFChannelDescription(TSFChannelDescription copy, TSFModuleDescription module)
{
_crc32 = copy._crc32;
_downloadBeginSeconds = copy._downloadBeginSeconds;
_downloadDataCount = copy._downloadDataCount;
_downloadDataFileName = copy._downloadDataFileName;
_downloadDataValid = copy._downloadDataValid;
_downloadEndSeconds = copy._downloadEndSeconds;
if (null != copy._inputChannel) { _inputChannel = new TSFInputChannelDescription(copy._inputChannel, this); }
_numSensorEIDs = copy._numSensorEIDs;
if (null != copy._outputChannel) { _outputChannel = new TSFOutputChannelDescription(copy._outputChannel, this); }
_parent = module;
_postCalibrationInfoValid = copy._postCalibrationInfoValid;
if (null != copy._postCalResults) { _postCalResults = new TSFCalibrationInformation(copy._postCalResults, this); }
_preCalibrationInfoValid = copy._preCalibrationInfoValid;
if (null != copy._preCalResults) { _preCalResults = new TSFCalibrationInformation(copy._preCalResults, this); }
if (null != copy._savedPreCalResults) { _savedPreCalResults = new TSFCalibrationInformation(copy._savedPreCalResults, this); }
_sensorEID = copy._sensorEID;
_sensorEIDs = new List<string>(copy._sensorEIDs.ToArray());
_sensorInfoValid = copy._sensorInfoValid;
_sensorUserChannelDescription = copy._sensorUserChannelDescription;
_source = copy._source;
_type = copy._type;
_userChannelNumber = copy._userChannelNumber;
_version = copy._version;
}
}
}

View File

@@ -0,0 +1,140 @@
using System;
using System.Data;
using System.Data.SqlClient;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
namespace DTS.SensorDB
{
/// <summary>
/// Digital Inputs allow collected data to behave consistently with a digital data source
/// the settings are for configuring firmware appropriately and for transforming data for consumption
/// </summary>
public class DigitalInputSetting : SensorData
{
/// <summary>
/// constructor and copy constructor
/// </summary>
public DigitalInputSetting() : base()
{
SetDefaults(this);
}
public DigitalInputSetting(IDigitalInDbRecord record) : base()
{
SetDefaults(this);
try
{
DatabaseId = record.Id;
SettingName = record.SerialNumber;
ISOCode = record.ISOCode;
ISOChannelName = record.ISOChannelName;
UserCode = record.UserCode;
UserChannelName = record.UserChannelName;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
LastModified = record.LastModified;
LastUpdatedBy = record.LastModifiedBy;
InputMode = record.Mode;
DIUnits = record.MeasurementUnit;
//Since the ISOCode is not stored in the SensorsDigitalIn table like it is in SensorsAnalog, create one
SetFilterAndFilterClassISO(record.FilterClass, true, true); //Always set Filter to 0
EID = record.EID;
UserValue1 = record.UserValue1;
UserValue2 = record.UserValue2;
UserValue3 = record.UserValue3;
TagsBlobBytes = record.UserTags;
Comment = record.UserValue1;
ScaleMultiplier.FromDbSerializeString(record.ScaleMultiplier.ToSerializeDbString());
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
}
public DigitalInputSetting(IDataRecord reader) : base()
{
SetDefaults(this);
try
{
DatabaseId = Convert.ToInt32(reader["Id"]);
SettingName = Convert.ToString(reader["SerialNumber"]);
ISOCode = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.ISOCode.ToString()]);
ISOChannelName = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.ISOChannelName.ToString()]);
UserCode = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserCode.ToString()]);
UserChannelName = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserChannelName.ToString()]);
Broken = Convert.ToBoolean(reader[DbOperations.DigitalInputSettings.Fields.Broken.ToString()]);
DoNotUse = Convert.ToBoolean(reader[DbOperations.DigitalInputSettings.Fields.DoNotUse.ToString()]);
LastModified = Convert.ToDateTime(reader[DbOperations.DigitalInputSettings.Fields.LastModified.ToString()]);
LastUpdatedBy = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.LastModifiedBy.ToString()]);
InputMode = (DigitalInputModes)Convert.ToInt32(reader[DbOperations.DigitalInputSettings.Fields.SettingMode.ToString()]);
DIUnits = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.MeasurementUnit.ToString()]);
//Since the ISOCode is not stored in the SensorsDigitalIn table like it is in SensorsAnalog, create one
SetFilterAndFilterClassISO(new FilterClass(Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.FilterClass.ToString()])), true, true); //Always set Filter to 0
EID = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.eId.ToString()]);
UserValue1 = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserValue1.ToString()]);
UserValue2 = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserValue2.ToString()]);
UserValue3 = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserValue3.ToString()]);
TagsBlobBytes = (byte[])reader[DbOperations.DigitalInputSettings.Fields.UserTags.ToString()];
Comment = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserValue1.ToString()]);
ScaleMultiplier.FromDbSerializeString(Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.ScaleMultiplier.ToString()]));
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
}
public DigitalInputSetting(DigitalInputSetting copy)
: base(copy)
{
SetDefaults(this);
}
public static void SetDefaults(SensorData sd)
{
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 2400;
sd.Bridge = SensorConstants.BridgeType.DigitalInput;
sd.Capacity = 1;
sd.DisplayUnit = "V";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 2500;
sd.OffsetToleranceLow = 2500;
sd.Model = "Digital Input Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public DigitalInputSetting(SensorData sd)
: base(sd)
{
Bridge = SensorConstants.BridgeType.DigitalInput;
SetDefaults(this);
UserSerialNumber = sd.UserSerialNumber;
SerialNumber = sd.SerialNumber;
UserValue1 = sd.UserValue1;
UserValue2 = sd.UserValue2;
UserValue3 = sd.UserValue3;
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
var record = new DigitalInDbRecord(setting, setting.TagsBlobBytes, setting.ScaleMultiplier);
var hr = DbOperations.SensorsDigitalInUpdateInsert(record);
if (0 == hr)
{
setting.Id = record.Id;
}
}
}
}

View File

@@ -0,0 +1,260 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// stolen from HLApi
/// used only sparsely in DataPRO
/// </summary>
public class TSFRackDescription
{
/// <summary>
/// the number specified in the .INI file
/// </summary>
private int _number;
public int Number { get { return _number; } set { _number = value; } }
private int _version;
public int Version { get { return _version; } set { _version = value; } }
private int _type;
public int Type { get { return _type; } set { _type = value; } }
private TSFSystemDescription _parent;
public TSFSystemDescription Parent { get { return _parent; } set { _parent = value; } }
/// <summary>
/// ??
/// </summary>
private int _flags;
public int Flags;
/// <summary>
/// ??
/// </summary>
private int _source;
public int Source { get { return _source; } set { _source = value; } }
/// <summary>
/// The calculated CRC for this struct
/// </summary>
private ulong _crc32;
public ulong CRC32 { get { return _crc32; } set { _crc32 = value; } }
// Variables to describe the HW configuration of this rack.
/// <summary>
/// Are the HW* valiables valid?
/// </summary>
private bool _hwInfoValid;
public bool HardwareInfoValid { get { return _hwInfoValid; } set { _hwInfoValid = value; } }
/// <summary>
/// How many SIM's do we have?
/// </summary>
private int _hwSIMCount;
private int HWSIMCount { get { return _hwSIMCount; } set { _hwSIMCount = value; } }
/// <summary>
/// How many TOM's do we have?
/// </summary>
private int _hwTOMCount;
public int HWTOMCount { get { return _hwTOMCount; } set { _hwTOMCount = value; } }
/// <summary>
/// How many analog channels do we have?
/// </summary>
private int _hwAnalogChannelCount;
public int HWAnalogChannelCount { get { return _hwAnalogChannelCount; } set { _hwAnalogChannelCount = value; } }
/// <summary>
/// How many squib channels do we have?
/// </summary>
private int _hwSquibChannelCount;
public int HWSquibChannelCount { get { return _hwSquibChannelCount; } set { _hwSquibChannelCount = value; } }
/// <summary>
/// How many digital outputs do we have?
/// </summary>
private int _hwDigitalOutputChannelCount;
public int HWDigitalOutputChannelCount { get { return _hwDigitalOutputChannelCount; } set { _hwDigitalOutputChannelCount = value; } }
/// <summary>
/// How many digital inputs do we have?
/// </summary>
private int _hwDigitalInputChannelCount;
public int HWDigitalInputChannelCount { get { return _hwDigitalInputChannelCount; } set { _hwDigitalInputChannelCount = value; } }
/// <summary>
/// The serial number of this rack
/// </summary>
private string _hwSerialNumber;
public string HWSerialNumber { get { return _hwSerialNumber; } set { _hwSerialNumber = value.Trim(); } }
/// <summary>
/// The IP address of this rack
/// </summary>
private string _hwIPAddress;
public string HWIPAddress { get { return _hwIPAddress; } set { _hwIPAddress = value; } }
/// <summary>
/// How many entries is there in the HWModuleList?
/// </summary>
public int HWModuleCount { get { return HWModuleList.Length; } }
/// <summary>
/// The address to an array of ModuleDescription's
/// </summary>
private List<TSFModuleDescription> _hwModuleList = new List<TSFModuleDescription>();
public TSFModuleDescription[] HWModuleList { get { return _hwModuleList.ToArray(); } set { _hwModuleList = new List<TSFModuleDescription>(value); } }
// This represents the different power sources for this rack
/// <summary>
/// Are the Power* and Battery* variables valid?
/// </summary>
private bool _powerInfoValid = false;
public bool PowerInfoValid { get { return _powerInfoValid; } set { _powerInfoValid = value; } }
/// <summary>
/// Current voltage of source 1
/// </summary>
private double _powerSource1Volts;
public double PowerSource1Volts { get { return _powerSource1Volts; } set { _powerSource1Volts = value; } }
/// <summary>
/// Current voltage of source 2
/// </summary>
private double _powerSource2Volts;
public double PowerSource2Volts { get { return _powerSource2Volts; } set { _powerSource2Volts = value; } }
/// <summary>
/// Not really a state, current charge voltage maybe?
/// </summary>
private double _batteryChargeState;
public double BatteryChargeState { get { return _batteryChargeState; } set { _batteryChargeState = value; } }
/// <summary>
/// Is it charging or draining?
/// </summary>
private int _batteryChargeDirection;
public int BatteryChargeDirection { get { return _batteryChargeDirection; } set { _batteryChargeDirection = value; } }
// This represents the digital inputs on this rack
/// <summary>
/// Is the DigitalInputBits valid?
/// </summary>
private bool _digitalInputBitsValid;
public bool DigitalInputBitsValid { get { return _digitalInputBitsValid; } set { _digitalInputBitsValid = value; } }
/// <summary>
/// One bit for each digital input
/// </summary>
private ulong _digitalInputBits;
public ulong DigitalInputBits { get { return _digitalInputBits; } set { _digitalInputBits = value; } }
// Current info about this racks LED's and fault/trigger lines.
/// <summary>
/// Is the LED/Fault/Trigger info below valid?
/// </summary>
private bool _LEDInfoValid;
public bool LEDInfoValid { get { return _LEDInfoValid; } set { _LEDInfoValid = value; } }
/// <summary>
/// What color is the cal LED? See HLAPI_LED_*
/// </summary>
private char _calLED;
public char CalLED { get { return _calLED; } set { _calLED = value; } }
/// <summary>
/// What color is the armed LED? See HLAPI_LED_*
/// </summary>
private char _armLED;
public char ArmLED { get { return _armLED; } set { _armLED = value; } }
/// <summary>
/// What color is the start record LED? See HLAPI_LED_*
/// </summary>
private char _statLED;
public char StatLED { get { return _statLED; } set { _statLED = value; } }
/// <summary>
/// Current state of trigger fault
/// </summary>
private bool _triggerFault;
public bool TriggerFault { get { return _triggerFault; } set { _triggerFault = value; } }
/// <summary>
/// Current state of the level trigger
/// </summary>
private bool _levelTrigger;
public bool LevelTrigger { get { return _levelTrigger; } set { _levelTrigger = value; } }
/// <summary>
/// This boolean indicates if this rack is currently powered down and should be ignored for all operations.
/// </summary>
private bool _isPoweredDown;
public bool IsPoweredDown { get { return _isPoweredDown; } set { _isPoweredDown = value; } }
/// <summary>
/// this boolean indicates if this rack (G5) is in a docking station or not
/// </summary>
private bool _isInDockingStation;
public bool IsInDockingStation { get { return _isInDockingStation; } set { _isInDockingStation = value; } }
public TSFRackDescription() { }
public TSFRackDescription(TSFRackDescription copy)
{
_armLED = copy.ArmLED;
_batteryChargeDirection = copy._batteryChargeDirection;
_batteryChargeState = copy._batteryChargeState;
_calLED = copy._calLED;
_crc32 = copy._crc32;
_digitalInputBits = copy._digitalInputBits;
_digitalInputBitsValid = copy._digitalInputBitsValid;
_flags = copy._flags;
_hwAnalogChannelCount = copy._hwAnalogChannelCount;
_hwDigitalInputChannelCount = copy._hwDigitalInputChannelCount;
_hwDigitalOutputChannelCount = copy._hwDigitalOutputChannelCount;
_hwInfoValid = copy._hwInfoValid;
_hwIPAddress = copy._hwIPAddress;
_hwModuleList = new List<TSFModuleDescription>();
foreach (var m in copy._hwModuleList) { _hwModuleList.Add(new TSFModuleDescription(m, this)); }
_hwSerialNumber = copy._hwSerialNumber;
_hwSIMCount = copy._hwSIMCount;
_hwSquibChannelCount = copy._hwSquibChannelCount;
_hwTOMCount = copy._hwTOMCount;
_isInDockingStation = copy._isInDockingStation;
_isPoweredDown = copy._isPoweredDown;
_LEDInfoValid = copy._LEDInfoValid;
_levelTrigger = copy._levelTrigger;
_parent = copy._parent;
_powerInfoValid = copy._powerInfoValid;
_powerSource1Volts = copy._powerSource1Volts;
_powerSource2Volts = copy._powerSource2Volts;
_source = copy._source;
_statLED = copy._statLED;
_triggerFault = copy._triggerFault;
_type = copy._type;
_version = copy._version;
_number = copy.Number;
}
public void SetModule(int moduleIndex, int trigMode, int trigChan, int trigDir, double trigLevel, int moduleType)
{
for (int i = _hwModuleList.Count; i <= moduleIndex; i++)
{
TSFModuleDescription hwModule = null;
if (i == moduleIndex)
{
hwModule = new TSFModuleDescription();
hwModule.Parent = this;
hwModule.Slot = moduleIndex;
hwModule.Type = moduleType;
}
_hwModuleList.Add(hwModule);
}
}
}
}

View File

@@ -0,0 +1,721 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTS.Common.Classes.Sensors;
using DTS.Common.DAS.Concepts;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
namespace DTS.SensorDB.TDM
{
/// <summary>
/// this class handles logic of TDM CSV export it is partially built from
/// http://fogbugz/fogbugz/default.asp?5286#31544
/// and http://build:8080/svn/Software/Code/TDASManager/trunk/source/sensor.c
/// </summary>
public class TDMCSVImport
{
/// <summary>
/// most of these will get mapped to full bridge, a couple to half bridge
/// the existing TDM code doesn't appear to consider 1/4 bridge
/// </summary>
private enum MeasurementTypes
{
MEASTYPE_FULLBRIDGE,
MEASTYPE_HALFBRIDGE,
MEASTYPE_VOLTAGE,
MEASTYPE_IRTRACC,
MEASTYPE_VOLTAGE_FB,
MEASTYPE_POTENTIOMETER_FB,
MEASTYPE_POTENTIOMETER_HB,
MEASTYPE_ARS_ANGLE
}
/// <summary>
/// Available filter types in the file
/// note FIR100 not supported by SLICE code currently?
/// </summary>
private enum FilterTypes
{
FILTERTYPE_USEFREQ = 0,
FILTERTYPE_CFC60,
FILTERTYPE_CFC180,
FILTERTYPE_CFC600,
FILTERTYPE_CFC1000,
FILTERTYPE_FIR100,
FILTERTYPE_NONE,
FILTERTYPE_UNFILTERED
}
/// <summary>
/// possible zero methods for sensors
/// </summary>
private enum ZeroMethods
{
ZMETHOD_PREZERO = 1,
ZMETHOD_AVGTIME,
ZMETHOD_EQUALS0MV
}
/// <summary>
/// goes from a label/string in CSV to an enum (measurement type)
/// </summary>
/// <param name="label"></param>
/// <returns></returns>
private static MeasurementTypes LabelToMeasurementType(string label)
{
switch (label)
{
case "Full Bridge": return MeasurementTypes.MEASTYPE_FULLBRIDGE;
case "Half Bridge": return MeasurementTypes.MEASTYPE_HALFBRIDGE;
case "Voltage Mode": return MeasurementTypes.MEASTYPE_VOLTAGE;
case "IRTRACC": return MeasurementTypes.MEASTYPE_IRTRACC;
case "Voltage Mode FB": return MeasurementTypes.MEASTYPE_VOLTAGE_FB;
case "Potentiometer FB": return MeasurementTypes.MEASTYPE_POTENTIOMETER_FB;
case "Potentiometer HB": return MeasurementTypes.MEASTYPE_POTENTIOMETER_HB;
case "Angular Rate Sensor - Angle": return MeasurementTypes.MEASTYPE_ARS_ANGLE;
default:
throw new NotSupportedException("unknown measurement type: " + label);
}
}
/// <summary>
/// goes from an enum to a label/string (measurement type)
/// </summary>
/// <param name="mt"></param>
/// <returns></returns>
private static string MeasurementTypeToLabel(MeasurementTypes mt)
{
switch (mt)
{
case MeasurementTypes.MEASTYPE_FULLBRIDGE: return "Full Bridge";
case MeasurementTypes.MEASTYPE_HALFBRIDGE: return "Half Bridge";
case MeasurementTypes.MEASTYPE_VOLTAGE: return "Voltage Mode";
case MeasurementTypes.MEASTYPE_IRTRACC: return "IRTRACC";
case MeasurementTypes.MEASTYPE_VOLTAGE_FB: return "Voltage Mode FB";
case MeasurementTypes.MEASTYPE_POTENTIOMETER_FB: return "Potentiometer FB";
case MeasurementTypes.MEASTYPE_POTENTIOMETER_HB: return "Potentiometer HB";
case MeasurementTypes.MEASTYPE_ARS_ANGLE: return "Angular Rate Sensor - Angle";
default:
throw new NotSupportedException("unknown measurement type: " + mt.ToString());
}
}
/// <summary>
/// all possible tags/columns in CSV
/// </summary>
public enum TAGS
{
SENSOR_CSV_LABEL_SERIAL_NO,
SENSOR_CSV_LABEL_COMMENT,
SENSOR_CSV_LABEL_EID,
SENSOR_CSV_LABEL_CALDATE,
SENSOR_CSV_LABEL_MANUFACTURER,
SENSOR_CSV_LABEL_SENSOR_TYPE,
SENSOR_CSV_LABEL_UNITS,
SENSOR_CSV_LABEL_CAPACITY_EU,
SENSOR_CSV_LABEL_MEASUREMENT_TYPE,
SENSOR_CSV_LABEL_EXCITATION_VOLTS,
SENSOR_CSV_LABEL_SENSITIVITY,
SENSOR_CSV_LABEL_SENSITIVITY_UNITS,
SENSOR_CSV_LABEL_INVERT,
SENSOR_CSV_LABEL_USE_SHUNT_CAL,
SENSOR_CSV_LABEL_BRIDGE_RESISTANCE_OHMS,
SENSOR_CSV_LABEL_ZMO_MV,
SENSOR_CSV_LABEL_ZMO_UPDATE_MV,
SENSOR_CSV_LABEL_ZMO_TOLERANCE_MV,
SENSOR_CSV_LABEL_REMOVE_ZMO_OFFSET,
SENSOR_CSV_LABEL_TEST_DEVICE,
SENSOR_CSV_LABEL_TEST_DEVICE_TYPE,
SENSOR_CSV_LABEL_CODE,
SENSOR_CSV_LABEL_JCODE,
SENSOR_CSV_LABEL_FILTER_TYPE,
SENSOR_CSV_LABEL_FILTER_FREQUENCY,
SENSOR_CSV_LABEL_RANGE_0,
SENSOR_CSV_LABEL_RANGE_1,
SENSOR_CSV_LABEL_RANGE_2,
SENSOR_CSV_LABEL_RANGE_3,
SENSOR_CSV_LABEL_TOYOTA_CALC_1,
SENSOR_CSV_LABEL_TOYOTA_CALC_2,
SENSOR_CSV_LABEL_TOYOTA_CALC_3,
SENSOR_CSV_LABEL_ZERO_METHOD,
SENSOR_CSV_LABEL_ZERO_INITIAL_EU,
SENSOR_CSV_LABEL_ZERO_TIME_START_MSEC,
SENSOR_CSV_LABEL_ZERO_TIME_END_MSEC,
SENSOR_CSV_LABEL_FLAGS,
UNKNOWN //any flag we don't know gets stuffed into unkown
}
/// <summary>
/// goes from a tag to a string/label (columns/fields)
/// </summary>
/// <param name="tag"></param>
/// <returns></returns>
private static string TagToLabel(TAGS tag)
{
switch (tag)
{
case TAGS.SENSOR_CSV_LABEL_SERIAL_NO: return "Serial No";
case TAGS.SENSOR_CSV_LABEL_COMMENT: return "Comment";
case TAGS.SENSOR_CSV_LABEL_EID: return "EID";
case TAGS.SENSOR_CSV_LABEL_CALDATE: return "Calibration Date";
case TAGS.SENSOR_CSV_LABEL_MANUFACTURER: return "Manufacturer";
case TAGS.SENSOR_CSV_LABEL_SENSOR_TYPE: return "Sensor Type";
case TAGS.SENSOR_CSV_LABEL_UNITS: return "Units";
case TAGS.SENSOR_CSV_LABEL_CAPACITY_EU: return "Capacity (EU)";
case TAGS.SENSOR_CSV_LABEL_MEASUREMENT_TYPE: return "Measurement Type";
case TAGS.SENSOR_CSV_LABEL_EXCITATION_VOLTS: return "Excitation Volts";
case TAGS.SENSOR_CSV_LABEL_SENSITIVITY: return "Sensitivity";
case TAGS.SENSOR_CSV_LABEL_SENSITIVITY_UNITS: return "Sensitivity Units";
case TAGS.SENSOR_CSV_LABEL_INVERT: return "Invert (1 = Yes, 0 = No)";
case TAGS.SENSOR_CSV_LABEL_USE_SHUNT_CAL: return "Use Shunt Cal (1 = Yes, 0 = No)";
case TAGS.SENSOR_CSV_LABEL_BRIDGE_RESISTANCE_OHMS: return "Bridge Resistance Ohms";
case TAGS.SENSOR_CSV_LABEL_ZMO_MV: return "ZMO mV";
case TAGS.SENSOR_CSV_LABEL_ZMO_UPDATE_MV: return "ZMO Updated mV";
case TAGS.SENSOR_CSV_LABEL_ZMO_TOLERANCE_MV: return "ZMO Tolerance mV";
case TAGS.SENSOR_CSV_LABEL_REMOVE_ZMO_OFFSET: return "Remove ZMO Offset";
case TAGS.SENSOR_CSV_LABEL_TEST_DEVICE: return "Test Device (DO NOT CHANGE)";
case TAGS.SENSOR_CSV_LABEL_TEST_DEVICE_TYPE: return "Test Device Type (DO NOT CHANGE)";
case TAGS.SENSOR_CSV_LABEL_CODE: return "Ch. Code (DO NOT CHANGE)";
case TAGS.SENSOR_CSV_LABEL_JCODE: return "J Code (DO NOT CHANGE)";
case TAGS.SENSOR_CSV_LABEL_FILTER_TYPE: return "Filter Type";
case TAGS.SENSOR_CSV_LABEL_FILTER_FREQUENCY: return "Filter Frequency";
case TAGS.SENSOR_CSV_LABEL_RANGE_0: return "Low Range";
case TAGS.SENSOR_CSV_LABEL_RANGE_1: return "Medium Range";
case TAGS.SENSOR_CSV_LABEL_RANGE_2: return "High Range";
case TAGS.SENSOR_CSV_LABEL_RANGE_3: return "Arbitrary Range";
case TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_1: return "Toyota Calc 1";
case TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_2: return "Toyota Calc 2";
case TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_3: return "Toyota Calc 3";
case TAGS.SENSOR_CSV_LABEL_ZERO_METHOD: return "Zero Method";
case TAGS.SENSOR_CSV_LABEL_ZERO_INITIAL_EU: return "Zero Initial EU";
case TAGS.SENSOR_CSV_LABEL_ZERO_TIME_START_MSEC: return "Zero Start Time ms";
case TAGS.SENSOR_CSV_LABEL_ZERO_TIME_END_MSEC: return "Zero End Time ms";
case TAGS.SENSOR_CSV_LABEL_FLAGS: return "Flags";
}
throw new NotSupportedException("Unknown tag: " + tag.ToString());
}
/// <summary>
/// goes from a label to a tag/string (columns/fields)
/// </summary>
/// <param name="label"></param>
/// <returns></returns>
public static TAGS LabelToTag(string label)
{
switch (label)
{
case "Serial No": return TAGS.SENSOR_CSV_LABEL_SERIAL_NO;
case "Comment": return TAGS.SENSOR_CSV_LABEL_COMMENT;
case "EID": return TAGS.SENSOR_CSV_LABEL_EID;
case "Calibration Date": return TAGS.SENSOR_CSV_LABEL_CALDATE;
case "Manufacturer": return TAGS.SENSOR_CSV_LABEL_MANUFACTURER;
case "Sensor Type": return TAGS.SENSOR_CSV_LABEL_SENSOR_TYPE;
case "Units": return TAGS.SENSOR_CSV_LABEL_UNITS;
case "Capacity (EU)": return TAGS.SENSOR_CSV_LABEL_CAPACITY_EU;
case "Measurement Type": return TAGS.SENSOR_CSV_LABEL_MEASUREMENT_TYPE;
case "Excitation Volts": return TAGS.SENSOR_CSV_LABEL_EXCITATION_VOLTS;
case "Sensitivity": return TAGS.SENSOR_CSV_LABEL_SENSITIVITY;
case "Sensitivity Units": return TAGS.SENSOR_CSV_LABEL_SENSITIVITY_UNITS;
case "Invert (1 = Yes, 0 = No)": return TAGS.SENSOR_CSV_LABEL_INVERT;
case "Use Shunt Cal (1 = Yes, 0 = No)": return TAGS.SENSOR_CSV_LABEL_USE_SHUNT_CAL;
case "Bridge Resistance Ohms": return TAGS.SENSOR_CSV_LABEL_BRIDGE_RESISTANCE_OHMS;
case "ZMO mV": return TAGS.SENSOR_CSV_LABEL_ZMO_MV;
case "ZMO Updated mV": return TAGS.SENSOR_CSV_LABEL_ZMO_UPDATE_MV;
case "ZMO Tolerance mV": return TAGS.SENSOR_CSV_LABEL_ZMO_TOLERANCE_MV;
case "Remove ZMO Offset": return TAGS.SENSOR_CSV_LABEL_REMOVE_ZMO_OFFSET;
case "Test Device (DO NOT CHANGE)": return TAGS.SENSOR_CSV_LABEL_TEST_DEVICE;
case "Test Device Type (DO NOT CHANGE)": return TAGS.SENSOR_CSV_LABEL_TEST_DEVICE_TYPE;
case "Ch. Code (DO NOT CHANGE)": return TAGS.SENSOR_CSV_LABEL_CODE;
case "J Code (DO NOT CHANGE)": return TAGS.SENSOR_CSV_LABEL_JCODE;
case "Filter Type": return TAGS.SENSOR_CSV_LABEL_FILTER_TYPE;
case "Filter Frequency": return TAGS.SENSOR_CSV_LABEL_FILTER_FREQUENCY;
case "Low Range": return TAGS.SENSOR_CSV_LABEL_RANGE_0;
case "Medium Range": return TAGS.SENSOR_CSV_LABEL_RANGE_1;
case "High Range": return TAGS.SENSOR_CSV_LABEL_RANGE_2;
case "Arbitrary Range": return TAGS.SENSOR_CSV_LABEL_RANGE_3;
case "Toyota Calc 1": return TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_1;
case "Toyota Calc 2": return TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_2;
case "Toyota Calc 3": return TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_3;
case "Zero Method": return TAGS.SENSOR_CSV_LABEL_ZERO_METHOD;
case "Zero Initial EU": return TAGS.SENSOR_CSV_LABEL_ZERO_INITIAL_EU;
case "Zero Start Time ms": return TAGS.SENSOR_CSV_LABEL_ZERO_TIME_START_MSEC;
case "Zero End Time ms": return TAGS.SENSOR_CSV_LABEL_ZERO_TIME_END_MSEC;
case "Flags": return TAGS.SENSOR_CSV_LABEL_FLAGS;
}
throw new NotSupportedException("unknown tag: " + label);
}
public static DTS.SensorDB.SensorData GetSensor(string[] tokens, TAGS[] tagOrder, ref List<string> errors, Dictionary<string, string> sensorTypeToDimension)
{
DTS.SensorDB.SensorData sd = new SensorData();
sd.Calibration = new SensorCalibration();
double filterFrequency = 0D;
FilterTypes filterType = FilterTypes.FILTERTYPE_NONE;
string calc1 = "";
string calc2 = "";
string calc3 = "";
double dSensitivity = 0D;
for (int i = 0; i < tokens.Length && i < tagOrder.Length; i++)
{
var tag = tagOrder[i];
string sItem = tokens[i].Trim();
//remove starting =" if found
if (sItem.StartsWith("=")) { sItem = sItem.Substring(1); }
//remove starting and trailing "
if (sItem.StartsWith("\"") && sItem.EndsWith("\""))
{
sItem = sItem.Substring(1, sItem.Length - 2);
}
try
{
switch (tag)
{
case TAGS.SENSOR_CSV_LABEL_FLAGS:
//indicates marked for deletion ...
break;
case TAGS.SENSOR_CSV_LABEL_BRIDGE_RESISTANCE_OHMS:
{
sItem = sItem.Trim();
double d;
if (double.TryParse(sItem, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
sd.BridgeResistance = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_CALDATE:
{
sItem = sItem.Trim();
if (string.IsNullOrWhiteSpace(sItem))
{
sd.Calibration.CalibrationDate = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
}
else
{
string[] subtokens = new string[0];
string sDay = "";
string sMonth = "";
string sYear = "";
if (sItem.Contains("/"))
{
sItem = sItem.Replace("//", "/");
subtokens = sItem.Split('/');
if (3 == subtokens.Length) { sYear = subtokens[2]; sMonth = subtokens[0]; sDay = subtokens[1]; }
}
else if (sItem.Contains("-"))
{
subtokens = sItem.Split('-');
if (3 == subtokens.Length) { sYear = subtokens[0]; sMonth = subtokens[1]; sDay = subtokens[2]; }
}
if (3 != subtokens.Length)
{
errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem));
sd.Calibration.CalibrationDate = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
}
else
{
int d;
int m;
int y;
if (int.TryParse(sMonth, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out m)
&& int.TryParse(sDay, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d)
&& int.TryParse(sYear, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out y))
{
try
{
sd.Calibration.CalibrationDate = new DateTime(y, m, d);
}
catch (System.Exception)
{
errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem));
sd.Calibration.CalibrationDate = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
}
}
else
{
errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem));
sd.Calibration.CalibrationDate = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
}
}
}
}
break;
case TAGS.SENSOR_CSV_LABEL_CAPACITY_EU:
{
sItem = sItem.Trim();
double d;
if (double.TryParse(sItem, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
sd.Capacity = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_CODE:
sd.UserValue2 = sItem;
break;
case TAGS.SENSOR_CSV_LABEL_COMMENT:
sd.Comment = sItem;
break;
case TAGS.SENSOR_CSV_LABEL_EID:
if (!string.IsNullOrWhiteSpace(sItem))
{
sd.EID = sItem;
}
break;
case TAGS.SENSOR_CSV_LABEL_EXCITATION_VOLTS:
{
double d;
if (!double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem));
}
else
{
if (0 == d) { d = 5D; }//handle the "Voltage Insertion" mode, which is a 0 in the CSV for excitation
var exc = DTS.Common.DAS.Concepts.Test.Module.Channel.Sensor.GetExcitationVoltageEnumFromMagnitude(d);
sd.SupportedExcitation = new ExcitationVoltageOptions.ExcitationVoltageOption[] { exc };
sd.Calibration.Records.Records[0].Excitation = exc;
}
}
break;
case TAGS.SENSOR_CSV_LABEL_FILTER_FREQUENCY:
{
double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
filterFrequency = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_FILTER_TYPE:
{
int iType;
if (int.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out iType))
{
filterType = (FilterTypes)iType;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_INVERT:
{
sItem = sItem.Trim();
switch (sItem.ToUpper())
{
case "0":
case "F":
case "N": sd.Invert = false; break;
case "1":
case "Y":
case "T": sd.Invert = true; break;
default:
errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem));
break;
}
}
break;
case TAGS.SENSOR_CSV_LABEL_JCODE:
{
sd.UserValue1 = sItem;
}
break;
case TAGS.SENSOR_CSV_LABEL_MANUFACTURER:
{
sd.Manufacturer = sItem;
}
break;
case TAGS.SENSOR_CSV_LABEL_MEASUREMENT_TYPE:
{
var type = LabelToMeasurementType(sItem.Trim());
switch (type)
{
case MeasurementTypes.MEASTYPE_ARS_ANGLE:
sd.Bridge = SensorConstants.BridgeType.FullBridge;
break;
case MeasurementTypes.MEASTYPE_FULLBRIDGE:
sd.Bridge = SensorConstants.BridgeType.FullBridge;
break;
case MeasurementTypes.MEASTYPE_HALFBRIDGE:
sd.Bridge = SensorConstants.BridgeType.HalfBridge_SigPlus;
break;
case MeasurementTypes.MEASTYPE_IRTRACC:
sd.Bridge = SensorConstants.BridgeType.FullBridge;
sd.Calibration.NonLinear = true;
sd.Calibration.Records.Records[0].Poly.NonLinearStyle = NonLinearStyles.IRTraccDiagnosticsZero;
sd.Calibration.Records.Records[0].Poly.MarkValid(true);
break;
case MeasurementTypes.MEASTYPE_POTENTIOMETER_FB:
sd.Bridge = SensorConstants.BridgeType.FullBridge;
break;
case MeasurementTypes.MEASTYPE_POTENTIOMETER_HB:
sd.Bridge = SensorConstants.BridgeType.HalfBridge_SigPlus;
break;
case MeasurementTypes.MEASTYPE_VOLTAGE:
sd.Bridge = SensorConstants.BridgeType.HalfBridge_SigPlus;
break;
case MeasurementTypes.MEASTYPE_VOLTAGE_FB:
sd.Bridge = SensorConstants.BridgeType.FullBridge;
break;
}
}
break;
case TAGS.SENSOR_CSV_LABEL_RANGE_0:
{
double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
sd.RangeLow = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_RANGE_1:
{
double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
sd.RangeMedium = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_RANGE_2:
{
double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
sd.RangeHigh = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_RANGE_3:
{
/*double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
sd.Capacity = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }*/
}
break;
case TAGS.SENSOR_CSV_LABEL_REMOVE_ZMO_OFFSET:
{
switch (sItem.Trim().ToUpper())
{
case "1":
case "T":
case "Y":
sd.Calibration.RemoveOffset = true;
break;
case "0":
case "F":
case "N":
sd.Calibration.RemoveOffset = false;
break;
default:
errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem));
break;
}
}
break;
case TAGS.SENSOR_CSV_LABEL_SENSITIVITY:
{
double d;
if (double.TryParse(sItem.Trim(), out d))
{
sd.Calibration.Records.Records[0].Sensitivity = d;
dSensitivity = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_SENSITIVITY_UNITS:
{
switch (sItem.Trim().ToLower())
{
case "mv/v/eu": sd.Calibration.IsProportional = true; sd.Calibration.Records.Records[0].SensitivityUnits = SensorConstants.SensUnits.mVperVperEU; break;
case "mv/eu": sd.Calibration.IsProportional = false; sd.Calibration.Records.Records[0].SensitivityUnits = SensorConstants.SensUnits.mVperEU; break;
default: errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); break;
}
}
break;
case TAGS.SENSOR_CSV_LABEL_SENSOR_TYPE:
{
if (!sensorTypeToDimension.ContainsKey(sItem.Trim()))
{
errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem));
}
else
{
sd.PhysicalDimension = sensorTypeToDimension[sItem.Trim()];
}
}
break;
case TAGS.SENSOR_CSV_LABEL_SERIAL_NO:
sd.SerialNumber = sItem.Trim();
sd.Calibration.SerialNumber = sd.SerialNumber;
break;
case TAGS.SENSOR_CSV_LABEL_TEST_DEVICE:
//not currently used
break;
case TAGS.SENSOR_CSV_LABEL_TEST_DEVICE_TYPE:
//not currently used
break;
case TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_1:
calc1 = sItem.Trim();
break;
case TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_2:
calc2 = sItem.Trim();
break;
case TAGS.SENSOR_CSV_LABEL_TOYOTA_CALC_3:
calc3 = sItem.Trim();
break;
case TAGS.SENSOR_CSV_LABEL_UNITS:
sItem = sItem.Trim();
sd.DisplayUnit = sItem.Trim();
Array.ForEach(sd.Calibration.Records.Records, record => record.EngineeringUnits = sItem.Trim()); //FB16398: set units on all records, not just first
break;
case TAGS.SENSOR_CSV_LABEL_USE_SHUNT_CAL:
{
switch (sItem.Trim().ToUpper())
{
case "0":
case "F":
case "N":
sd.Shunt = ShuntMode.None;
break;
case "1":
case "T":
case "Y":
sd.Shunt = ShuntMode.Emulation;
break;
default:
errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem));
break;
}
}
break;
case TAGS.SENSOR_CSV_LABEL_ZERO_INITIAL_EU:
{
double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{//TODO: linear/nonlinear
sd.Calibration.InitialOffsets = new InitialOffsets(new InitialOffset(d));
}
}
break;
case TAGS.SENSOR_CSV_LABEL_ZERO_METHOD:
{
int iTemp;
if (int.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out iTemp))
{
ZeroMethods zm = (ZeroMethods)iTemp;
switch (zm)
{
case ZeroMethods.ZMETHOD_AVGTIME: sd.Calibration.ZeroMethods.Methods[0].Method = ZeroMethodType.AverageOverTime; break;
case ZeroMethods.ZMETHOD_EQUALS0MV: sd.Calibration.ZeroMethods.Methods[0].Method = ZeroMethodType.None; break;
case ZeroMethods.ZMETHOD_PREZERO: sd.Calibration.ZeroMethods.Methods[0].Method = ZeroMethodType.UsePreEventDiagnosticsZero; break;
default: errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); break;
}
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_ZERO_TIME_END_MSEC:
{
double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{//TODO: linear/nonlinear
sd.Calibration.ZeroMethods.Methods[0].End = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_ZERO_TIME_START_MSEC:
{
double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{//TODO: linear/nonlinear
sd.Calibration.ZeroMethods.Methods[0].Start = d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_ZMO_MV:
{
//we don't do anything with this currently
}
break;
case TAGS.SENSOR_CSV_LABEL_ZMO_TOLERANCE_MV:
{
double d;
if (double.TryParse(sItem.Trim(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
sd.OffsetToleranceHigh = d;
sd.OffsetToleranceLow = -1D * d;
}
else { errors.Add(string.Format("{0} Invalid: {1}", tag.ToString(), sItem)); }
}
break;
case TAGS.SENSOR_CSV_LABEL_ZMO_UPDATE_MV:
{
//we don't do anything with this currently
}
break;
case TAGS.UNKNOWN:
break;
}
}
catch (System.Exception ex)
{
errors.Add("problem handing " + tag.ToString() + ": " + ex.Message);
}
}
sd.UserValue3 = string.Format("{0}{1}{2}{1}{3}", calc1, System.Globalization.CultureInfo.InvariantCulture.TextInfo.ListSeparator, calc2, calc3);
if (sd.Calibration.NonLinear)
{
sd.Calibration.Records.Records[0].Sensitivity = 0;
sd.Calibration.Records.Records[0].Poly.LinearizationExponent = -75D / 175D;
sd.Calibration.Records.Records[0].Poly.MMPerV = 1000D / dSensitivity;
}
switch (filterType)
{
case FilterTypes.FILTERTYPE_CFC1000: sd.Filter = new FilterClass(FilterClassType.CFC1000); break;
case FilterTypes.FILTERTYPE_CFC180: sd.Filter = new FilterClass(FilterClassType.CFC180); break;
case FilterTypes.FILTERTYPE_CFC60: sd.Filter = new FilterClass(FilterClassType.CFC60); break;
case FilterTypes.FILTERTYPE_CFC600: sd.Filter = new FilterClass(FilterClassType.CFC600); break;
case FilterTypes.FILTERTYPE_FIR100:
sd.Filter = new FilterClass(FilterClassType.CFC180);
errors.Add("FIR100 not supported - converting to CFC180");
break;
case FilterTypes.FILTERTYPE_NONE: sd.Filter = new FilterClass(FilterClassType.None); break;
case FilterTypes.FILTERTYPE_UNFILTERED: sd.Filter = new FilterClass(FilterClassType.Unfiltered); break;
case FilterTypes.FILTERTYPE_USEFREQ: sd.Filter = new FilterClass(filterFrequency); break;
default:
errors.Add("unknown filtertype: " + filterType.ToString());
break;
}
sd.UUID = sd.SerialNumber;
if (sd.Capacity < 1)
{
sd.Capacity = 1;
errors.Add(string.Format("{0} does not have a valid capacity. A capacity of 1 will be used", sd.SerialNumber));
}
if (string.IsNullOrWhiteSpace(sd.DisplayUnit))
{
sd.DisplayUnit = "g";
Array.ForEach(sd.Calibration.Records.Records, record => record.EngineeringUnits = "g"); //FB16398: set units on all records, not just first
errors.Add(string.Format("{0} does not have engineering units specified. A value of 'g' will be used", sd.SerialNumber));
}
return sd;
}
}
}

View File

@@ -0,0 +1,258 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="SensorCalibration_Ctor_Err1" xml:space="preserve">
<value>SensorCalibration: Expected version {0}, found version {1}</value>
</data>
<data name="SensorData_Ctor_Err1" xml:space="preserve">
<value>SensorData: Expected version {0}, found version {1}</value>
</data>
<data name="SensorDBTables_Add_SensorCalibration_Err1" xml:space="preserve">
<value>SensorDBTables.Add(SensorCalibration): newCal is null</value>
</data>
<data name="SensorDBTables_Add_SensorCalibration_Err2" xml:space="preserve">
<value>SensorDBTables.Add(SensorCalibration): newCal.SerialNumber is null</value>
</data>
<data name="SensorDBTables_Add_SensorCalibration_Err3" xml:space="preserve">
<value>SensorDBTables.Add(SensorCalibration): newCal.SerialNumber({0}) doesn't exist</value>
</data>
<data name="SensorDBTables_Add_SensorData_Err1" xml:space="preserve">
<value>SensorDBTables.Add(SensorData): newSensor is null</value>
</data>
<data name="SensorDBTables_Add_SensorData_Err2" xml:space="preserve">
<value>SensorDBTables.Add(SensorData): newSensor.SerialNumber is null</value>
</data>
<data name="SensorDBTables_Add_SensorData_Err3" xml:space="preserve">
<value>SensorDBTables.Add(SensorData): newSensor.SerialNumber({0}) is not unique</value>
</data>
<data name="SensorDBTables_Add_SensorData_Err4" xml:space="preserve">
<value>SensorDBTables.Add(SensorData): newSensor.Model({0}) doesn't exist</value>
</data>
<data name="SensorDBTables_Add_SensorData_Err5" xml:space="preserve">
<value>SensorDBTables.Add(SensorData): newSensor.Id({0}) is not unique</value>
</data>
<data name="SensorDBTables_Add_SensorModel_Err1" xml:space="preserve">
<value>SensorDBTables.Add(SensorModel): newModel is null</value>
</data>
<data name="SensorDBTables_Add_SensorModel_Err2" xml:space="preserve">
<value>SensorDBTables.Add(SensorModel): newModel.Name is null</value>
</data>
<data name="SensorDBTables_Add_SensorModel_Err3" xml:space="preserve">
<value>SensorDBTables.Add(SensorModel): newModel.Name({0}) is not unique</value>
</data>
<data name="SensorDBTables_Close_Err1" xml:space="preserve">
<value>SensorDBTables.Close: Trying to close DB with dirty tables</value>
</data>
<data name="SensorDBTables_Delete_SensorCalibration_Err1" xml:space="preserve">
<value>SensorDBTables.Delete(SensorCalibration): calib is null</value>
</data>
<data name="SensorDBTables_Delete_SensorCalibration_Err2" xml:space="preserve">
<value>SensorDBTables.Delete(SensorCalibration): calib.SerialNumber is null</value>
</data>
<data name="SensorDBTables_Delete_SensorCalibration_Err3" xml:space="preserve">
<value>SensorDBTables.Delete(SensorCalibration): Calibrations table is corrupt, there's more than one entry with same SerialNumber and date</value>
</data>
<data name="SensorDBTables_Delete_SensorData_Err1" xml:space="preserve">
<value>SensorDBTables.Delete(SensorData): sensor is null</value>
</data>
<data name="SensorDBTables_Delete_SensorData_Err2" xml:space="preserve">
<value>SensorDBTables.Delete(SensorData): sensor.SerialNumber is null</value>
</data>
<data name="SensorDBTables_Delete_SensorData_Err3" xml:space="preserve">
<value>SensorDBTables.Delete(SensorData): Sensors table is corrupt, there's more than one entry with same SerialNumber</value>
</data>
<data name="SensorDBTables_Delete_SensorModel_Err1" xml:space="preserve">
<value>SensorDBTables.Delete(SensorModel): model is null</value>
</data>
<data name="SensorDBTables_Delete_SensorModel_Err2" xml:space="preserve">
<value>SensorDBTables.Delete(SensorModel): model.Name is null</value>
</data>
<data name="SensorDBTables_Delete_SensorModel_Err3" xml:space="preserve">
<value>SensorDBTables.Delete(SensorModel): Model table is corrupt, there's more than one entry with same name</value>
</data>
<data name="SensorDBTables_Update_SensorCalibration_Err1" xml:space="preserve">
<value>SensorDBTables.Update(SensorCalibration): calib is null</value>
</data>
<data name="SensorDBTables_Update_SensorCalibration_Err2" xml:space="preserve">
<value>SensorDBTables.Update(SensorCalibration): calib.SerialNumber is null</value>
</data>
<data name="SensorDBTables_Update_SensorCalibration_Err3" xml:space="preserve">
<value>SensorDBTables.Update(SensorCalibration): Calibrations table is corrupt, there's more than one entry with same SerialNumber and date</value>
</data>
<data name="SensorDBTables_Update_SensorData_Err1" xml:space="preserve">
<value>SensorDBTables.Update(SensorData): sensor parameter is null</value>
</data>
<data name="SensorDBTables_Update_SensorData_Err2" xml:space="preserve">
<value>SensorDBTables.Update(SensorData): sensor.SerialNumber is null</value>
</data>
<data name="SensorDBTables_Update_SensorData_Err3" xml:space="preserve">
<value>SensorDBTables.Update(SensorData): Sensors table is corrupt, there's more than one entry with same SerialNumber</value>
</data>
<data name="SensorDBTables_Update_SensorModel_Err1" xml:space="preserve">
<value>SensorDBTables.Update(SensorModel): model is null</value>
</data>
<data name="SensorDBTables_Update_SensorModel_Err2" xml:space="preserve">
<value>SensorDBTables.Update(SensorModel): model.Name is null</value>
</data>
<data name="SensorDBTables_Update_SensorModel_Err3" xml:space="preserve">
<value>SensorDBTables.Update(SensorModel): Model table is corrupt, there's more than one entry with same name</value>
</data>
<data name="SensorModel_Ctor_Err1" xml:space="preserve">
<value>SensorModel: Expected version {0}, found version {1}</value>
</data>
<data name="SensorDBTables_Update_SensorData_Err4" xml:space="preserve">
<value>SensorDBTables.Update(SensorData): the new sensor.Id({0}) is not unique</value>
</data>
<data name="SensorDBTables_GetCalibrationBySerialNumberAndDate_Err1" xml:space="preserve">
<value>SensorDBTables.GetCalibrationBySerialNumberAndDate: Duplicate entries for {0} and {1}</value>
</data>
<data name="SensorDBTables_GetLatestSensitivityBySerialNumber_Err1" xml:space="preserve">
<value>SensorDBTables.GetLatestSensitivityBySerialNumber: Sensor {0} doesn't have any calibration entries</value>
</data>
<data name="SensorFields_Excitation" xml:space="preserve">
<value>Excitation</value>
</data>
<data name="SensorFields_NonLinearFormat" xml:space="preserve">
<value>Non-Linear Format</value>
</data>
<data name="SensorFields_Sensitivity" xml:space="preserve">
<value>Sensitivity</value>
</data>
<data name="SensorFields_EngineeringUnits" xml:space="preserve">
<value>Engineering Units</value>
</data>
<data name="SensorFields_CapacityOutputIsBasedOn" xml:space="preserve">
<value>Capacity (EU)</value>
</data>
<data name="SensorFields_AtCapacity" xml:space="preserve">
<value>At Capacity</value>
</data>
<data name="SensorFields_SensitivityUnits" xml:space="preserve">
<value>Sensitivity Units</value>
</data>
<data name="SensorFields_ZeroPoint" xml:space="preserve">
<value>ZeroPoint</value>
</data>
<data name="FilterClassType_None" xml:space="preserve">
<value>Prefiltered &gt; CFC 1000 (P)</value>
</data>
<data name="FilterClassType_Unfiltered" xml:space="preserve">
<value>Unfiltered (0)</value>
</data>
</root>

View File

@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// the DIM section of a TSF
/// we currently do nothing with the DIM section other than parse it
/// DIMs are not officially supported in DataPRO yet
/// </summary>
public class TSFDIMSection
{
private const string SECTION_START_HEADER = "---- DIM Begin (1.0) ----";
private const string COLUMN_HEADER = "Datachan,Rack,Module,Chan,Description,Serial No,Mode,Inverted,EID,Filename,Scale,Filter Mode,Filter Threshold,ISO CODE,Cable Test";
private const string SECTION_END_HEADER = "---- DIM End ----";
private List<TSFDIMEntry> _dimEntries = new List<TSFDIMEntry>();
public TSFDIMEntry[] DIMEntries
{
get { return _dimEntries.ToArray(); }
set { _dimEntries = new List<TSFDIMEntry>(value); }
}
public void ReadFrom(List<string> lines, ref int currentLine, ref List<ReadTSFError> errors)
{
if (currentLine == lines.Count)
{
//errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string sectionStart = lines[currentLine++];
if (false == sectionStart.Contains(SECTION_START_HEADER))
{
//DIM Section may not be defined for this TSF. Bail and dont error.
currentLine--;
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string columnHeaders = lines[currentLine++];
if (columnHeaders != COLUMN_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_COLUMNSECTIONHEADER, currentLine, columnHeaders));
return;
}
bool done = false;
List<TSFDIMEntry> dims = new List<TSFDIMEntry>();
while (!done)
{
if (currentLine == lines.Count) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine)); return; }
string line = lines[currentLine++];
if (!line.Contains("DIM End"))
{
TSFDIMEntry entry = new TSFDIMEntry();
string[] tokens = line.Split(new char[] { ',' });
for (int iCurField = 0; iCurField < tokens.Length; iCurField++)
{
string s = tokens[iCurField];
TSFDIMEntry.Fields field = (TSFDIMEntry.Fields)iCurField;
switch (field)
{
case TSFDIMEntry.Fields.CableTest:
try { entry.CableTest = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_CABLETEST, currentLine, s)); }
break;
case TSFDIMEntry.Fields.Chan:
try { entry.Chan = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_CHAN, currentLine, s)); }
break;
case TSFDIMEntry.Fields.Datachan:
try { entry.DataChan = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_DATACHAN, currentLine, s)); }
break;
case TSFDIMEntry.Fields.Description: entry.Description = s; break;
case TSFDIMEntry.Fields.EID: entry.EID = s; break;
case TSFDIMEntry.Fields.Filename: entry.FileName = s; break;
case TSFDIMEntry.Fields.FilterMode:
try { entry.FilterMode = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_FILTERMODE, currentLine, s)); }
break;
case TSFDIMEntry.Fields.FilterThreshold:
try { entry.FilterThreshold = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_FILTERTHRESHOLD, currentLine, s)); }
break;
case TSFDIMEntry.Fields.Inverted:
try { entry.Inverted = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_INVERTED, currentLine, s)); }
break;
case TSFDIMEntry.Fields.ISOCODE: entry.ISOCode = s; break;
case TSFDIMEntry.Fields.Mode: entry.Mode = s; break;
case TSFDIMEntry.Fields.Module:
try { entry.Module = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_MODULE, currentLine, s)); }
break;
case TSFDIMEntry.Fields.Rack:
try { entry.Rack = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_RACK, currentLine, s)); }
break;
case TSFDIMEntry.Fields.Scale:
try { entry.Scale = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_DIM_INVALID_SCALE, currentLine, s)); }
break;
case TSFDIMEntry.Fields.SerialNo: entry.SerialNumber = s; break;
default: throw new NotSupportedException("TSFFile::ReadTSF unknown DIM field: " + field.ToString());
}
}
dims.Add(entry);
}
else { done = true; }
}
DIMEntries = dims.ToArray();
}
}
}

View File

@@ -0,0 +1,198 @@
using System;
using DTS.Common.Interface.Sensors;
using DTS.Common.Settings;
namespace DTS.SensorDB
{
public class IEPESensorDefault : DTS.Common.Base.BasePropertyChanged, IIEPESensorDefaults
{
#region constants
private const string _24V_POWERLOW_KEY = "_24VPowerLow";
private const string _24V_POWERHIGH_KEY = "_24VPowerHigh";
private const double _24VPOWER_LOW_DEFAULT = 23D;
private const double _24VPOWER_HIGH_DEFAULT = 26.5D;
private const string IEPE_RANGE_LOW_KEY = "IEPERangeLowLimitScalar";
private const string IEPE_RANGE_HIGH_KEY = "IEPERangeHighLimitScalar";
private const double IEPE_RANGE_HIGH_LIMIT = 100D;
private const double IEPE_RANGE_LOW_LIMIT = 1D;
private const string DISABLE_AUTOSENSE_KEY = "DisableAutoSense";
private const bool DISABLE_AUTOSENSE_DEFAULT = false;
#endregion constants
#region properties
private bool _disableAutoSense;
/// <summary>
/// whether AutoSense is allowed or not
/// 14634 Implement enable/disable of the "SLICE PRO Auto-sense" feature
/// </summary>
public bool DisableAutoSense
{
get => _disableAutoSense;
set
{
SetProperty(ref _disableAutoSense, value, "DisableAutoSense");
OnPropertyChanged("DisableAutoSense");
}
}
private double __24VPowerLow;
public double _24VPowerLow
{
get => __24VPowerLow;
set
{
SetProperty(ref __24VPowerLow, value, "_24VPowerLow");
OnPropertyChanged("ToleranceValid");
}
}
private double __24VPowerHigh;
public double _24VPowerHigh
{
get => __24VPowerHigh;
set
{
SetProperty(ref __24VPowerHigh, value, "_24VPowerHigh");
OnPropertyChanged("ToleranceValid");
}
}
private double _rangeLowLimitScalar;
/// <summary>
/// the actual range low acceptable value (scalar applied to desired range)
/// </summary>
public double RangeLowLimitScalar
{
get => _rangeLowLimitScalar;
set
{
SetProperty(ref _rangeLowLimitScalar, value, "RangeLowLimitScalar");
OnPropertyChanged("RangeToleranceValid");
}
}
private double _rangeHighLimitScalar;
/// <summary>
/// the actual range high acceptable value (scalar applied to desired range)
/// </summary>
public double RangeHighLimitScalar
{
get => _rangeHighLimitScalar;
set
{
SetProperty(ref _rangeHighLimitScalar, value, "RangeHighLimitScalar");
OnPropertyChanged("RangeToleranceValid");
}
}
public bool ToleranceValid => _24VPowerHigh > _24VPowerLow;
public bool RangeToleranceValid => RangeLowLimitScalar < RangeHighLimitScalar;
#endregion properties
#region methods
public bool Validate()
{
return ToleranceValid && RangeToleranceValid;
}
#region static methods
public static IIEPESensorDefaults GetIEPESensorDefaults(string user)
{
var low = SettingsDB.GetGlobalValueDouble(_24V_POWERLOW_KEY, _24VPOWER_LOW_DEFAULT);
var high = SettingsDB.GetGlobalValueDouble(_24V_POWERHIGH_KEY, _24VPOWER_HIGH_DEFAULT);
var rangeLow = SettingsDB.GetGlobalValueDouble(IEPE_RANGE_LOW_KEY, IEPE_RANGE_LOW_LIMIT);
var rangeHigh = SettingsDB.GetGlobalValueDouble(IEPE_RANGE_HIGH_KEY, IEPE_RANGE_HIGH_LIMIT);
var disableAutoSense = SettingsDB.GetGlobalValueBool(DISABLE_AUTOSENSE_KEY, DISABLE_AUTOSENSE_DEFAULT);
return new IEPESensorDefault()
{
_24VPowerHigh = high,
_24VPowerLow = low,
RangeHighLimitScalar = rangeHigh,
RangeLowLimitScalar = rangeLow,
DisableAutoSense = disableAutoSense
};
}
public static void Save(IIEPESensorDefaults defaults)
{
SettingsDB.SetGlobalValueDouble(_24V_POWERLOW_KEY, defaults._24VPowerLow);
SettingsDB.SetGlobalValueDouble(_24V_POWERHIGH_KEY, defaults._24VPowerHigh);
SettingsDB.SetGlobalValueDouble(IEPE_RANGE_HIGH_KEY, defaults.RangeHighLimitScalar);
SettingsDB.SetGlobalValueDouble(IEPE_RANGE_LOW_KEY, defaults.RangeLowLimitScalar);
SettingsDB.SetGlobalValueBoolean(DISABLE_AUTOSENSE_KEY, defaults.DisableAutoSense);
}
public static void RestoreDefaults(IIEPESensorDefaults sensorDefaults)
{
sensorDefaults._24VPowerHigh = _24VPOWER_HIGH_DEFAULT;
sensorDefaults._24VPowerLow = _24VPOWER_LOW_DEFAULT;
sensorDefaults.RangeHighLimitScalar = IEPE_RANGE_HIGH_LIMIT;
sensorDefaults.RangeLowLimitScalar = IEPE_RANGE_LOW_LIMIT;
sensorDefaults.DisableAutoSense = DISABLE_AUTOSENSE_DEFAULT;
}
#endregion static methods
public void ReadXML(System.Xml.XmlElement root)
{
foreach (var node in root.ChildNodes)
{
if (node is System.Xml.XmlElement) { ProcessXMLElement(node as System.Xml.XmlElement); }
}
}
private void ProcessXMLElement(System.Xml.XmlElement node)
{
if (Enum.TryParse(node.Name, out IEPEXMLFields field))
{
switch (field)
{
case IEPEXMLFields._24PowerHigh: __24VPowerHigh = Convert.ToDouble(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case IEPEXMLFields._24PowerLow: __24VPowerLow = Convert.ToDouble(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case IEPEXMLFields.RangeHighLimitScalar: RangeHighLimitScalar = Convert.ToDouble(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case IEPEXMLFields.RangeLowLimitScalar: RangeLowLimitScalar = Convert.ToDouble(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case IEPEXMLFields.DisableAutoSense: DisableAutoSense = Convert.ToBoolean(node.InnerText); break;
default: throw new NotSupportedException("IEPESensorDefault::ProcessXMLElement unsupported field: " + field);
}
}
}
public void WriteXML(ref System.Xml.XmlWriter writer)
{
writer.WriteStartElement("IEPESettingDefaults");
writer.WriteStartElement(IEPEXMLFields._24PowerHigh.ToString());
writer.WriteString(_24VPowerHigh.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteEndElement();
writer.WriteStartElement(IEPEXMLFields._24PowerLow.ToString());
writer.WriteString(_24VPowerLow.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteEndElement();
writer.WriteStartElement(IEPEXMLFields.RangeHighLimitScalar.ToString());
writer.WriteString(RangeHighLimitScalar.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteEndElement();
writer.WriteStartElement(IEPEXMLFields.RangeLowLimitScalar.ToString());
writer.WriteString(RangeLowLimitScalar.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteEndElement();
writer.WriteStartElement(IEPEXMLFields.DisableAutoSense.ToString());
writer.WriteString(DisableAutoSense.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
#endregion methods
}
public enum IEPEXMLFields
{
_24PowerHigh,
_24PowerLow,
RangeHighLimitScalar,
RangeLowLimitScalar,
DisableAutoSense
}
}

View File

@@ -0,0 +1,300 @@
using System.Collections.Generic;
using System.Linq;
using DTS.Common.Utilities.Logging;
using DTS.Slice.Users;
namespace DTS.SensorDB
{
/// <summary>
/// A class that handles merging of sensor calibrations
/// </summary>
public class SensorMerge
{
public List<SensorData> SensorDataMergeList { get; private set; } = new List<SensorData>();
public Dictionary<string, List<SensorCalibration>> SensorCalibrationMergeList { get; private set; } = new Dictionary<string, List<SensorCalibration>>();
public Dictionary<int, int> OldSensorDatabaseIdToNew { get; private set; } = new Dictionary<int, int>();
private readonly User _currentUser = null;
private readonly object _lock = new object();
private Dictionary<string, MergeStatus> _mergeStatuses = new Dictionary<string, MergeStatus>();
public MergeStatus GetMergeStatus(string serialNumber)
{
lock (_lock)
{
return _mergeStatuses.ContainsKey(serialNumber) ? _mergeStatuses[serialNumber] : null;
}
}
public List<MergeStatus> GetMergeStatuses(List<string> serialNumbers)
{
var rv = new List<MergeStatus>();
foreach (var sn in serialNumbers)
{
rv.Add(GetMergeStatus(sn));
}
return rv;
}
public List<MergeStatus> GetAllMergeStatuses()
{
var rv = new List<MergeStatus>();
lock (_lock)
{
rv.AddRange(_mergeStatuses.Values);
}
return rv;
}
public class MergeStatus
{
/// <summary>
/// Gets or sets the string for IsSensorInUse for the sensor
/// </summary>
public string BrokenDoNotUse { get; set; }
/// <summary>
/// Gets or sets the bool for a sensor with an EID that matches another sensor in the database
/// </summary>
public bool ConflictedEID { get; set; }
/// <summary>
/// Gets or sets the bool for a sensor with an EID that matches another sensor in the database
/// </summary>
public bool WarnConflictedEID { get; set; }
/// <summary>
/// Gets or sets the bool for a sensor that may match serial number and cal date but have different calibration information.
/// </summary>
public bool ConflictedSensor { get; set; }
/// <summary>
/// If true, the sensor did not get committed because of an error
/// </summary>
public bool Errored => ConflictedEID && ConflictedSensor && WarnConflictedEID || ErrorCommitingCal || MismatchedModelOrBridgeType;
/// <summary>
/// indicates that there was an error with the cal or the cal failed to be committed
/// </summary>
public bool ErrorCommitingCal { get; set; } = false;
/// <summary>
/// If true, the sensor did not get committed because there was newer/same information in the database.
/// </summary>
public bool Ignored { get; set; }
/// <summary>
/// If true, the sensor was committed or updated.
/// </summary>
public bool Committed { get; set; }
/// <summary>
/// If true, the input file had a mismatch in the Model or BridgeType column
/// </summary>
public bool MismatchedModelOrBridgeType { get; set; }
}
public SensorMerge(User currentUser)
{
_currentUser = currentUser;
}
public SensorMerge(User currentUser, List<SensorData> sensorDataToMerge, Dictionary<string, List<SensorCalibration>> sensorCalibrationsToMerge)
{
SensorDataMergeList = sensorDataToMerge;
SensorCalibrationMergeList = sensorCalibrationsToMerge;
_currentUser = currentUser;
}
public SensorMerge(User currentUser, List<SensorData> sensorDataToMerge, Dictionary<string, List<SensorCalibration>> sensorCalibrationsToMerge, Dictionary<int, int> oldSensorDatabaseIdToNew)
{
SensorDataMergeList = sensorDataToMerge;
SensorCalibrationMergeList = sensorCalibrationsToMerge;
OldSensorDatabaseIdToNew = oldSensorDatabaseIdToNew;
_currentUser = currentUser;
}
public void PerformWork()
{
lock (_lock)
{
_mergeStatuses = new Dictionary<string, MergeStatus>();
// Verify that SensorDataMergeList Contains the Calibration entries.
// If it doesn't, add from the DB, if they exist there.
foreach (var scList in SensorCalibrationMergeList)
{
var sn = scList.Value.FirstOrDefault()?.SerialNumber;
if (string.IsNullOrEmpty(sn)) continue;
if (SensorDataMergeList.Any(x => string.Equals(x.SerialNumber, sn))) continue;
var existing = SensorsCollection.SensorsList.GetSensorBySerialNumber(sn);
if (existing != null)
{
SensorDataMergeList.Add(existing);
}
}
//handle broken [true] before do not use
//handle do not use [true] before regular.
SensorDataMergeList.Sort((a, b) =>
{
if (a.Equals(b))
{
return 0;
}
if (a.Broken == b.Broken)
{
if (a.DoNotUse == b.DoNotUse)
{
return a.CompareTo(b);
}
return a.DoNotUse ? -1 : 1;
}
return a.Broken ? -1 : 1;
});
foreach (var sd in SensorDataMergeList)
{
try
{
_mergeStatuses[sd.SerialNumber] = new MergeStatus();
var oldId = sd.DatabaseId;
if (sd.Broken || sd.DoNotUse)
{
_mergeStatuses[sd.SerialNumber].BrokenDoNotUse = DTS.SensorDB.SensorsCollection.SensorsList.IsSensorInUse(sd);
}
if (sd.IsSquib() || sd.IsDigitalInput() || sd.IsDigitalOutput())
{
var existing =
DTS.SensorDB.SensorsCollection.SensorsList.GetSensorBySerialNumber(sd.SerialNumber);
if (null == existing)
{
if (DTS.SensorDB.SensorsCollection.SensorsList.SensorIdExists(sd.EID))
{
//just fine, note it and don't commit it
_mergeStatuses[sd.SerialNumber].WarnConflictedEID = true;
}
else
{
CommitToSensorList(sd, oldId);
_mergeStatuses[sd.SerialNumber].Committed = true;
}
}
else if (!existing.SimpleEquals(sd))
{
// Setting does not match. Update it.
CommitToSensorList(sd, oldId);
_mergeStatuses[sd.SerialNumber].Committed = true;
}
else
{
_mergeStatuses[sd.SerialNumber].Ignored = true;
//just fine, note and move on (don't commit
}
}
else
{
if (!SensorCalibrationMergeList.ContainsKey(sd.UUID)) continue;
var scNew = SensorCalibrationMergeList[sd.UUID].FirstOrDefault();
var scOld = DTS.SensorDB.SensorCalibrationList.GetLatestCalibrationBySerialNumber(sd);
var bCommit = false;
if (null == scOld)
{
bCommit = true;
if (DTS.SensorDB.SensorsCollection.SensorsList.SensorIdExists(sd.EID) &&
(!sd.Broken || !sd.DoNotUse))
{
bCommit = false;
_mergeStatuses[sd.SerialNumber].ConflictedEID = true;
//ERROR
}
}
else if (scOld.CalibrationDate.Date < scNew.CalibrationDate || sd.Broken || sd.DoNotUse)
{
bCommit = true;
}
else if (scOld.CalibrationDate == scNew.CalibrationDate)
{
bCommit = false;
var sdOld = DTS.SensorDB.SensorsCollection.SensorsList.GetSensorBySerialNumber(sd.SerialNumber, false);
if (null == sdOld || !sdOld.SimpleEquals(sd))
{
//if the cal dates are the same but the cal info is not, we've got an error
//if the ids are the same, the cal dates are the same, and broken and do not use are all the same,
//we've got nothing to update, so we've got an error
//if broken/donotuse/id change do the update
if (null != sdOld && (!scOld.SimpleEquals(scNew) ||
sdOld.EID.Equals(sd.EID) && sdOld.Broken == sd.Broken && sd.DoNotUse == sdOld.DoNotUse))
{
_mergeStatuses[sd.SerialNumber].ConflictedSensor = true;
//ERROR
}
else
{
//http://fogbugz/fogbugz/default.asp?10391
//allow updating if the cal info is the same, and ids have changed
//we might want to check that just the id changed ...
bCommit = true;
}
}
else
{
//just fine, note it and don't commit it
_mergeStatuses[sd.SerialNumber].Ignored = true;
}
}
if (!bCommit) continue;
try
{
CommitToSensorList(sd, oldId);
}
catch (System.Exception ex)
{
//flag all 3 problems otherwise "Errored" isn't true with current rules
_mergeStatuses[sd.SerialNumber].ConflictedEID = true;
_mergeStatuses[sd.SerialNumber].ConflictedSensor = true;
_mergeStatuses[sd.SerialNumber].WarnConflictedEID = true;
APILogger.Log(ex);
continue;
}
if (null != scNew && !scNew.SimpleEquals(scOld))
{
try
{
//avoid any dates which are invalid according to ms sql
if (scNew.CalibrationDate.Year <= 1900)
{
_mergeStatuses[sd.SerialNumber].ErrorCommitingCal = true;
APILogger.Log($"Invalid date: {scNew.CalibrationDate.ToShortDateString()} - {sd.SerialNumber}");
continue;
}
SensorCalibrationList.Commit(scNew, true, sd);
}
catch (System.Exception ex)
{
_mergeStatuses[sd.SerialNumber].ErrorCommitingCal = true;
APILogger.Log(ex);
continue;
}
}
_mergeStatuses[sd.SerialNumber].Committed = true;
}
}
catch (System.Exception ex)
{
if (ex.Message.Contains("can't change sensor to"))
{
_mergeStatuses[sd.SerialNumber].MismatchedModelOrBridgeType = true;
}
else
{
_mergeStatuses[sd.SerialNumber].ErrorCommitingCal = true;
}
APILogger.Log(ex);
continue;
}
}
}
}
private void CommitToSensorList(SensorData sd, int oldId)
{
SensorsCollection.SensorsList.Commit(_currentUser.UserName, sd, false);
if (sd.DatabaseId != oldId)
{
OldSensorDatabaseIdToNew[oldId] = sd.DatabaseId;
}
}
}
}

View File

@@ -0,0 +1,239 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTS.SensorDB.TSF;
namespace DTS.SensorDB
{
/// <summary>
/// helper class to read/write TSF files
/// mostly taken from TDC code
/// </summary>
public class TSFFile
{
private const double MINIMUM_BRIDGE_RESISTANCE_OHMS = 100D;
private const double MAXIMUM_BRIDGE_RESISTANCE_OHMS = 16000.0D;
/// <summary>
/// cribbed from tdc, the string to indicate an empty rack
/// </summary>
public const string EMPTY_RACK_SN = "NONE";
/// <summary>
/// cribbed from TDC, crash barrier types
/// </summary>
public enum ICRASH_BARRIER_TYPE
{
IWALL_BARRIER = 0,
ITROLLEY_BARRIER = 1
};
/// <summary>
/// this is a replacement function for TDC functionality
/// we don't really have this functionality in datapro yet, so we have
/// a filler function for now
/// </summary>
/// <returns></returns>
public ICRASH_BARRIER_TYPE GetICrashBarrierType()
{
return ICRASH_BARRIER_TYPE.IWALL_BARRIER;
}
/// <summary>
/// set progress, value should be 0-1 (so multiply by 100 to get percent)
/// </summary>
/// <param name="value"></param>
public delegate void RegisterProgressDelgate(double value);
private string _softwareVersion;
public string SoftwareVersion { get { return _softwareVersion; } set { _softwareVersion = value; } }
private double _versionNumber;
public double VersionNumber { get { return _versionNumber; } set { _versionNumber = value; } }
private string _tsfName;
public string TSFName { get { return _tsfName; } set { _tsfName = value; } }
private string _sysDate;
public string SysDate { get { return _sysDate; } set { _sysDate = value; } }
private string _sysTime;
public string SysTime { get { return _sysTime; } set { _sysTime = value; } }
private string _testDescription;
public string TestDescription { get { return _testDescription; } set { _testDescription = value; } }
public enum Tags
{
SoftwareVersion,
VersionNumber,
TSFName,
SysDate,
SysTime,
TestDescription,
SamplingInformationSection,
RackInformationSection,
ModuleInformationSection,
SensorChannelSection,
CalculatedChannelSection,
TOMChannelSection,
TCFSection
}
private TSFTCFSection _tcfSection = new TSFTCFSection();
public TSFTCFSection TCFSection
{
get { return _tcfSection; }
set { _tcfSection = value; }
}
private TSFTOMChannelInformationSection _tomChannelSection = new TSFTOMChannelInformationSection();
public TSFTOMChannelInformationSection TOMChannelSection
{
get { return _tomChannelSection; }
set { _tomChannelSection = value; }
}
private TSFCalculatedChannelInformationSection _calculatedChannelSection = new TSFCalculatedChannelInformationSection();
public TSFCalculatedChannelInformationSection CalculatedChannelSection
{
get { return _calculatedChannelSection; }
set { _calculatedChannelSection = value; }
}
private TSFSensorChannelInformationSection _sensorChannelSection = new TSFSensorChannelInformationSection();
public TSFSensorChannelInformationSection SensorChannelSection
{
get { return _sensorChannelSection; }
set { _sensorChannelSection = value; }
}
private TSFModuleInformationSection _moduleInformationSection = new TSFModuleInformationSection();
public TSFModuleInformationSection ModuleInformationSection
{
get { return _moduleInformationSection; }
set { _moduleInformationSection = value; }
}
private TSFRackInformationSection _rackInformationSection = new TSFRackInformationSection();
public TSFRackInformationSection RackInformationSection
{
get { return _rackInformationSection; }
set { _rackInformationSection = value; }
}
private TSFSamplingInformationSection _samplingSection;
public TSFSamplingInformationSection SamplingInformationSection
{
get { return _samplingSection; }
set { _samplingSection = value; }
}
private TSFDIMSection _dimSection = new TSFDIMSection();
public TSFDIMSection DIMSection
{
get { return _dimSection; }
set { _dimSection = value; }
}
private TSFG5DigitalInputSection _g5DigitalInputSection = new TSFG5DigitalInputSection();
public TSFG5DigitalInputSection G5DigitalInputSection
{
get { return _g5DigitalInputSection; }
set { _g5DigitalInputSection = value; }
}
/// <summary>
/// read a TSF file, extract out all the different components
/// </summary>
/// <param name="filename"></param>
/// <param name="system"></param>
/// <param name="tsfReadProtocol"></param>
/// <param name="workingSIFDirectory"></param>
/// <param name="defaultAveWindowStart"></param>
/// <param name="defaultAveWindowStop"></param>
public void ReadTSF(string filename, TDCINIFile ini, string tsfReadProtocol, string workingSIFDirectory,
double defaultAveWindowStart, double defaultAveWindowStop, out List<ReadTSFError> errors, RegisterProgressDelgate setProgress)
{
errors = new List<ReadTSFError>();
var invariant = System.Globalization.CultureInfo.InvariantCulture;
// CHECK IF FILE EXISTS
if (!System.IO.File.Exists(filename))
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_FILE_NOT_FOUND));
return;
}
// TDC does this, it doesn't seem to be necessary for us
// DETERMINE DIRECTORY FROM WHICH TSF OPENED
//var fileInfo = new System.IO.FileInfo(filename);
//string location = fileInfo.DirectoryName;
// READ IN VALUES FROM TSF
List<string> lines = new List<string>();
try
{
lines.AddRange(System.IO.File.ReadAllLines(filename));
}
catch (System.Exception ex) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_FILE_IO_ERROR, 0, ex.Message)); return; }
if (lines.Count < 5) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSFFILE_INCOMPLETE)); return; }
SoftwareVersion = lines[0];
try { VersionNumber = double.Parse(SoftwareVersion.Substring(0, 3), invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_INVALID_VERSION, 0, SoftwareVersion)); return; }
//tdc sets some static variables for rack sizes based on the soft version, it doesn't seem to be necessary for our purposes?
List<string> temp = new List<string>();
temp.AddRange(lines);
lines.Clear();
foreach (string l in temp)
{
string s = l.TrimEnd();
s = s.Replace('\t', ',');
lines.Add(s);
}
int currentLine = 1;
TSFName = lines[currentLine++];
SysDate = lines[currentLine++];
SysTime = lines[currentLine++];
TestDescription = lines[currentLine++];
// CHECK VERSION, IF OLDER THEN 6.3 THEN BAIL
if (VersionNumber < 6.3) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_OLD_FILE_VERSION, 0, VersionNumber.ToString())); return; }
try
{
SamplingInformationSection = new TSFSamplingInformationSection(lines, ref currentLine);
}
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine)); return; }
var systemDescription = ini.GetSystemDescription();
RackInformationSection.ReadFrom(lines, ref currentLine, ref errors, this, systemDescription);
setProgress(currentLine / (double)lines.Count);
ModuleInformationSection.ReadFrom(lines, ref currentLine, ref errors, systemDescription, RackInformationSection);
setProgress(currentLine / (double)lines.Count);
SensorChannelSection.ReadFrom(lines, ref currentLine, ref errors);
CalculatedChannelSection.ReadFrom(lines, ref currentLine, ref errors);
TOMChannelSection.ReadFrom(lines, ref currentLine, ref errors);
TCFSection.ReadFrom(lines, ref currentLine, ref errors);
DIMSection.ReadFrom(lines, ref currentLine, ref errors);
G5DigitalInputSection.ReadFrom(lines, ref currentLine, ref errors);
}
}
}

View File

@@ -0,0 +1,90 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DTS.SensorDB {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class StringResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal StringResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DTS.SensorDB.StringResources", typeof(StringResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Digital In.
/// </summary>
internal static string Digital_In {
get {
return ResourceManager.GetString("Digital_In", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Axis {1}.
/// </summary>
internal static string SensorAxis {
get {
return ResourceManager.GetString("SensorAxis", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ---.
/// </summary>
internal static string Value_NA {
get {
return ResourceManager.GetString("Value_NA", resourceCulture);
}
}
}
}

View File

@@ -0,0 +1,101 @@
using DTS.Common.Classes;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO.Ports;
namespace DTS.SensorDB
{
public class UartSetting : SensorData
{
///<summary>
///</summary>
public UartSetting() : base()
{
SetDefaults(this);
}
public UartSetting(UartSetting copy) : base(copy)
{
SetDefaults(this);
}
public UartSetting(IUARTRecord record)
{
SetDefaults(this);
DatabaseId = record.Id;
SerialNumber = record.SerialNumber;
UartBaudRate = record.UartBaudRate;
UartDataBits = record.UartDataBits;
UartStopBits = record.UartStopBits;
UartParity = record.UartParity;
//FB 30486 Hardcode FlowControl to NONE for UART sensor type
UartDataFormat = record.UartDataFormat;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
LastModified = record.LastModified;
LastUpdatedBy = record.LastUpdatedBy;
}
//public UartSetting(IDataRecord reader)
//{
// SetDefaults(this);
// try
// {
// DatabaseId = Convert.ToInt32(reader["Id"]);
// SerialNumber = Convert.ToString(reader[DbOperations.UartIOSettings.Fields.SerialNumber.ToString()]);
// UartBaudRate = Convert.ToUInt32(reader[DbOperations.UartIOSettings.Fields.BaudRate.ToString()]);
// UartDataBits = Convert.ToUInt32(reader[DbOperations.UartIOSettings.Fields.DataBits.ToString()]);
// UartStopBits = (StopBits)Enum.Parse(typeof(StopBits), Convert.ToString(reader[DbOperations.UartIOSettings.Fields.StopBits.ToString()]));
// UartParity = (Parity)Enum.Parse(typeof(Parity), Convert.ToString(reader[DbOperations.UartIOSettings.Fields.Parity.ToString()]));
// UartFlowControl = (Handshake)Enum.Parse(typeof(Handshake), Convert.ToString(reader[DbOperations.UartIOSettings.Fields.FlowControl.ToString()]));
// UartDataFormat = (UartDataFormat)Enum.Parse(typeof(UartDataFormat), Convert.ToString(reader[DbOperations.UartIOSettings.Fields.DataFormat.ToString()]));
// Broken = Utility.GetBool((IDataReader)reader, DbOperations.UartIOSettings.Fields.Broken.ToString());
// DoNotUse = Utility.GetBool((IDataReader)reader, DbOperations.UartIOSettings.Fields.DoNotUse.ToString());
// LastModified = Convert.ToDateTime(reader[DbOperations.UartIOSettings.Fields.LastModified.ToString()]);
// LastUpdatedBy = Convert.ToString(reader[DbOperations.UartIOSettings.Fields.LastModifiedBy.ToString()]);
// }
// catch (Exception ex)
// {
// APILogger.Log("Failed to process: ", ex);
// }
//}
public static void SetDefaults(SensorData sd)
{
sd.SupportedExcitation = new Common.Enums.ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Undefined };
sd.Bridge = SensorConstants.BridgeType.UART;
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 1;
sd.DisplayUnit = "";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 0;
sd.OffsetToleranceLow = 0;
sd.Model = "UART Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
IUARTRecord record = new UARTRecord(setting);
var hr = DbOperations.SensorsUARTUpdateInsert(ref record);
if (0 == hr)
{
setting.DatabaseId = record.Id;
}
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// this class just adds TestChannelNumber to all channels in a TSF
/// some sections have a datachannel #, however tom squib fire channels don't, tom digital channels don't, etc
/// it's advantageous to still be able to index those channels as well
/// </summary>
public abstract class TSFChannel
{
public const int NOT_ASSIGNED = -1;
private int _testChannelNumber = NOT_ASSIGNED;
public int TestChannelNumber
{
get { return _testChannelNumber; }
set { _testChannelNumber = value; }
}
}
}

View File

@@ -0,0 +1,139 @@
using System;
using DTS.Common.Classes.Sensors;
namespace DTS.SensorDB
{
/// <summary>
/// an entry in the Start Sensor Channel Information section of a TSF
/// can contain
/// datachan,rack,mod,chan,descrip,s/n,offsetlow,offsethigh,calmode,calstep(ohm/volt),shuntval(eu),proptoext,sens(mv/eu or mv/v/eu),gain,extvolt,EU,filter,invert,zeroref,desiredmaxrange,commentfield,caldate,Offset?,InitialEU,sensorID,ISOcode,IRTRACC exponent,sensor category,desired max range scaling,C0,C1,C2,C3,C4,C5
/// these entries are analog sensor channels
/// </summary>
public class TSFSensorEntry : TSFChannel
{
public enum Fields
{
datachan,
rack,
mod,
chan,
descrip,
serialNumber,
offsetlow,
offsethigh,
calmode,
calstep,//(ohm/volt),
shuntval,//(eu)
proptoext,
sens,//(mv/eu or mv/v/eu),
gain,
extvolt,
EU,
filter,
invert,
zeroref,
desiredmaxrange,
commentfield,
caldate,
Offset,//?,
InitialEU,
sensorID,
ISOcode,
IRTRACCexponent,
sensorcategory,
desiredmaxrangescaling,
C0,
C1,
C2,
C3,
C4,
C5
}
public int DataChan { get; set; }
public int Rack { get; set; }
public int Module { get; set; }
public int Chan { get; set; }
public string Description { get; set; }
public string SerialNumber { get; set; }
public double OffsetLow { get; set; }
public double OffsetHigh { get; set; }
public bool RemoveOffset { get; set; } = true;
public CalMode CalMode { get; set; } = new CalMode();
public double CalStep { get; set; }
public double ShuntValue { get; set; }
public bool ProportionalToExcitation { get; set; }
public double Sensitivity { get; set; }
public double Gain { get; set; }
public double ExtVolt { get; set; }
public string EU { get; set; }
/*private string _filter;
public string Filter { get { return _filter; } set { _filter = value; } }
*/
public double Filter { get; set; }
public bool Invert { get; set; }
public ZeroRef ZeroRef { get; set; }
public double DesiredMaxRange { get; set; }
public string CommentField { get; set; }
public DateTime CalDate { get; set; }
public bool Offset { get; set; }
public double InitialEU { get; set; }
private string _sensorId;
public string SensorId
{
get { return _sensorId; }
set
{
if (value.ToLower() == "none") { value = ""; }
_sensorId = value;
}
}
public string ISOCode { get; set; }
public double IRTRACCexponent { get; set; }
public SensorInformationFile.TDCSensorCategory SensorCategory { get; set; } = SensorInformationFile.TDCSensorCategory.Normal;
public double DesiredMaxRangeScaling { get; set; }
public double C0 { get; set; }
public double C1 { get; set; }
public double C2 { get; set; }
public double C3 { get; set; }
public double C4 { get; set; }
public double C5 { get; set; }
public double C6 { get; set; }
}
}

View File

@@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Digital_In" xml:space="preserve">
<value>Digital In</value>
</data>
<data name="SensorAxis" xml:space="preserve">
<value>{0} Axis {1}</value>
</data>
<data name="Value_NA" xml:space="preserve">
<value>---</value>
</data>
</root>

View File

@@ -0,0 +1,427 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using DTS.Common.Enums;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
namespace DTS.SensorDB
{
public class SensorCalibrationList
{
private static List<SensorCalibration> _cachedCalibrations = null;
public static void SetCachedCalibrations(SensorCalibration[] cachedCals)
{
_cachedCalibrations = null == cachedCals ? null : new List<SensorCalibration>(cachedCals);
}
public static void ClearCachedCalibrations()
{
_cachedCalibrations = null;
_calibrationList?._calibrations?.Clear();
}
// I'm not sure we ever want to call this constructor? we probably always want to get all?
//22287 Calibration error in Edit Test Setup when DataPRO is initiated and Sensors tab is not clicked first.
//private SensorCalibrationList(string sensorSerialNumber)
//{
// _calibrations = new Dictionary<string, List<SensorCalibration>>();
// var hr = DbOperations.SensorCalibrationsGet(null, sensorSerialNumber, out var records);
// if( 0 == hr && null != records && records.Any())
// {
// foreach( var record in records)
// {
// var sc = new SensorCalibration(record);
// if (!_calibrations.ContainsKey(sc.SerialNumber))
// {
// _calibrations.Add(sc.SerialNumber, new List<SensorCalibration>());
// }
// _calibrations[sc.SerialNumber].Add(sc);
// }
// }
//}
protected SensorCalibrationList(ISensorCalDbRecord[] records)
{
_calibrations = new Dictionary<string, List<SensorCalibration>>();
if (null != records && records.Any())
{
foreach (var record in records)
{
var sc = new SensorCalibration(record);
if (!_calibrations.ContainsKey(sc.SerialNumber))
{
_calibrations.Add(sc.SerialNumber, new List<SensorCalibration>());
}
_calibrations[sc.SerialNumber].Add(sc);
}
}
}
private readonly Dictionary<string, List<SensorCalibration>> _calibrations;
private static readonly object LOCK = new object();
private static SensorCalibrationList _calibrationList;
public static void Reload()
{
lock (LOCK)
{
_calibrationList = new SensorCalibrationList(GetSensorCalibrationsFromDb());
}
}
public static void Reload(ISensorCalDbRecord[] records)
{
lock (LOCK)
{
_calibrationList = new SensorCalibrationList(records);
}
}
public static ISensorCalDbRecord[] GetSensorCalibrationsFromDb()
{
var hr = DbOperations.SensorCalibrationsGet(null, null, out var records);
if (hr == 0) { return records; }
return new ISensorCalDbRecord[0];
}
public static SensorCalibration GetLatestCalibrationBySerialNumber(SensorData sd, ISensorCalDbRecord[] sensorCalDbRecords = null)
{
if (null == sd) { return null; }
if (sd.IsDigitalInput() || sd.IsSquib() || sd.IsDigitalOutput()) { return SensorCalibration.NewDigitalSC(sd.IsDigitalInput() ? sd.DIUnits : "V"); }
if (null != _cachedCalibrations)
{
var matches = from sc in _cachedCalibrations where sc.SerialNumber == sd.SerialNumber select sc;
var sensorCalibrations = matches as SensorCalibration[] ?? matches.ToArray();
if (sensorCalibrations.Any())
{
return ValidateAndGetSensorCalibrationFromCache(sensorCalibrations);
}
}
lock (LOCK)
{
AssignCalibrationListFromFb(ref sensorCalDbRecords);
if (_calibrationList._calibrations.ContainsKey(sd.SerialNumber) && _calibrationList._calibrations[sd.SerialNumber].Count > 0)
{
return ValidateAndGetSensorCalibration(sd);
}
return null;
}
}
private static SensorCalibration ValidateAndGetSensorCalibrationFromCache(SensorCalibration[] sensorCalibrations)
{
SensorCalibration cal = null;
foreach (var sc in sensorCalibrations)
{
if (null == cal || cal.CalibrationDate < sc.CalibrationDate || cal.CalibrationDate == sc.CalibrationDate && cal.ModifyDate < sc.ModifyDate) { cal = sc; }
}
return cal;
}
private static void AssignCalibrationListFromFb(ref ISensorCalDbRecord[] sensorCalDbRecords)
{
if ((null == _calibrationList) || (_calibrationList._calibrations == null) || (!_calibrationList._calibrations.Any()))
{
if (sensorCalDbRecords == null)
{
sensorCalDbRecords = GetSensorCalibrationsFromDb();
}
_calibrationList = new SensorCalibrationList(sensorCalDbRecords);
}
}
private static SensorCalibration ValidateAndGetSensorCalibration(SensorData sd)
{
try
{
var item = _calibrationList._calibrations[sd.SerialNumber].Aggregate((i1, i2) =>
{
if (i1.CalibrationDate > i2.CalibrationDate)
{
return i1;
}
else
{
return i1.CalibrationDate == i2.CalibrationDate && i1.ModifyDate > i2.ModifyDate ? i1 : i2;
}
});
return new SensorCalibration(item);//for safety reasons, don't return the original
}
catch (Exception ex)
{
APILogger.Log(ex);
}
return null;
}
public static SensorCalibration NewEmbeddedSC(string units)
{
return SensorCalibration.NewEmbeddedSC(units);
}
public static SensorCalibration GetLatestCalibrationBySerialNumberAndExcitation(SensorData sd, ExcitationVoltageOptions.ExcitationVoltageOption exc)
{
if (null == sd) { return null; }
if (sd.IsDigitalInput() || sd.IsSquib() || sd.IsDigitalOutput()) { return SensorCalibration.NewDigitalSC(sd.IsDigitalInput() ? sd.DIUnits : "V"); }
if (sd.IsTestSpecificEmbedded) { return SensorCalibration.NewEmbeddedSC(sd.Calibration?.EngineeringUnits ?? "V"); } //TODO: REMOVE THIS HACK when we have proper get cal functions
if (sd.IsTestSpecificThermo) { return SensorCalibration.NewEmbeddedSC(sd.Calibration?.EngineeringUnits ?? "C"); }
if (null != _cachedCalibrations && _cachedCalibrations.Any())
{
var matches = from sc in _cachedCalibrations where sc.SerialNumber == sd.SerialNumber select sc;
var sensorCalibrations = matches as SensorCalibration[] ?? matches.ToArray();
if (sensorCalibrations.Any())
{
SensorCalibration cal = null;
foreach (var sc in sensorCalibrations)
{
if (sc.IsProportional)
{
var bOk = Array.Exists(sc.Records.Records, record => record.Excitation == exc);
if (!bOk) { continue; }
}
if (null == cal) { cal = sc; }
else if (sc.CalibrationDate > cal.CalibrationDate) { cal = sc; }
else if (sc.CalibrationDate == cal.CalibrationDate && sc.ModifyDate > cal.ModifyDate)
{
cal = sc;
}
}
if (null != cal) { return cal; }
}
}
lock (LOCK)
{
if (null == _calibrationList || 0 == _calibrationList._calibrations.Count)
{
_calibrationList = new SensorCalibrationList(GetSensorCalibrationsFromDb());
}
if (!_calibrationList._calibrations.ContainsKey(sd.SerialNumber) || _calibrationList._calibrations[sd.SerialNumber].Count <= 0) return null;
try
{
var list = _calibrationList._calibrations[sd.SerialNumber];
list.Sort();
foreach (var sc in list)
{
if (!sc.IsProportional) { return new SensorCalibration(sc); }
if (Array.Exists(sc.Records.Records, record => record.Excitation == exc))
{
return new SensorCalibration(sc);
}
}
}
catch (Exception ex) { APILogger.Log(ex); }
return null;
}
}
public static SensorCalibration GetLatestCalibrationsBySerialNumberAndCalDate(string ser, DateTime calDate)
{
if (null == _calibrationList)
{
_calibrationList = new SensorCalibrationList(GetSensorCalibrationsFromDb());
}
if (!_calibrationList._calibrations.ContainsKey(ser) || _calibrationList._calibrations[ser].Count <= 0)
return null;
try
{
var list = new List<SensorCalibration>(_calibrationList._calibrations[ser]);
for (var i = list.Count - 1; i >= 0; i--)
{
if (list[i].CalibrationDate != calDate) { list.RemoveAt(i); }
}
if (list.Count <= 0) return null;
list.Sort();
return new SensorCalibration(list[0]);
}
catch (Exception ex) { APILogger.Log(ex); }
return null;
}
public static SensorCalibration GetLatestCalibrationsBySerialNumberCalDateAndModifyDate(string ser, DateTime calDate, DateTime modifyDate)
{
if (null == _calibrationList)
{
_calibrationList = new SensorCalibrationList(GetSensorCalibrationsFromDb());
}
if (_calibrationList._calibrations.ContainsKey(ser) && _calibrationList._calibrations[ser].Count > 0)
{
try
{
var list = new List<SensorCalibration>(_calibrationList._calibrations[ser]);
for (var i = list.Count - 1; i >= 0; i--)
{
if (list[i].CalibrationDate != calDate)
{
list.RemoveAt(i);
}
else
{
//12488 Import Test Setup adds new sensor calibration entries every time
//note that modify date as datetime can have more deviation than cal dates, which are just date
//so we have to consider the minimum varation between time, which I set to 1 second here
var delta = list[i].ModifyDate.Subtract(modifyDate);
if (Math.Abs(delta.TotalSeconds) >= 1)
{
list.RemoveAt(i);
}
}
}
if (list.Count <= 0) return null;
list.Sort();
return new SensorCalibration(list[0]);
}
catch (Exception ex) { APILogger.Log(ex); }
return null;
}
return null;
}
public static SensorCalibration[] GetCalibrationsBySerialNumber(SensorData sd)
{
if (null == sd) { return new SensorCalibration[0]; }
if (sd.IsDigitalInput() || sd.IsSquib() || sd.IsDigitalOutput()) { return new[] { SensorCalibration.NewDigitalSC(sd.IsDigitalInput() ? sd.DIUnits : "V") }; }
if (null != _cachedCalibrations)
{
var matches = from sc in _cachedCalibrations where sd.SerialNumber == sc.SerialNumber select sc;
var sensorCalibrations = matches as SensorCalibration[] ?? matches.ToArray();
if (sensorCalibrations.Any())
{
return sensorCalibrations.ToArray();
}
}
lock (LOCK)
{
if (null == _calibrationList || 0 == _calibrationList._calibrations.Count)
{
_calibrationList = new SensorCalibrationList(GetSensorCalibrationsFromDb());
}
if (!_calibrationList._calibrations.ContainsKey(sd.SerialNumber)) return new SensorCalibration[0];
var list = new List<SensorCalibration>(_calibrationList._calibrations[sd.SerialNumber].Count);
list.AddRange(_calibrationList._calibrations[sd.SerialNumber].Select(sc => new SensorCalibration(sc)));
return list.ToArray();
}
}
/// <summary>
/// commits a sensor to the db
/// </summary>
/// <param name="sc"></param>
/// <param name="bChangeModifyDate"></param>
/// <param name="sd"></param>
/// <param name="bSetLatestCalId">whether to set the calibration id on the sensor to the sensor calibration when the calibration is committed</param>
public static void Commit(SensorCalibration sc, bool bChangeModifyDate, SensorData sd, bool bSetLatestCalId = false)
{
try
{
if (sd.IsDigitalInput() || sd.IsDigitalOutput() || sd.IsSquib()
|| sd.IsStreamOutput() || sd.IsStreamInput() || sd.IsUart()) { return; }
if (null == sc) { return; }
SensorCalibration scExisting = null;
if (!bChangeModifyDate) { scExisting = GetLatestCalibrationsBySerialNumberCalDateAndModifyDate(sc.SerialNumber, sc.CalibrationDate, sc.ModifyDate); }
if (null != scExisting && sc.Equals(scExisting)) { return; }//no update needed
if (string.IsNullOrEmpty(sc.SerialNumber)) { return; }//don't commit a calibration without a serialnumber
//correct units capitalization if needed
foreach (var record in sc.Records.Records)
{
var units = MeasurementUnitList.GetMeasurementUnit(record.EngineeringUnits);
if (null != units && units.MainDisplayUnit != record.EngineeringUnits) { record.EngineeringUnits = units.MainDisplayUnit; }
}
sc.Username = string.Empty;
if (null != DbOperations.CurrentUserDbRecord) { sc.Username = DbOperations.CurrentUserDbRecord.UserName; }
sc.Insert(bChangeModifyDate, sd, bSetLatestCalId);
if (!_calibrationList._calibrations.ContainsKey(sc.SerialNumber)) { _calibrationList._calibrations.Add(sc.SerialNumber, new List<SensorCalibration>()); }
_calibrationList._calibrations[sc.SerialNumber].Add(new SensorCalibration(sc));
}
// ReSharper disable once PossibleNullReferenceException
catch (Exception ex) { APILogger.Log("Failed to write sensor calibration", sc.SerialNumber, ex); }
}
/// <summary>
/// deletes all calibration data
/// originally created so TDM imports could clear all tables except DAS tables
/// </summary>
public static void DeleteAll()
{
try
{
var hr = DbOperations.SensorCalibrationsDelete(null, null, null);
if (0 != hr) { return; }
lock (LOCK)
{
if (null == _calibrationList)
{
_calibrationList = new SensorCalibrationList(GetSensorCalibrationsFromDb());
}
_calibrationList._calibrations.Clear();
}
}
catch (Exception ex) { APILogger.Log("Failed to delete sensor calibrations ", ex); }
}
/// <summary>
/// Deletes Calibration records from the database and Calibration List dictionary that match the serialNumber param
/// </summary>
/// <param name="serialNumber"></param>
public static void DeleteCalsBySerialNumber(string serialNumber)
{
// 6853 - Sensitivities are lost when importing SLICEWare sensors.
try
{
var hr = DbOperations.SensorCalibrationsDelete(serialNumber, null, null);
if (0 != hr)
{
APILogger.Log("Failed to delete sensor calibration ", serialNumber, hr);
return;
}
lock (LOCK)
{
if (null == _calibrationList) { _calibrationList = new SensorCalibrationList(GetSensorCalibrationsFromDb()); }
if (!_calibrationList._calibrations.ContainsKey(serialNumber)) return;
for (var i = _calibrationList._calibrations[serialNumber].Count - 1; i >= 0; i--) { _calibrationList._calibrations[serialNumber].RemoveAt(i); }
}
}
catch (Exception ex) { APILogger.Log("Failed to delete sensor calibration ", serialNumber, ex); }
}
public static void Delete(SensorCalibration sc)
{
try
{
var hr = DbOperations.SensorCalibrationsDelete(sc.SerialNumber, sc.CalibrationDate.Date, sc.ModifyDate);
if (0 != hr)
{
APILogger.Log("Failed to delete sensor calibration ", sc.SerialNumber, sc.CalibrationDate.ToShortDateString(), sc.ModifyDate.ToString(CultureInfo.InvariantCulture), hr);
return;
}
lock (LOCK)
{
if (null == _calibrationList)
{
_calibrationList = new SensorCalibrationList(GetSensorCalibrationsFromDb());
}
if (!_calibrationList._calibrations.ContainsKey(sc.SerialNumber)) return;
for (var i = _calibrationList._calibrations[sc.SerialNumber].Count - 1; i >= 0; i--)
{
if (_calibrationList._calibrations[sc.SerialNumber][i].CalibrationDate != sc.CalibrationDate ||
_calibrationList._calibrations[sc.SerialNumber][i].ModifyDate != sc.ModifyDate) continue;
_calibrationList._calibrations[sc.SerialNumber].RemoveAt(i);
break;
}
}
}
catch (Exception ex) { APILogger.Log("Failed to delete sensor calibration ", sc.SerialNumber, sc.CalibrationDate.ToShortDateString(), sc.ModifyDate.ToString(CultureInfo.InvariantCulture), ex); }
}
}
}

View File

@@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using DTS.Common.Utilities.Logging;
using DTS.Common.DAS.Concepts;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
namespace DTS.SensorDB
{
public abstract class SensorDBBase
{
//protected System.Globalization.CultureInfo InvariantCulture = System.Globalization.CultureInfo.InvariantCulture;
//protected string TableName;
private static void Error(string tag, string id, string TableName)
{
if (!string.IsNullOrEmpty(id))
throw new System.Exception(string.Format("{0}: Can't find tag {1} for entry {2}", TableName, tag, id));
else
throw new System.Exception(string.Format("{0}: Can't find tag {1} in file", TableName, tag));
}
public static XElement GetTagValueSafe(XElement elem, string tag, string id, String TableName)
{
XElement tmp = null;
try
{
tmp = elem.Element(tag);
}
catch (System.Exception)
{
}
return tmp;
}
public static XElement GetTagValue(XElement elem, string tag, string id, String TableName)
{
XElement tmp = null;
try
{
tmp = elem.Element(tag);
}
catch (System.Exception)
{
Error(tag, id, TableName); // will not return
}
if (tmp == null)
{
Error(tag, id, TableName); // will not return
}
return tmp;
}
public static void GetValue(XElement elem, string tag, out string target, string id, string TableName)
{
target = (string)GetTagValue(elem, tag, id, TableName);
}
public static void GetValueSafe(XElement elem, string tag, out string target, string id, string TableName)
{
try { target = (string)GetTagValueSafe(elem, tag, id, TableName); }
catch (System.Exception ex)
{
APILogger.Log(ex.Message);
target = "";
}
}
public static void GetValue(XElement elem, string tag, out int target, string id, string TableName)
{
target = (int)GetTagValue(elem, tag, id, TableName);
}
public static void GetValue(XElement elem, string tag, out SensorStatus target, string id, string TableName)
{
target = (SensorStatus)Enum.Parse(typeof(SensorStatus), (string)GetTagValue(elem, tag, id, TableName));
}
public static void GetValue(XElement elem, string tag, out double target, string id, string TableName)
{
var element = GetTagValue(elem, tag, id, TableName);
if (double.TryParse(element.Value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out var d))
{
target = d;
}
else { target = double.NaN; }
}
public static void GetValue(XElement elem, string tag, out bool target, string id, string TableName)
{
target = (bool)GetTagValue(elem, tag, id, TableName);
}
public static void GetValue(XElement elem, string tag, out SensorConstants.BridgeType target, string id, string TableName)
{
var myEnum = Enum.Parse(typeof(SensorConstants.BridgeType), (string)GetTagValue(elem, tag, id, TableName));
target = (SensorConstants.BridgeType)myEnum;
}
public static void GetValue(XElement elem, string tag, out ShuntMode target, string id, string TableName)
{
target = (ShuntMode)Enum.Parse(typeof(ShuntMode), (string)GetTagValue(elem, tag, id, TableName));
}
public static void GetValue(XElement elem, string tag, out BridgeLeg target, string id, string TableName)
{
target = (BridgeLeg)Enum.Parse(typeof(BridgeLeg), (string)GetTagValue(elem, tag, id, TableName));
}
public static void GetValue(XElement elem, string tag, out ExcitationVoltageOptions.ExcitationVoltageOption target, string id, string TableName)
{
target = ExcitationVoltageOptions.ExcitationVoltageOption.Undefined;
try
{
var excitationStr = (string)GetTagValue(elem, tag, id, TableName);
// this excitation string should be in the form Volt2, Volt2_5, Volt5 and so on
// to be a little more helpful, we'll try to manage strings in 2, 2.5, 5 format
// too.
if (!excitationStr.StartsWith("Volt"))
{
excitationStr = "Volt" + excitationStr.Replace('.', '_');
}
target = ExcitationVoltageOptions.ExcitationVoltageOption.Volt5;
Enum.TryParse(excitationStr, out target);
//(Test.Module.Channel.Sensor.ExcitationVoltageOption)Enum.Parse(typeof(Test.Module.Channel.Sensor.ExcitationVoltageOption), excitationStr);
if (target == ExcitationVoltageOptions.ExcitationVoltageOption.Undefined)
{
target = ExcitationVoltageOptions.ExcitationVoltageOption.Volt5;
}
//throw new ArgumentException("SensorDB: " + excitationStr + " is not a valid excitation");
}
catch (System.Exception ex) { APILogger.Log(ex.Message, ex); }
}
public static void GetValue(XElement elem, string tag, out DateTime target, string id, string TableName)
{
target = (DateTime)GetTagValue(elem, tag, id, TableName);
}
public static void GetValue(XElement elem, string tag, out FilterClassType target, string id, string TableName)
{
target = (FilterClassType)Enum.Parse(typeof(FilterClassType), (string)GetTagValue(elem, tag, id, TableName));
}
public static void GetValue(XElement elem, string tag, out ZeroMethodType target, string id, string TableName)
{
var myEnum = Enum.Parse(typeof(ZeroMethodType), (string)GetTagValue(elem, tag, id, TableName));
target = (ZeroMethodType)myEnum;
}
}
}

View File

@@ -0,0 +1,76 @@
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
using System;
namespace DTS.SensorDB
{
public class StreamInputSetting : SensorData
{
///<summary>
///</summary>
public StreamInputSetting() : base()
{
SetDefaults(this);
}
public StreamInputSetting(StreamInputSetting copy) : base(copy)
{
SetDefaults(this);
}
public StreamInputSetting(IStreamInputRecord record)
{
SetDefaults(this);
try
{
DatabaseId = record.Id;
SerialNumber = record.SerialNumber;
StreamInUDPAddress = record.StreamInUDPAddress;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
LastModified = record.LastModified;
LastUpdatedBy = record.LastUpdatedBy;
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
}
public static void SetDefaults(SensorData sd)
{
sd.SupportedExcitation = new Common.Enums.ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Undefined };
sd.Bridge = SensorConstants.BridgeType.StreamIn;
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 1;
sd.DisplayUnit = "";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 0;
sd.OffsetToleranceLow = 0;
sd.Model = "Stream Input Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
IStreamInputRecord record = new StreamInputRecord(setting);
var hr = DbOperations.SensorsStreamInputUpdateInsert(ref record);
if (0 == hr)
{
setting.DatabaseId = record.Id;
}
}
}
}

View File

@@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// stolen from HLAPI
/// this is only sparsely used in DataPRO currently and is mostly reference
/// </summary>
public class TSFInputChannelDescription
{
private int _version;
public int Version { get { return _version; } set { _version = value; } }
private TSFChannelDescription _parent;
public TSFChannelDescription Parent { get { return _parent; } set { _parent = value; } }
private int _source;
public int Source { get { return _source; } set { _source = value; } }
private ulong _crc32;
public ulong CRC32 { get { return _crc32; } set { _crc32 = value; } }
private bool _analogInfoValid;
public bool AnalogInfoValid { get { return _analogInfoValid; } set { _analogInfoValid = value; } }
/// <summary>
/// HLAPI_INPUT_TYPE
/// </summary>
private char _analogChannelType;
public char AnalogChannelType { get { return _analogChannelType; } set { _analogChannelType = value; } }
/// <summary>
/// See HLAPI_INPUT_FILTER_MODE
/// </summary>
private char _analogChannelFilterMode;
public char AnalogChannelFilterMode { get { return _analogChannelFilterMode; } set { _analogChannelFilterMode = value; } }
/// <summary>
/// See HLAPI_INPUT_OFFSET_MODE
/// </summary>
private char _analogChannelOffsetMode;
public char AnalogChannelOffsetMode { get { return _analogChannelOffsetMode; } set { _analogChannelOffsetMode = value; } }
/// <summary>
/// See HLAPI_INPUT_SHUNT_MODE
/// </summary>
private char _analogChannelShuntMode;
public char AnalogChannelShuntMode { get { return _analogChannelShuntMode; } set { _analogChannelShuntMode = value; } }
private double _analogExcitationVoltage;
public double AnalogExcitationVoltage { get { return _analogExcitationVoltage; } set { _analogExcitationVoltage = value; } }
private double _analogGain;
public double AnalogGain { get { return _analogGain; } set { _analogGain = value; } }
private int _analogShuntResistanceOhms;
public int AnalogShuntResistanceOhms { get { return _analogShuntResistanceOhms; } set { _analogShuntResistanceOhms = value; } }
private int _analogShuntEmulationOhms;
public int AnalogShuntEmulationOhms { get { return _analogShuntEmulationOhms; } set { _analogShuntEmulationOhms = value; } }
private double _analogShuntEU;
public double AnalogShuntEU { get { return _analogShuntEU; } set { _analogShuntEU = value; } }
private double _analogSensitivity;
public double AnalogSensitivity { get { return _analogSensitivity; } set { _analogSensitivity = value; } }
private char _analogSensitivityUnits;
public char AnalogSensitivityUnits { get { return _analogSensitivityUnits; } set { _analogSensitivityUnits = value; } }
private string _analogEULabel;
public string AnalogEULabel { get { return _analogEULabel; } set { _analogEULabel = value; } }
private bool _analogInvertData;
public bool AnalogInvertData { get { return _analogInvertData; } set { _analogInvertData = value; } }
private bool _digitalInfoValid;
public bool DigitalInfoValid { get { return _digitalInfoValid; } set { _digitalInfoValid = value; } }
private bool _realtimeInfoValid;
public bool RealtimeInfoValid { get { return _realtimeInfoValid; } set { _realtimeInfoValid = value; } }
private bool _useForRealtime;
public bool UseForRealtime { get { return _useForRealtime; } set { _useForRealtime = value; } }
private static object MyLock = new object();
private List<short> _realtimeADC = new List<short>();
public short[] RealtimeADC
{
get { lock (MyLock) { return _realtimeADC.ToArray(); } }
set { lock (MyLock) { _realtimeADC = new List<short>(value); } }
}
public int RealtimeSamples
{
get { lock (MyLock) { return RealtimeADC.Length; } }
}
public TSFInputChannelDescription() { }
public TSFInputChannelDescription(TSFInputChannelDescription copy, TSFChannelDescription channel)
{
_analogChannelFilterMode = copy._analogChannelFilterMode;
_analogChannelOffsetMode = copy._analogChannelOffsetMode;
_analogChannelShuntMode = copy._analogChannelShuntMode;
_analogChannelType = copy._analogChannelType;
_analogEULabel = copy._analogEULabel;
_analogExcitationVoltage = copy._analogExcitationVoltage;
_analogGain = copy._analogGain;
_analogInfoValid = copy._analogInfoValid;
_analogInvertData = copy._analogInvertData;
_analogSensitivity = copy._analogSensitivity;
_analogSensitivityUnits = copy._analogSensitivityUnits;
_analogShuntEmulationOhms = copy._analogShuntEmulationOhms;
_analogShuntEU = copy._analogShuntEU;
_analogShuntResistanceOhms = copy._analogShuntResistanceOhms;
_crc32 = copy._crc32;
_digitalInfoValid = copy._digitalInfoValid;
_parent = channel;
_realtimeADC = new List<short>();
_realtimeInfoValid = false;
_source = copy._source;
_useForRealtime = copy._useForRealtime;
_version = copy._version;
}
}
}

View File

@@ -0,0 +1,445 @@
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram MajorVersion="1" MinorVersion="1">
<Class Name="DTS.SensorDB.CalibrationRecords" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="16.25" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>IAAAAAAAEAEAAAAAAQAgAQAAEAAAAAAAAQAAAAAAAAA=</HashCode>
<FileName>CalibrationRecords.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.CalibrationRecord" Collapsed="true">
<Position X="14.5" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AICgAAAAEwIQBAgAEQAAAQIAQVAIAACAAAAAAIBAAAA=</HashCode>
<FileName>CalibrationRecords.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.DigitalInputSetting" Collapsed="true">
<Position X="0.5" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>DigitalInputSetting.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.DigitalOutputSetting" Collapsed="true">
<Position X="2.75" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAEAAQAAAAAAAIAAAAAAAgAEAAAAAAAAAAAAAAEA=</HashCode>
<FileName>DigitalOutputSetting.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.FilterClass" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="18" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAQAQAABAAAAAAAEoAQAAAAAgKEgAIAAAIAgARCABAA=</HashCode>
<FileName>FilterClass.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.IsoCode" Collapsed="true">
<Position X="18" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AEAAOAAAAAAEgIggACUokAAAAAAAACAAAAAIQIAAAAA=</HashCode>
<FileName>IsoCode.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.MeasurementUnit" Collapsed="true">
<Position X="21.5" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAEQAAEAAAIAAAEgAAABCAAAAQASAAAAAAAAAEAgAA=</HashCode>
<FileName>MeasurementUnit.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.MeasurementUnitList" Collapsed="true">
<Position X="23.25" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AIAEEIAAAAAgAAAAAAAAAAAAAECAAAAIAAIAAggAAAI=</HashCode>
<FileName>MeasurementUnit.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorCalibration" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="14.5" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>IEAAQFEIWCEKICUCsxAAkQQAoAFAAoAARGsRAAAhAAA=</HashCode>
<FileName>SensorCalibration.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SensorCalibrationList" Collapsed="true">
<Position X="16.25" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAEAAAAAAAAQgAABAAAQAMgEIAAAADAgBAAABAAA=</HashCode>
<FileName>SensorCalibrationList.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorData" Collapsed="true">
<Position X="2.75" Y="5" Width="1.5" />
<TypeIdentifier>
<HashCode>2EBMPEBcPHgEIQSlcs3AAQWCyIMUiocC7DGLhSUIBYU=</HashCode>
<FileName>SensorData.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" />
</Class>
<Class Name="DTS.SensorDB.LowHigh" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="19.75" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAQAgAAAAAAABAAAIhQAAAACgAlAAAAAQAAAARAAAAA=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SensorDBTables" Collapsed="true">
<Position X="19.75" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAA4ZaACBVDBIEYoAAmAocEhAgQgQCCTCwCQQoIHEE=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorDBBase" Collapsed="true">
<Position X="18" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>CAAAAAAAJAAAAQAAAAAAAAAAAAAAAAAAAAQAAAAAAAA=</HashCode>
<FileName>SensorDBBase.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorInformationFile" Collapsed="true">
<Position X="21.5" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>QAAAAgBAAAAAAAAAAAAAAQAgIAAAAIAAAAAAAAAAAEA=</HashCode>
<FileName>SensorInformationFile.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorBase" Collapsed="true">
<Position X="3.75" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>Mm5USGQAIBAIaASAAWhABICCAZhQJApxQluOwpwiCKs=</HashCode>
<FileName>SensorModel.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorModel" Collapsed="true">
<Position X="7.25" Y="5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAQAAAAAAAEAoAAAAAAAAAAAgEAAAAAAAAACIE=</HashCode>
<FileName>SensorModel.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" />
</Class>
<Class Name="DTS.SensorDB.SensorModelCollection" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="23.25" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAEAAAQQACEIgIACEAIAAgIGIgAAgAEAAAEgAAAA=</HashCode>
<FileName>SensorModel.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SensorRange" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="25" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACQAAAAAAAAAAAAAIhQAAgACgAlAAAAAAAAAARAEAAA=</HashCode>
<FileName>SensorRange.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SensorsCollection" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="14.5" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AIAAIEGAAYACAAYkIAAEIIDIgAFARANEGMEgCANAAAE=</HashCode>
<FileName>SensorsCollection.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SquibSetting" Collapsed="true">
<Position X="5" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAgAAEAAQAAAAAAAAAAAAAQAAACEAAAAwAAAAAAAAAA=</HashCode>
<FileName>SquibSetting.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.StringResources" Collapsed="true">
<Position X="16.25" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAAAABEAAAAQAAAUAAAAAAAAAAAIA=</HashCode>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.Strings" Collapsed="true">
<Position X="18" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>wBKgBCDBDyAEQQl4BBABEAIgEQgABAIQAgACAABADMA=</HashCode>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINIFile" Collapsed="true">
<Position X="21.5" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>OWOOJv/hAMuGGvz0YvB5gz3K/JhVLU5Ii8qhUTsjIG4=</HashCode>
<FileName>TDCINI\TDCINIFile.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.G5DigtalInputChannelTSFEntry" Collapsed="true">
<Position X="0.75" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>IAABCGAAAAAAAAAEAAIAAAAAACAAAgAEAAAgCAgABCI=</HashCode>
<FileName>TSF\G5DigitalInputChannelTSFEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFCalibrationInformation" Collapsed="true">
<Position X="16.25" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>KAgCDAAgAkAAIQBgIBAAQgAYGAAAACEAIAABAKJCEAQ=</HashCode>
<FileName>TSF\TSFCalibrationInformation.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFChannel" Collapsed="true">
<Position X="6.25" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAABAAAAAAAAAAAAAAAAAAIAAAAAAAAQAAAAAAA=</HashCode>
<FileName>TSF\TSFChannel.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFChannelDescription" Collapsed="true">
<Position X="18" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>IAAABQAAA0AAIASQKgCAaACQQgBmgBEAIxAAEAXACCA=</HashCode>
<FileName>TSF\TSFChannelDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFTOMDigitalOutputChannel" Collapsed="true">
<Position X="12" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>ADABACAEAAAiIAQEABAAAAAAAAAIAgAAAQAACAgAAAA=</HashCode>
<FileName>TSF\TSFDigitalChannel.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFFile" Collapsed="true">
<Position X="21.5" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAkFQAAoAAAAAmRCIAAgAQgAQgEAIE0GAAAhAAAAUAU=</HashCode>
<FileName>TSF\TSFFile.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFInputChannelDescription" Collapsed="true">
<Position X="14.5" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>MBgAAQARIkUAIMAAAgEGQCExIcBCKAIAAAAhVQBACAA=</HashCode>
<FileName>TSF\TSFInputChannelDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFModuleDescription" Collapsed="true">
<Position X="16.25" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>JACAACABs0AAIAQAAhAoQIIQAAIkBAEAAREEAABAAiA=</HashCode>
<FileName>TSF\TSFModuleDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFOutputChannelDescription" Collapsed="true">
<Position X="19.75" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>KAAAAAIKCkgGIQCAMghAQAwYiAQCCAEQBAABDCFCAAA=</HashCode>
<FileName>TSF\TSFOutputChannelDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFRackDescription" Collapsed="true">
<Position X="21.5" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>OQDARQiCQ0AILAQEAMEIYJAwCAhEABICFRkQgQBAIAE=</HashCode>
<FileName>TSF\TSFRackDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFSensorEntry" Collapsed="true">
<Position X="5.25" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAIRMGQACEEgBAAAAAABAIAACZEFgkAIAAAgCCEAlBI=</HashCode>
<FileName>TSF\TSFSensorEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFSquibFireEntry" Collapsed="true">
<Position X="7.5" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>ABADACAEAAAiIARAADDAAAAAACAMAgAAAQABTggAAAA=</HashCode>
<FileName>TSF\TSFSquibFireEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFSystemDescription" Collapsed="true">
<Position X="16.25" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>MRAkGEgYA0hQLAFMAIEBQmAkAAKQAQCGEAgAgAJILAA=</HashCode>
<FileName>TSF\TSFSystemDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIDataZeroTimeWindowSeconds" Collapsed="true">
<Position X="19.75" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAIAAAAAACAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>TDCINI\INIDataZeroTimeWindowSeconds.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIIIHSExport" Collapsed="true">
<Position X="21.5" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AQEAAAAAAAAAAAAAAAAAAAQgAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>TDCINI\INIIIHSExport.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIISOExportParameters" Collapsed="true">
<Position X="23.25" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAACAAAAACAAAEAAAAAAAoACAAABAAAAAAEAAQIAA=</HashCode>
<FileName>TDCINI\INIISOExportParameters.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIRackInventory" Collapsed="true">
<Position X="25" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAACAAAAAAAAAAAAAAAAAgAgAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>TDCINI\INIRackInventory.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INISmartBatteryThresholds" Collapsed="true">
<Position X="14.5" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAgAAAAAAAAAgAAAAAAAAAAAAACAAAAA=</HashCode>
<FileName>TDCINI\INISmartBatteryThresholds.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIViewerROI" Collapsed="true">
<Position X="16.25" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAACAACAAgAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>TDCINI\INIViewerROI.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.TDCINIError" Collapsed="true">
<Position X="19.75" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAQBAAAABAAAAAAAAIAAAAAAQAAABAAA=</HashCode>
<FileName>TDCINI\TDCINIError.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.TDCINIRS232Info" Collapsed="true">
<Position X="23.25" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAAABAAAAgAAAAAAAAAAAAAAQBAAA=</HashCode>
<FileName>TDCINI\TDCINIRS232Info.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.TSFINIRegionOfInterest" Collapsed="true">
<Position X="25" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAAIAAAAAgAAAAAAAAAAAAAgAAAAA=</HashCode>
<FileName>TDCINI\TSFINIRegionOfInterest.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDM.TDMCSVImport" Collapsed="true">
<Position X="25" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAAAABAAAQAAAACAABIAAAAAAAAAA=</HashCode>
<FileName>TDM\TDMCSVImport.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.ReadTSFError" Collapsed="true">
<Position X="25" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAQBAAAAJAAAAAAAAIAAAAAAQAAAAAAA=</HashCode>
<FileName>TSF\ReadTSFError.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFTOMChannelInformationSection" Collapsed="true">
<Position X="19.75" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>gAAAAAAAAAAAAADAAJAAAAAiAAQAAIAAAAAAAAAgAIA=</HashCode>
<FileName>TSF\TOMChannelInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFCalculatedChannelEntry" Collapsed="true">
<Position X="3" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AFAAIBABAABgAAAHAAAxAAAIAQAAAgAAAAAgAAmgAAA=</HashCode>
<FileName>TSF\TSFCalculatedChannelEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFCalculatedChannelInformationSection" Collapsed="true">
<Position X="14.5" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACAAAAAAAAAAAAAAAAAAAAQgAAEAAEAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFCalculatedChannelInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFDIMEntry" Collapsed="true">
<Position X="9.75" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>EBABAOgCAIAoAAQEAgIAACAAACEAAgCAAAAgCAxQBCI=</HashCode>
<FileName>TSF\TSFDIMEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFDIMSection" Collapsed="true">
<Position X="19.75" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ECAAAAAAAAAAAAAAAAAAAAAgAIAAAEAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFDIMSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFG5DigitalInputSection" Collapsed="true">
<Position X="23.25" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACBAAAAAAAAAAAAAAAgAAAAgAAAAAEAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFG5DigitalInputSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFModuleInformationSection" Collapsed="true">
<Position X="18" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACAAAAAAAAAAAAAAAAAAAAAgAAAAAEAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFModuleInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFRackInformationSection" Collapsed="true">
<Position X="23.25" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAACAAAAAAAAAAAAAAAAAgAgQAAMAAAAAAAAAAAAA=</HashCode>
<FileName>TSF\TSFRackInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFSamplingInformationSection" Collapsed="true">
<Position X="25" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAACCRAAAAAABAAAAAAAAAAgQAAMEEAAYAAAAAAAA=</HashCode>
<FileName>TSF\TSFSamplingInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFSensorChannelInformationSection" Collapsed="true">
<Position X="14.5" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>CCAAAAAAAAAAACEAAAIAAAAgAAAAAAAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFSensorChannelInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFTCFSection" Collapsed="true">
<Position X="18" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFTCFSection.cs</FileName>
</TypeIdentifier>
</Class>
<Enum Name="DTS.SensorDB.ShuntMode" Collapsed="true">
<Position X="18" Y="7.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAIAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAEACAA=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
</Enum>
<Enum Name="DTS.SensorDB.BridgeLeg" Collapsed="true">
<Position X="14.5" Y="7.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAgAAAAAAAQAAAAAAAAIAAAAAAAAAAAAAAAAAAQA=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
</Enum>
<Enum Name="DTS.SensorDB.CouplingModes" Collapsed="true">
<Position X="16.25" Y="7.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAABAAgAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
</Enum>
<Font Name="Segoe UI" Size="9" />
</ClassDiagram>

View File

@@ -0,0 +1,383 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using DTS.Common.Enums;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
namespace DTS.SensorDB
{
public class SensorCalibrationList
{
private static List<SensorCalibration> _cachedCalibrations = null;
public static void SetCachedCalibrations(SensorCalibration[] cachedCals)
{
_cachedCalibrations = null == cachedCals ? null : new List<SensorCalibration>(cachedCals);
}
public static void ClearCachedCalibrations()
{
_cachedCalibrations = null;
_calibrationList?._calibrations?.Clear();
}
// I'm not sure we ever want to call this constructor? we probably always want to get all?
//22287 Calibration error in Edit Test Setup when DataPRO is initiated and Sensors tab is not clicked first.
//private SensorCalibrationList(string sensorSerialNumber)
//{
// _calibrations = new Dictionary<string, List<SensorCalibration>>();
// var hr = DbOperations.SensorCalibrationsGet(null, sensorSerialNumber, out var records);
// if( 0 == hr && null != records && records.Any())
// {
// foreach( var record in records)
// {
// var sc = new SensorCalibration(record);
// if (!_calibrations.ContainsKey(sc.SerialNumber))
// {
// _calibrations.Add(sc.SerialNumber, new List<SensorCalibration>());
// }
// _calibrations[sc.SerialNumber].Add(sc);
// }
// }
//}
protected SensorCalibrationList()
{
_calibrations = new Dictionary<string, List<SensorCalibration>>();
var hr = DbOperations.SensorCalibrationsGet(null, null, out var records);
if (0 == hr && null != records && records.Any())
{
foreach (var record in records)
{
var sc = new SensorCalibration(record);
if (!_calibrations.ContainsKey(sc.SerialNumber))
{
_calibrations.Add(sc.SerialNumber, new List<SensorCalibration>());
}
_calibrations[sc.SerialNumber].Add(sc);
}
}
}
private readonly Dictionary<string, List<SensorCalibration>> _calibrations;
private static readonly object LOCK = new object();
private static SensorCalibrationList _calibrationList;
public static void Reload()
{
lock (LOCK)
{
_calibrationList = new SensorCalibrationList();
}
}
public static SensorCalibration GetLatestCalibrationBySerialNumber(SensorData sd)
{
if (null == sd) { return null; }
if (sd.IsDigitalInput() || sd.IsSquib() || sd.IsDigitalOutput()) { return SensorCalibration.NewDigitalSC(sd.IsDigitalInput() ? sd.DIUnits : "V"); }
if (null != _cachedCalibrations)
{
var matches = from sc in _cachedCalibrations where sc.SerialNumber == sd.SerialNumber select sc;
var sensorCalibrations = matches as SensorCalibration[] ?? matches.ToArray();
if (sensorCalibrations.Any())
{
SensorCalibration cal = null;
foreach (var sc in sensorCalibrations)
{
if (null == cal) { cal = sc; }
else if (cal.CalibrationDate < sc.CalibrationDate) { cal = sc; }
else if (cal.CalibrationDate == sc.CalibrationDate && cal.ModifyDate < sc.ModifyDate)
{
cal = sc;
}
}
return cal;
}
}
lock (LOCK)
{
if ((null == _calibrationList) || (_calibrationList._calibrations == null) || (!_calibrationList._calibrations.Any()))
{
_calibrationList = new SensorCalibrationList();
}
if (_calibrationList._calibrations.ContainsKey(sd.SerialNumber) && _calibrationList._calibrations[sd.SerialNumber].Count > 0)
{
try
{
var item = _calibrationList._calibrations[sd.SerialNumber].Aggregate((i1, i2) =>
i1.CalibrationDate > i2.CalibrationDate ? i1 : i1.CalibrationDate == i2.CalibrationDate && i1.ModifyDate > i2.ModifyDate ? i1 : i2);
return new SensorCalibration(item);//for safety reasons, don't return the original
}
catch (Exception ex) { APILogger.Log(ex); }
return null;
}
return null;
}
}
public static SensorCalibration NewEmbeddedSC(string units)
{
return SensorCalibration.NewEmbeddedSC(units);
}
public static SensorCalibration GetLatestCalibrationBySerialNumberAndExcitation(SensorData sd, ExcitationVoltageOptions.ExcitationVoltageOption exc)
{
if (null == sd) { return null; }
if (sd.IsDigitalInput() || sd.IsSquib() || sd.IsDigitalOutput()) { return SensorCalibration.NewDigitalSC(sd.IsDigitalInput() ? sd.DIUnits : "V"); }
if (sd.IsTestSpecificEmbedded) { return SensorCalibration.NewEmbeddedSC(sd.Calibration?.EngineeringUnits ?? "V"); } //TODO: REMOVE THIS HACK when we have proper get cal functions
if (null != _cachedCalibrations && _cachedCalibrations.Any())
{
var matches = from sc in _cachedCalibrations where sc.SerialNumber == sd.SerialNumber select sc;
var sensorCalibrations = matches as SensorCalibration[] ?? matches.ToArray();
if (sensorCalibrations.Any())
{
SensorCalibration cal = null;
foreach (var sc in sensorCalibrations)
{
if (sc.IsProportional)
{
var bOk = Array.Exists(sc.Records.Records, record => record.Excitation == exc);
if (!bOk) { continue; }
}
if (null == cal) { cal = sc; }
else if (sc.CalibrationDate > cal.CalibrationDate) { cal = sc; }
else if (sc.CalibrationDate == cal.CalibrationDate && sc.ModifyDate > cal.ModifyDate)
{
cal = sc;
}
}
if (null != cal) { return cal; }
}
}
lock (LOCK)
{
if (null == _calibrationList || 0 == _calibrationList._calibrations.Count)
{
_calibrationList = new SensorCalibrationList();
}
if (!_calibrationList._calibrations.ContainsKey(sd.SerialNumber) || _calibrationList._calibrations[sd.SerialNumber].Count <= 0) return null;
try
{
var list = _calibrationList._calibrations[sd.SerialNumber];
list.Sort();
foreach (var sc in list)
{
if (!sc.IsProportional) { return new SensorCalibration(sc); }
if (Array.Exists(sc.Records.Records, record => record.Excitation == exc))
{
return new SensorCalibration(sc);
}
}
}
catch (Exception ex) { APILogger.Log(ex); }
return null;
}
}
public static SensorCalibration GetLatestCalibrationsBySerialNumberAndCalDate(string ser, DateTime calDate)
{
if (null == _calibrationList)
{
_calibrationList = new SensorCalibrationList();
}
if (!_calibrationList._calibrations.ContainsKey(ser) || _calibrationList._calibrations[ser].Count <= 0)
return null;
try
{
var list = new List<SensorCalibration>(_calibrationList._calibrations[ser]);
for (var i = list.Count - 1; i >= 0; i--)
{
if (list[i].CalibrationDate != calDate) { list.RemoveAt(i); }
}
if (list.Count <= 0) return null;
list.Sort();
return new SensorCalibration(list[0]);
}
catch (Exception ex) { APILogger.Log(ex); }
return null;
}
public static SensorCalibration GetLatestCalibrationsBySerialNumberCalDateAndModifyDate(string ser, DateTime calDate, DateTime modifyDate)
{
if (null == _calibrationList)
{
_calibrationList = new SensorCalibrationList();
}
if (_calibrationList._calibrations.ContainsKey(ser) && _calibrationList._calibrations[ser].Count > 0)
{
try
{
var list = new List<SensorCalibration>(_calibrationList._calibrations[ser]);
for (var i = list.Count - 1; i >= 0; i--)
{
if (list[i].CalibrationDate != calDate)
{
list.RemoveAt(i);
}
else
{
//12488 Import Test Setup adds new sensor calibration entries every time
//note that modify date as datetime can have more deviation than cal dates, which are just date
//so we have to consider the minimum varation between time, which I set to 1 second here
var delta = list[i].ModifyDate.Subtract(modifyDate);
if (Math.Abs(delta.TotalSeconds) >= 1)
{
list.RemoveAt(i);
}
}
}
if (list.Count <= 0) return null;
list.Sort();
return new SensorCalibration(list[0]);
}
catch (Exception ex) { APILogger.Log(ex); }
return null;
}
return null;
}
public static SensorCalibration[] GetCalibrationsBySerialNumber(SensorData sd)
{
if (null == sd) { return new SensorCalibration[0]; }
if (sd.IsDigitalInput() || sd.IsSquib() || sd.IsDigitalOutput()) { return new[] { SensorCalibration.NewDigitalSC(sd.IsDigitalInput() ? sd.DIUnits : "V") }; }
if (null != _cachedCalibrations)
{
var matches = from sc in _cachedCalibrations where sd.SerialNumber == sc.SerialNumber select sc;
var sensorCalibrations = matches as SensorCalibration[] ?? matches.ToArray();
if (sensorCalibrations.Any())
{
return sensorCalibrations.ToArray();
}
}
lock (LOCK)
{
if (null == _calibrationList || 0 == _calibrationList._calibrations.Count)
{
_calibrationList = new SensorCalibrationList();
}
if (!_calibrationList._calibrations.ContainsKey(sd.SerialNumber)) return new SensorCalibration[0];
var list = new List<SensorCalibration>(_calibrationList._calibrations[sd.SerialNumber].Count);
list.AddRange(_calibrationList._calibrations[sd.SerialNumber].Select(sc => new SensorCalibration(sc)));
return list.ToArray();
}
}
/// <summary>
/// commits a sensor to the db
/// </summary>
/// <param name="sc"></param>
/// <param name="bChangeModifyDate"></param>
/// <param name="sd"></param>
/// <param name="bSetLatestCalId">whether to set the calibration id on the sensor to the sensor calibration when the calibration is committed</param>
public static void Commit(SensorCalibration sc, bool bChangeModifyDate, SensorData sd, bool bSetLatestCalId = false)
{
try
{
if (sd.IsDigitalInput() || sd.IsDigitalOutput() || sd.IsSquib()
|| sd.IsStreamOutput() || sd.IsStreamInput() || sd.IsUart()) { return; }
if (null == sc) { return; }
SensorCalibration scExisting = null;
if (!bChangeModifyDate) { scExisting = GetLatestCalibrationsBySerialNumberCalDateAndModifyDate(sc.SerialNumber, sc.CalibrationDate, sc.ModifyDate); }
if (null != scExisting && sc.Equals(scExisting)) { return; }//no update needed
if (string.IsNullOrEmpty(sc.SerialNumber)) { return; }//don't commit a calibration without a serialnumber
//correct units capitalization if needed
foreach (var record in sc.Records.Records)
{
var units = MeasurementUnitList.GetMeasurementUnit(record.EngineeringUnits);
if (null != units && units.MainDisplayUnit != record.EngineeringUnits) { record.EngineeringUnits = units.MainDisplayUnit; }
}
sc.Username = string.Empty;
if (null != DbOperations.CurrentUserDbRecord) { sc.Username = DbOperations.CurrentUserDbRecord.UserName; }
sc.Insert(bChangeModifyDate, sd, bSetLatestCalId);
if (!_calibrationList._calibrations.ContainsKey(sc.SerialNumber)) { _calibrationList._calibrations.Add(sc.SerialNumber, new List<SensorCalibration>()); }
_calibrationList._calibrations[sc.SerialNumber].Add(new SensorCalibration(sc));
}
// ReSharper disable once PossibleNullReferenceException
catch (Exception ex) { APILogger.Log("Failed to write sensor calibration", sc.SerialNumber, ex); }
}
/// <summary>
/// deletes all calibration data
/// originally created so TDM imports could clear all tables except DAS tables
/// </summary>
public static void DeleteAll()
{
try
{
var hr = DbOperations.SensorCalibrationsDelete(null, null, null);
if (0 != hr) { return; }
lock (LOCK)
{
if (null == _calibrationList)
{
_calibrationList = new SensorCalibrationList();
}
_calibrationList._calibrations.Clear();
}
}
catch (Exception ex) { APILogger.Log("Failed to delete sensor calibrations ", ex); }
}
/// <summary>
/// Deletes Calibration records from the database and Calibration List dictionary that match the serialNumber param
/// </summary>
/// <param name="serialNumber"></param>
public static void DeleteCalsBySerialNumber(string serialNumber)
{
// 6853 - Sensitivities are lost when importing SLICEWare sensors.
try
{
var hr = DbOperations.SensorCalibrationsDelete(serialNumber, null, null);
if (0 != hr)
{
APILogger.Log("Failed to delete sensor calibration ", serialNumber, hr);
return;
}
lock (LOCK)
{
if (null == _calibrationList) { _calibrationList = new SensorCalibrationList(); }
if (!_calibrationList._calibrations.ContainsKey(serialNumber)) return;
for (var i = _calibrationList._calibrations[serialNumber].Count - 1; i >= 0; i--) { _calibrationList._calibrations[serialNumber].RemoveAt(i); }
}
}
catch (Exception ex) { APILogger.Log("Failed to delete sensor calibration ", serialNumber, ex); }
}
public static void Delete(SensorCalibration sc)
{
try
{
var hr = DbOperations.SensorCalibrationsDelete(sc.SerialNumber, sc.CalibrationDate.Date, sc.ModifyDate);
if (0 != hr)
{
APILogger.Log("Failed to delete sensor calibration ", sc.SerialNumber, sc.CalibrationDate.ToShortDateString(), sc.ModifyDate.ToString(CultureInfo.InvariantCulture), hr);
return;
}
lock (LOCK)
{
if (null == _calibrationList)
{
_calibrationList = new SensorCalibrationList();
}
if (!_calibrationList._calibrations.ContainsKey(sc.SerialNumber)) return;
for (var i = _calibrationList._calibrations[sc.SerialNumber].Count - 1; i >= 0; i--)
{
if (_calibrationList._calibrations[sc.SerialNumber][i].CalibrationDate != sc.CalibrationDate ||
_calibrationList._calibrations[sc.SerialNumber][i].ModifyDate != sc.ModifyDate) continue;
_calibrationList._calibrations[sc.SerialNumber].RemoveAt(i);
break;
}
}
}
catch (Exception ex) { APILogger.Log("Failed to delete sensor calibration ", sc.SerialNumber, sc.CalibrationDate.ToShortDateString(), sc.ModifyDate.ToString(CultureInfo.InvariantCulture), ex); }
}
}
}

View File

@@ -0,0 +1,69 @@
using DTS.Common.Classes;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO.Ports;
namespace DTS.SensorDB
{
public class CanSetting : SensorData
{
///<summary>
///</summary>
public CanSetting() : base()
{
SetDefaults(this);
}
public CanSetting(CanSetting copy) : base(copy)
{
SetDefaults(this);
}
public CanSetting(ICANRecord record)
{
SetDefaults(this);
DatabaseId = record.Id;
SerialNumber = record.SerialNumber;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
LastModified = record.LastModified;
LastUpdatedBy = record.LastUpdatedBy;
}
public static void SetDefaults(SensorData sd)
{
sd.SupportedExcitation = new Common.Enums.ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Undefined };
sd.Bridge = SensorConstants.BridgeType.CAN;
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 1;
sd.DisplayUnit = "";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 0;
sd.OffsetToleranceLow = 0;
sd.Model = "CAN Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
ICANRecord record = new CANRecord(setting);
var hr = DbOperations.SensorsCanUpdateInsert(ref record);
if (0 == hr)
{
setting.DatabaseId = record.Id;
}
}
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// the G5 Digital Input Channels section entry
/// each entry can contain
/// datachan,rack,mod,chan,descrip,ISOCode,scale,invert
/// </summary>
public class G5DigtalInputChannelTSFEntry : TSFChannel
{
private int _dataChan;
public int DataChan { get { return _dataChan; } set { _dataChan = value; } }
private int _rack;
public int Rack { get { return _rack; } set { _rack = value; } }
private int _mod;
public int Module { get { return _mod; } set { _mod = value; } }
private int _chan;
public int Chan { get { return _chan; } set { _chan = value; } }
private string _descripton;
public string Descripton { get { return _descripton; } set { _descripton = value; } }
private string _isocode;
public string ISOCode { get { return _isocode; } set { _isocode = value; } }
private double _scale;
public double Scale { get { return _scale; } set { _scale = value; } }
private bool _invert;
public bool Invert { get { return _invert; } set { _invert = value; } }
public enum Fields
{
datachan,
rack,
mod,
chan,
descrip,
ISOCode,
scale,
invert
}
}
}

View File

@@ -0,0 +1,204 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
public class IsoCode
{
private char[] _isoCodeFull = new char[] { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };
private char _TestObject { get { return _isoCodeFull[0]; } set { _isoCodeFull[0] = value; } }
public string TestObject
{
get { return new string(new char[] { _TestObject }); }
set
{
if (string.IsNullOrEmpty(value)) { _TestObject = '?'; }
else { _TestObject = value[0]; }
}
}
private char _Position { get { return _isoCodeFull[1]; } set { _isoCodeFull[1] = value; } }
public string Position
{
get { return new string(new char[] { _Position }); }
set
{
if (string.IsNullOrEmpty(value)) { _Position = '?'; }
else { _Position = value[0]; }
}
}
private char[] _MainLocation
{
get { return new char[] { _isoCodeFull[2], _isoCodeFull[3], _isoCodeFull[4], _isoCodeFull[5] }; }
set
{
for (int i = 0; i < 4; i++)
{
if (value.Length <= i) { _isoCodeFull[i + 2] = '0'; }
else { _isoCodeFull[i + 2] = value[i]; }
}
}
}
public string MainLocation
{
get { return new string(_MainLocation); }
set
{
string main = value;
if (main.Length < 4) { main = main.PadRight(4, '?'); }
else if (main.Length > 4) { main = main.Substring(0, 4); }
_MainLocation = main.ToCharArray(0, 4);
}
}
private char[] _FineLocation1
{
get { return new char[] { _isoCodeFull[6], _isoCodeFull[7] }; }
set
{
for (int i = 0; i < 2; i++)
{
if (value.Length < i) { _isoCodeFull[i + 6] = '0'; }
else { _isoCodeFull[i + 6] = value[i]; }
}
}
}
public string FineLocation1
{
get { return new string(_FineLocation1); }
set
{
string loc = value;
if (loc.Length < 2) { loc = loc.PadRight(2, '?'); }
else if (loc.Length > 2) { loc = loc.Substring(0, 2); }
_FineLocation1 = loc.ToCharArray(0, 2);
}
}
private char[] _FineLocation2
{
get { return new char[] { _isoCodeFull[8], _isoCodeFull[9] }; }
set
{
for (int i = 0; i < 2; i++)
{
if (value.Length < i) { _isoCodeFull[i + 8] = '0'; }
else { _isoCodeFull[i + 8] = value[i]; }
}
}
}
public string FineLocation2
{
get { return new string(_FineLocation2); }
set
{
string loc = value;
if (loc.Length < 2) { loc = loc.PadRight(2, '?'); }
else if (loc.Length > 2) { loc = loc.Substring(0, 2); }
_FineLocation2 = loc.ToCharArray(0, 2);
}
}
private char[] _FineLocations3
{
get { return new char[] { _isoCodeFull[10], _isoCodeFull[11] }; }
set
{
for (int i = 0; i < 2; i++)
{
if (value.Length < i) { _isoCodeFull[i + 10] = '0'; }
else { _isoCodeFull[i + 10] = value[i]; }
}
}
}
public string FineLocation3
{
get { return new string(_FineLocations3); }
set
{
string loc = value;
if (loc.Length < 2) { loc = loc.PadRight(2, '?'); }
else if (loc.Length > 2) { loc = loc.Substring(0, 2); }
_FineLocations3 = loc.ToCharArray(0, 2);
}
}
private char[] _PhysicalDimension
{
get { return new char[] { _isoCodeFull[12], _isoCodeFull[13] }; }
set
{
for (int i = 0; i < 2; i++)
{
if (value.Length < i) { _isoCodeFull[i + 12] = '0'; }
else { _isoCodeFull[i + 12] = value[i]; }
}
}
}
public string PhysicalDimension
{
get { return new string(_PhysicalDimension); }
set
{
string dim = value;
if (dim.Length < 2) { dim = dim.PadRight(2, '?'); }
else if (dim.Length > 2) { dim = dim.Substring(0, 2); }
_PhysicalDimension = dim.ToCharArray(0, 2);
}
}
private char _Direction { get { return _isoCodeFull[14]; } set { _isoCodeFull[14] = value; } }
public string Direction
{
get { return new string(new char[] { _Direction }); }
set
{
if (string.IsNullOrEmpty(value)) { _Direction = '?'; }
else { _Direction = value[0]; }
}
}
private char _FilterClass { get { return _isoCodeFull[15]; } set { _isoCodeFull[15] = value; } }
public string FilterClass
{
get { return new string(new char[] { _FilterClass }); }
set
{
if (string.IsNullOrEmpty(value)) { _FilterClass = '?'; }
else { _FilterClass = value[0]; }
}
}
public IsoCode(string isoCode)
{
if (null == isoCode) { isoCode = ""; }
if (isoCode.Length > 16) { isoCode = isoCode.Substring(0, 16); }
if (isoCode.Length < 16)
{
isoCode = isoCode.PadRight(16, '?');
}
for (int i = 0; i < 16; i++) { _isoCodeFull[i] = isoCode[i]; }
}
public string StringRepresentation
{
get
{
StringBuilder sb = new StringBuilder();
foreach (char c in _isoCodeFull) { sb.Append(c); }
return sb.ToString();
}
set
{
for (int i = 0; i < 16; i++)
{
if (i >= value.Length) { _isoCodeFull[i] = '0'; }
else { _isoCodeFull[i] = value[i]; }
}
}
}
}
}

View File

@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// helper class for the rack inventory section of the INI
/// </summary>
public class INIRackInventory
{
/// <summary>
/// helper class for an entry in the INI RackInventory section
/// </summary>
public class INIRackInfo
{
public int Number { get; set; }
public string SerialNumber { get; set; }
public int Size { get; set; }
public string IPAddress { get; set; }
public bool ReadFrom(string line, ref List<TDCINIError> errors)
{
string[] tokens = line.Split(new char[] { ',' });
if (tokens.Length != 4)
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_RACKINVENTORY_INVALID, line));
return false;
}
int i;
if (!int.TryParse(tokens[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out i))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_RACKINVENTORY_INVALID, tokens[0]));
return false;
}
else { Number = i; }
SerialNumber = tokens[1];
if (!int.TryParse(tokens[2], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out i))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_RACKINVENTORY_INVALID, tokens[2]));
return false;
}
else { Size = i; }
IPAddress = tokens[3];
return true;
}
public TSFRackDescription ToTSFRackDescription()
{
TSFRackDescription rack = new TSFRackDescription();
rack.Number = Number;
rack.HWIPAddress = IPAddress;
rack.HWSerialNumber = SerialNumber.Trim();
return rack;
}
}
private List<INIRackInfo> _racks = new List<INIRackInfo>();
public INIRackInfo[] Racks
{
get { return _racks.ToArray(); }
set { _racks = new List<INIRackInfo>(value); }
}
public bool ReadFrom(string[] lines, ref int iCurLine, ref List<TDCINIError> errors)
{
bool bDone = false;
List<INIRackInfo> racks = new List<INIRackInfo>();
while (!bDone)
{
string line = TDCINIFile.GetNextLine(lines, ref iCurLine, ref errors, TDCINIError.INIErrors.INI_RACKINVENTORY_INVALID);
if (null == line) { return false; }
if (line.StartsWith("----")) { bDone = true; }
else
{
INIRackInfo rack = new INIRackInfo();
if (!rack.ReadFrom(line, ref errors))
{
return false;
}
else { racks.Add(rack); }
}
}
Racks = racks.ToArray();
iCurLine--;
return true;
}
}
}

View File

@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// helper class for IIHS export section of INI
/// </summary>
public class INIIIHSExport
{
/// <summary>
/// whether to apply region of interest or not
/// </summary>
public bool ApplyROI { get; set; }
/// <summary>
/// start of ROI in seconds
/// </summary>
public double ROIStartSeconds { get; set; }
/// <summary>
/// end of ROI in seconds
/// </summary>
public double ROIEndSeconds { get; set; }
public bool ReadFrom(string line, int curLine, ref List<TDCINIError> errors)
{
string[] tokens = line.Split(new char[] { ',' });
if (3 != tokens.Length)
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_IIHSExport_INVALID, line, curLine));
return false;
}
switch (tokens[0])
{
case "0":
case "F":
case "N":
ApplyROI = false; break;
case "1":
case "T":
case "Y":
ApplyROI = true; break;
default:
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_IIHSExport_INVALID, tokens[0], curLine));
return false;
}
}
double d;
if (!double.TryParse(tokens[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_IIHSExport_INVALID, tokens[1], curLine));
return false;
}
else { ROIStartSeconds = d; }
if (!double.TryParse(tokens[2], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_IIHSExport_INVALID, tokens[2], curLine));
return false;
}
else { ROIEndSeconds = d; }
return true;
}
}
}

View File

@@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// stolen from HLAPI
/// not really used in DataPRO
/// </summary>
public class TSFOutputChannelDescription
{
private int _version;
public int Version { get { return _version; } set { _version = value; } }
private TSFChannelDescription _parent;
public TSFChannelDescription Parent { get { return _parent; } set { _parent = value; } }
private int _source;
public int Source { get { return _source; } set { _source = value; } }
private ulong _crc32;
public ulong CRC32 { get { return _crc32; } set { _crc32 = value; } }
private bool _squibInfoValid;
public bool SquibInfoValid { get { return _squibInfoValid; } set { _squibInfoValid = value; } }
/// <summary>
/// See HLAPI_OUTPUT_FIRE_MODE
/// </summary>
private char _squibFireMode;
public char SquibFireMode { get { return _squibFireMode; } set { _squibFireMode = value; } }
/// <summary>
/// See HLAPI_OUTPUT_MEASUREMENT_TYPE
/// </summary>
private char _squibMeasurementType;
public char SquibMeasurementType { get { return _squibMeasurementType; } set { _squibMeasurementType = value; } }
private bool _squibBypassCurrentFilter;
public bool SquibBypassCurrentFilter { get { return _squibBypassCurrentFilter; } set { _squibBypassCurrentFilter = value; } }
private bool _squibBypassVoltageFilter;
public bool SquibBypassVoltageFilter { get { return _squibBypassVoltageFilter; } set { _squibBypassVoltageFilter = value; } }
private double _squibToleranceLow;
public double SquibToleranceLow { get { return _squibToleranceLow; } set { _squibToleranceLow = value; } }
private double _squibToleranceHigh;
public double SquibToleranceHigh { get { return _squibToleranceHigh; } set { _squibToleranceHigh = value; } }
private double _squibOutputCurrent;
public double SquibOutputCurrent { get { return _squibOutputCurrent; } set { _squibOutputCurrent = value; } }
private bool _digitalInfoValid;
public bool DigitalInfoValid { get { return _digitalInfoValid; } set { _digitalInfoValid = value; } }
/// <summary>
/// HLAPI_OUTPUT_DIGITAL_MODE
/// </summary>
private char _digitalOutputMode;
public char DigitalOutputMode { get { return _digitalOutputMode; } set { _digitalOutputMode = value; } }
private bool _squibMeasurementValid;
public bool SquibMeasurementValid { get { return _squibMeasurementValid; } set { _squibMeasurementValid = value; } }
private double _squibMeasuredOhms;
public double SquibMeasuredOhms { get { return _squibMeasuredOhms; } set { _squibMeasuredOhms = value; } }
private bool _squibFireValid;
public bool SquibFireValid { get { return _squibFireValid; } set { _squibFireValid = value; } }
private bool _squibFirePassed;
public bool SquibFirePassed { get { return _squibFirePassed; } set { _squibFirePassed = value; } }
private bool _commonInfoValid;
public bool CommonInfoValid { get { return _commonInfoValid; } set { _commonInfoValid = value; } }
private double _commonDelayMS;
public double CommonDelayMS { get { return _commonDelayMS; } set { _commonDelayMS = value; } }
private double _commonDurationMS;
public double CommonDurationMS { get { return _commonDurationMS; } set { _commonDurationMS = value; } }
public TSFOutputChannelDescription() { }
public TSFOutputChannelDescription(TSFOutputChannelDescription copy, TSFChannelDescription channel)
{
_commonDelayMS = copy._commonDelayMS;
_commonDurationMS = copy._commonDurationMS;
_commonInfoValid = copy._commonInfoValid;
_crc32 = copy._crc32;
_digitalInfoValid = copy._digitalInfoValid;
_digitalOutputMode = copy._digitalOutputMode;
_parent = channel;
_source = copy._source;
_squibBypassCurrentFilter = copy._squibBypassCurrentFilter;
_squibBypassVoltageFilter = copy._squibBypassVoltageFilter;
_squibFireMode = copy._squibFireMode;
_squibFirePassed = copy._squibFirePassed;
_squibFireValid = copy._squibFireValid;
_squibInfoValid = copy._squibInfoValid;
_squibMeasuredOhms = copy._squibMeasuredOhms;
_squibMeasurementType = copy._squibMeasurementType;
_squibMeasurementValid = copy._squibMeasurementValid;
_squibOutputCurrent = copy._squibOutputCurrent;
_squibToleranceHigh = copy._squibToleranceHigh;
_squibToleranceLow = copy._squibToleranceLow;
_version = copy._version;
}
}
}

View File

@@ -0,0 +1,61 @@
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
using System;
namespace DTS.SensorDB
{
public class ThermocouplerSetting : SensorData
{
///<summary>
///</summary>
public ThermocouplerSetting() : base()
{
SetDefaults(this);
}
public ThermocouplerSetting(ThermocouplerSetting copy) : base(copy)
{
SetDefaults(this);
}
public ThermocouplerSetting(IThermocouplerRecord record)
{
SetDefaults(this);
try
{
DatabaseId = record.Id;
SerialNumber = record.SerialNumber;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
LastModified = record.LastModified;
LastUpdatedBy = record.LastUpdatedBy;
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
}
public static void SetDefaults(SensorData sd)
{
sd.SupportedExcitation = new Common.Enums.ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Undefined };
sd.Bridge = SensorConstants.BridgeType.Thermocoupler;
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 1;
sd.DisplayUnit = "";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 0;
sd.OffsetToleranceLow = 0;
sd.Model = "Thermocoupler Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
}
}

View File

@@ -0,0 +1,80 @@
using DTS.Common.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// an entry in TOM Digital Channels portion of TOM Channel Information section
/// each entry can contain
/// rack,module,chan,type,delay,durationON,duration
/// These are Output Channels
/// </summary>
public class TSFTOMDigitalOutputChannel : TSFChannel
{
private int _rack;
public int Rack { get { return _rack; } set { _rack = value; } }
private int _module;
public int Module { get { return _module; } set { _module = value; } }
private int _chan;
public int Chan { get { return _chan; } set { _chan = value; } }
public enum DigitalOutputTypes
{
NONE = 0,
FiveVLH = 1,
FiveVHL = 2,
CCNO = 3,
CCNC = 4
}
public static DigitalOutputModes GetDigitalOutputMode(DigitalOutputTypes outputType)
{
switch (outputType)
{
case TSFTOMDigitalOutputChannel.DigitalOutputTypes.CCNC:
return DigitalOutputModes.CCNC;
case TSFTOMDigitalOutputChannel.DigitalOutputTypes.CCNO:
return DigitalOutputModes.CCNO;
case TSFTOMDigitalOutputChannel.DigitalOutputTypes.FiveVHL:
return DigitalOutputModes.FVHL;
case TSFTOMDigitalOutputChannel.DigitalOutputTypes.FiveVLH:
return DigitalOutputModes.FVLH;
case TSFTOMDigitalOutputChannel.DigitalOutputTypes.NONE:
default:
return DigitalOutputModes.NONE;
}
}
private DigitalOutputTypes _type = DigitalOutputTypes.NONE;
public DigitalOutputTypes Type { get { return _type; } set { _type = value; } }
private double _delay;
public double Delay { get { return _delay; } set { _delay = value; } }
private bool _DurationOn;
public bool DurationOn { get { return _DurationOn; } set { _DurationOn = value; } }
private double _duration;
public double Duration { get { return _duration; } set { _duration = value; } }
private string _description = "N/A";
public string Description { get { return _description; } set { _description = value; } }
public enum Fields
{
rack, //%i
module, //%i
chan, //%i
type, //%i
delay, //%f
durationON, //%i
duration //%f
}
}
}

View File

@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// helper class for DataZeroTimeWindow section of INI
/// </summary>
public class INIDataZeroTimeWindowSeconds
{
/// <summary>
/// start of datazero window
/// </summary>
public double Start { get; set; }
/// <summary>
/// end of data zero window
/// </summary>
public double End { get; set; }
public bool ReadFrom(string line, ref List<TDCINIError> errors, int iCurrentLine)
{
string[] tokens = line.Split(new char[] { ',' });
if (2 != tokens.Length)
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_DataZeroTimeWindow_INVALID, line, iCurrentLine));
return false;
}
double d;
if (!double.TryParse(tokens[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_DataZeroTimeWindow_INVALID, line, iCurrentLine));
return false;
}
else { Start = d; }
if (!double.TryParse(tokens[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_DataZeroTimeWindow_INVALID, line, iCurrentLine));
return false;
}
else { End = d; }
return true;
}
}
}

View File

@@ -0,0 +1,138 @@
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
namespace DTS.SensorDB
{
public class DigitalOutputSetting : SensorData
{
public string ChannelDescription
{
get => SerialNumber;
set
{
SerialNumber = value;
OnPropertyChanged("ChannelDescription");
}
}
public DigitalOutputSetting(DigitalOutputSetting copy) : base(copy)
{
SetDefaults(this);
}
public DigitalOutputSetting()
{
SetDefaults(this);
}
//public DigitalOutputSetting(SensorData sd)
// : base(sd)
//{
// SetDefaults(this);
//}
private static void SetDefaults(SensorData sd)
{
sd.SupportedExcitation = new[] { ExcitationVoltageOptions.ExcitationVoltageOption.Volt5 };
sd.Bridge = SensorConstants.BridgeType.TOMDigital;
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 1;
sd.DisplayUnit = "V";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 2500;
sd.OffsetToleranceLow = 2500;
sd.Model = "Digital Output Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public DigitalOutputSetting(IDigitalOutDbRecord copy)
{
DatabaseId = copy.DatabaseId;
Broken = copy.Broken;
DoNotUse = copy.DoNotUse;
Bridge = SensorConstants.BridgeType.TOMDigital;
Version = copy.Version;
DigitalOutputMode = copy.DOMode;
DigitalOutputLimitDuration = copy.LimitDuration;
LastUpdatedBy = copy.ModifiedBy;
LastModified = copy.LastModified;
DigitalOutputDurationMS = copy.DODuration;
DigitalOutputDelayMS = copy.DODelay;
ChannelDescription = copy.SerialNumber;
SerialNumber = copy.SerialNumber;
if (null == copy.TagsBlobBytes)
{
TagsBlobBytes = null;
}
else if (copy.TagsBlobBytes.Any())
{
var bytes = new byte[copy.TagsBlobBytes.Length];
Array.Copy(copy.TagsBlobBytes, bytes, copy.TagsBlobBytes.Length);
TagsBlobBytes = bytes;
}
else
{
TagsBlobBytes = new byte[0];
}
SetDefaults(this);
}
public DigitalOutputSetting(IDataRecord reader)//, bool pre20 = false)
{
DatabaseId = Convert.ToInt32(reader["Id"]);
Broken = Convert.ToBoolean(reader[DbOperations.DigitalOutputSettings.Fields.Broken.ToString()]);
DoNotUse = Convert.ToBoolean(reader[DbOperations.DigitalOutputSettings.Fields.DoNotUse.ToString()]);
Bridge = SensorConstants.BridgeType.TOMDigital;
try
{
Version = Convert.ToInt32(reader[DbOperations.DigitalOutputSettings.Fields.Version.ToString()]);
DigitalOutputMode =
(DigitalOutputModes)Convert.ToInt16(
reader[DbOperations.DigitalOutputSettings.Fields.OutputMode.ToString()]);
//_localOnly = Convert.ToBoolean(reader[DbOperations.DigitalOutputSettings.Fields.LocalOnly.ToString()]);
DigitalOutputLimitDuration =
Convert.ToBoolean(reader[DbOperations.DigitalOutputSettings.Fields.LimitDuration.ToString()]);
LastUpdatedBy =
Convert.ToString(reader[DbOperations.DigitalOutputSettings.Fields.LastModifiedBy.ToString()]);
LastModified =
Convert.ToDateTime(reader[DbOperations.DigitalOutputSettings.Fields.LastModified.ToString()]);
DigitalOutputDurationMS =
Convert.ToDouble(reader[DbOperations.DigitalOutputSettings.Fields.DurationMSFloat.ToString()]);
DigitalOutputDelayMS =
Convert.ToDouble(reader[DbOperations.DigitalOutputSettings.Fields.DelayMS.ToString()]);
ChannelDescription = Convert.ToString(reader["SerialNumber"]);
TagsBlobBytes = (byte[])reader[DbOperations.DigitalOutputSettings.Fields.UserTags.ToString()];
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
SetDefaults(this);
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
var digitalOut = new DigitalOutDbRecord(setting, setting.TagsBlobBytes);
var hr = DbOperations.SensorsDigitalOutUpdateInsert(digitalOut);
if (0 == hr) { setting.DatabaseId = digitalOut.DatabaseId; }
}
}
}

View File

@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SensorDB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SensorDB")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6536b7c0-aa8b-4e96-8bf2-c4480ac3633f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.06.0081")]
[assembly: AssemblyFileVersion("1.06.0081")]

View File

@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// an entry in the TOM Squib Fire Channels portion of the Start TOM Channel Information section of a TSF
/// an entry can contain
/// rack,module,chan,descrip,id,type,current,delay,durationON,duration,OhmLow,OhmHigh,ISOcode
/// TSF starts number with 1 and squibs are numbered as channels 1-4 on a tom
/// </summary>
public class TSFSquibFireEntry : TSFChannel
{
private int _rack;
public int Rack { get { return _rack; } set { _rack = value; } }
private int _module;
public int Module { get { return _module; } set { _module = value; } }
private int _chan;
public int Chan { get { return _chan; } set { _chan = value; } }
private string _desc;
public string Description { get { return _desc; } set { _desc = value; } }
private string _id;
public string Id
{
get { return _id; }
set
{
if (value.ToLower() == "none") { value = ""; }
_id = value;
}
}
private int _type;
public int Type { get { return _type; } set { _type = value; } }
private double _current;
public double Current { get { return _current; } set { _current = value; } }
private double _delay;
public double Delay { get { return _delay; } set { _delay = value; } }
private bool _durationOn;
public bool DurationOn { get { return _durationOn; } set { _durationOn = value; } }
private double _duration;
public double Duration { get { return _duration; } set { _duration = value; } }
private double _ohmLow;
public double OhmLow { get { return _ohmLow; } set { _ohmLow = value; } }
private double _ohmHigh;
public double OhmHigh { get { return _ohmHigh; } set { _ohmHigh = value; } }
private string _isocode;
public string ISOcode { get { return _isocode; } set { _isocode = value; } }
public enum Fields
{
rack, //%i
module, //%i
chan, //%i
descrip,//%s
id, //%s
type, //%i
current,// %f
delay, //%f
durationON, //%i
duration, //%f
OhmLow, //%f
OhmHigh, //%f
ISOcode//%s
}
}
}

View File

@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// an entry in the DIM Begin section of a TSF
/// each entry can contain
/// Datachan,Rack,Module,Chan,Description,Serial No,Mode,Inverted,EID,Filename,Scale,Filter Mode,Filter Threshold,ISO CODE,Cable Test
/// we currently do nothing with these entries in DataPRO...
/// </summary>
public class TSFDIMEntry : TSFChannel
{
private int _dataChan;
public int DataChan { get { return _dataChan; } set { _dataChan = value; } }
private int _rack;
public int Rack { get { return _rack; } set { _rack = value; } }
private int _module;
public int Module { get { return _module; } set { _module = value; } }
private int _chan;
public int Chan { get { return _chan; } set { _chan = value; } }
private string _description;
public string Description { get { return Description; } set { _description = value; } }
private string _serialNumber;
public string SerialNumber { get { return _serialNumber; } set { _serialNumber = value; } }
private string _mode;
public string Mode { get { return _mode; } set { _mode = value; } }
private int _inverted;
public int Inverted { get { return _inverted; } set { _inverted = value; } }
private string _eid;
public string EID { get { return _eid; } set { _eid = value; } }
private string _filename;
public string FileName { get { return _filename; } set { _filename = value; } }
private double _scale;
public double Scale { get { return _scale; } set { _scale = value; } }
private int _filterMode;
public int FilterMode { get { return _filterMode; } set { _filterMode = value; } }
private double _filterThreshold;
public double FilterThreshold { get { return _filterThreshold; } set { _filterThreshold = value; } }
private string _isocode;
public string ISOCode { get { return _isocode; } set { _isocode = value; } }
private int _cableTest;
public int CableTest { get { return _cableTest; } set { _cableTest = value; } }
public enum Fields
{
Datachan,//i
Rack,//i
Module,//i
Chan, //i
Description,//s
SerialNo, //s
Mode, //i?
Inverted, //i
EID, //s
Filename, //s
Scale, //f
FilterMode, //i
FilterThreshold,//f
ISOCODE,//s
CableTest//i
}
}
}

View File

@@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// handles the rack information section of the TSF
/// </summary>
public class TSFRackInformationSection
{
private const string START_SECTION_HEADER = "---- Start Rack Information ----";
private const string COLUMN_HEADER = "Rack";
private const string END_SECTION_HEADER = "---- End Rack Information ----";
private List<TSFRackDescription> _racks = new List<TSFRackDescription>();
public TSFRackDescription[] Racks
{
get { return _racks.ToArray(); }
set { _racks = new List<TSFRackDescription>(value); }
}
public TSFRackInformationSection() { }
/// <summary>
/// reads the section from the TSF assumes currentline is the start of the section
/// </summary>
/// <param name="lines"></param>
/// <param name="currentLine"></param>
/// <param name="errors"></param>
/// <param name="tsf"></param>
/// <param name="system"></param>
public void ReadFrom(List<string> lines, ref int currentLine, ref List<ReadTSFError> errors, TSFFile tsf, TSFSystemDescription system)
{
var invariant = System.Globalization.CultureInfo.InvariantCulture;
_racks.Clear();
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string startSection = lines[currentLine++];
if (startSection != START_SECTION_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.RACKINFORMATIONSECTION_INVALIDHEADER, currentLine, startSection));
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string columnHeader = lines[currentLine++];
if (false == columnHeader.Contains(COLUMN_HEADER))
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.RACKINFORMATIONSECTION_INVALIDCOLUMNHEADER, currentLine, columnHeader));
return;
}
bool done = false;
while (!done)
{
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string line = lines[currentLine++];
if (line != END_SECTION_HEADER)
{
string[] tokens = line.Split(new char[] { ',' });
if (tokens.Length < 1)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_SKIPPED_RACK_ENTRY_INCOMPLETE, currentLine));
continue;
}
int rack;
try { rack = int.Parse(tokens[0], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_RACK_ENTRY_INVALID_RACK_VALUE, currentLine, tokens[0]));
continue;
}
/*
string rackIsoObject = tokens[1];
string rackIDummy = tokens[2];
int iRackIsoPosition;
try { iRackIsoPosition = int.Parse(tokens[3], invariant); }
catch (System.Exception)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_RACK_ENTRY_INVALID_ISO_POSITION, currentLine, tokens[3]));
continue;
}
int iRackG5DockingStation = int.Parse(tokens[4]);
int iRackISOModuleNum = int.Parse(tokens[5]);
* */
if (line.Contains(",B,") && tsf.GetICrashBarrierType() == TSFFile.ICRASH_BARRIER_TYPE.ITROLLEY_BARRIER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.RACK_ENTRY_IWALLTEST_ITROLLEY_FUNCTIONALITY, currentLine));
continue;
}
if (line.Contains(",T,") && tsf.GetICrashBarrierType() == TSFFile.ICRASH_BARRIER_TYPE.IWALL_BARRIER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.RACK_ENTRY_ITROLLEYTEST_IWALL_FUNCTIONALITY, currentLine));
continue;
}
TSFRackDescription r = null;//system.HWRack[rack];
foreach (var curRack in system.HWRack)
{
if (curRack.Number == rack)
{
r = curRack;
break;
}
}
if (null == r)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.RACK_ENTRY_INVALID_RACK_INDEX, currentLine));
continue;
}
if (r.HWSerialNumber == TSFFile.EMPTY_RACK_SN)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.RACK_ENTRY_INVALID_EMPTYRACK, currentLine));
continue;
}
_racks.Add(new TSFRackDescription(r));
}
else
{
done = true;
}
}
}
}
}

View File

@@ -0,0 +1,63 @@
using DTS.Common.Classes.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Slice.Users.UserSettings;
using DTS.Common.Constant;
namespace DTS.SensorDB
{
public sealed class CanSettingDefaults : Common.Base.BasePropertyChanged, ICanSettingDefaults
{
private readonly ISensorData _defaultCan;
public bool IsFD { get => _defaultCan.CanIsFD; set => _defaultCan.CanIsFD = value; }
public int ArbBaseBitrate { get => _defaultCan.CanArbBaseBitrate; set => _defaultCan.CanArbBaseBitrate = value; }
public int ArbBaseSJW { get => _defaultCan.CanArbBaseSJW; set => _defaultCan.CanArbBaseSJW = value; }
public int DataBitrate { get => _defaultCan.CanDataBitrate; set => _defaultCan.CanDataBitrate = value; }
public int DataSJW { get => _defaultCan.CanDataSJW; set => _defaultCan.CanDataSJW = value; }
public string FileType { get => _defaultCan.CanFileType; set => _defaultCan.CanFileType = value; }
public bool Validate()
{
return true;
}
public static void CommitChange(CanSettingDefaults settingDefaults, int userID)
{
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANIsFD, settingDefaults.IsFD);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANArbBaseBitrate, settingDefaults.ArbBaseBitrate);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANArbBaseSJW, settingDefaults.ArbBaseSJW);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANDataBitrate, settingDefaults.DataBitrate);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANDataSJW, settingDefaults.DataSJW);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANFileType, settingDefaults.FileType);
}
public static CanSettingDefaults GetCanSettingsDefault(int userID)
{
var sd = new SensorData()
{
CanIsFD = TestSetupDefaults.GetUserSettingValueBool(userID, PropertyEnums.PropertyIds.DefaultCANIsFD),
CanArbBaseBitrate = TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultCANArbBaseBitrate),
CanArbBaseSJW = TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultCANArbBaseSJW),
CanDataBitrate = TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultCANDataBitrate),
CanDataSJW = TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultCANDataSJW),
CanFileType = TestSetupDefaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultCANFileType)
};
return new CanSettingDefaults(sd);
}
private CanSettingDefaults(ISensorData defaultCan)
{
_defaultCan = defaultCan;
}
public static void RestoreDefaults(ICanSettingDefaults sensorDefaults)
{
sensorDefaults.IsFD = EmbeddedSensors.CANISFD_DEFAULT;
sensorDefaults.ArbBaseBitrate = EmbeddedSensors.CANFD_ARB_BASE_BITRATE_DEFAULT;
sensorDefaults.ArbBaseSJW = EmbeddedSensors.CANFD_1000000_ARB_BASE_SJW_MAX;
sensorDefaults.DataBitrate = EmbeddedSensors.DATA_BITRATE_DEFAULT;
sensorDefaults.DataSJW = EmbeddedSensors.DATA_SJW_DEFAULT;
sensorDefaults.FileType = EmbeddedSensors.FILETYPE_DEFAULT;
}
}
}

View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// handles the sampling information section of the TSF
/// can contain rate(Hz),pretrigtime(sec),posttrigtime(sec),AdjAAfilter(Hz),postcaltime(sec)
/// </summary>
public class TSFSamplingInformationSection
{
private const string START_SECTION_HEADER = "---- Start Sampling Information ----";
private const string COLUMN_HEADER = "rate(Hz),pretrigtime(sec),posttrigtime(sec),AdjAAfilter(Hz),postcaltime(sec)";
private const string END_SECTION_HEADER = "---- End Sampling Information ----";
private double _sampleRateHz;
public double SampleRateHz { get { return _sampleRateHz; } set { _sampleRateHz = value; } }
private double _preTriggerSeconds;
/// <summary>
/// pre trigger seconds (always positive)
/// </summary>
public double PreTriggerSeconds { get { return _preTriggerSeconds; } set { _preTriggerSeconds = value; } }
private double _postTriggerSeconds;
/// <summary>
/// post trigger seconds (always positive)
/// </summary>
public double PostTriggerSeconds { get { return _postTriggerSeconds; } set { _postTriggerSeconds = value; } }
private double _aaf;
public double AAF { get { return _aaf; } set { _aaf = value; } }
private double _postCalTimeSeconds;
public double PostCalTimeSeconds { get { return _postCalTimeSeconds; } set { _postCalTimeSeconds = value; } }
public TSFSamplingInformationSection(List<string> lines, ref int currentLine)
{
if (currentLine == lines.Count) { throw new System.IO.EndOfStreamException(); }
string startSection = lines[currentLine++];
if (startSection != START_SECTION_HEADER) { throw new System.IO.InvalidDataException(startSection); }
if (currentLine == lines.Count) { throw new System.IO.EndOfStreamException(); }
string columnHeader = lines[currentLine++];
if (columnHeader != COLUMN_HEADER) { throw new System.IO.InvalidDataException(columnHeader); }
// READ IN SAMPLING VALUES
if (currentLine == lines.Count) { throw new System.IO.EndOfStreamException(); }
string[] tokens = lines[currentLine++].Split(new string[] { "," }, StringSplitOptions.None);
if (tokens.Length < 5) { throw new System.IO.InvalidDataException(lines[currentLine - 1]); }
try { SampleRateHz = double.Parse(tokens[0], System.Globalization.CultureInfo.InvariantCulture); }
catch (System.Exception) { throw new System.IO.InvalidDataException(tokens[0]); }
try { PreTriggerSeconds = double.Parse(tokens[1], System.Globalization.CultureInfo.InvariantCulture); }
catch (System.Exception) { throw new System.IO.InvalidDataException(tokens[1]); }
try { PostTriggerSeconds = double.Parse(tokens[2], System.Globalization.CultureInfo.InvariantCulture); }
catch (System.Exception) { throw new System.IO.InvalidDataException(tokens[2]); }
try { AAF = double.Parse(tokens[3], System.Globalization.CultureInfo.InvariantCulture); }
catch (System.Exception) { throw new System.IO.InvalidDataException(tokens[3]); }
// IF PRETRIGTIME IS >0 THEN THIS IS PRE VER. 6.4A AND NEEDS TO BE CONVERTED TO A NEGATIVE NUMBER
PreTriggerSeconds = System.Math.Abs(PreTriggerSeconds);
PostTriggerSeconds = System.Math.Abs(PostTriggerSeconds);
if (currentLine == lines.Count) { throw new System.IO.EndOfStreamException(); }
string endSection = lines[currentLine++];
if (endSection != END_SECTION_HEADER)
{
throw new System.IO.InvalidDataException(endSection);
}
}
}
}

View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// helper class for RS232 section of INI file
/// </summary>
public class TDCINIRS232Info
{
/// <summary>
/// Communication port
/// </summary>
public int ComPortNumber { get; set; }
/// <summary>
/// Max speed of com port
/// </summary>
public int MaxComSpeed { get; set; }
/// <summary>
/// max number of ports
/// </summary>
public int MaxComPorts { get; set; }
public TDCINIRS232Info() { }
/// <summary>
/// read section from a line
/// returns true if read successfully, false if there were errors
/// </summary>
/// <param name="line"></param>
/// <param name="errors"></param>
/// <returns></returns>
public bool ReadFrom(string line, ref List<TDCINIError> errors)
{
string[] tokens = line.Split(new char[] { ',' });
if (3 != tokens.Length)
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_COMINFO_INVALID, line));
return false;
}
int i;
if (!int.TryParse(tokens[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out i))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_COMINFO_INVALID, line));
return false;
}
else { ComPortNumber = i; }
if (!int.TryParse(tokens[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out i))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_COMINFO_INVALID, line));
return false;
}
else { MaxComSpeed = i; }
if (!int.TryParse(tokens[2], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out i))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_COMINFO_INVALID, line));
return false;
}
else { MaxComPorts = i; }
return true;
}
}
}

View File

@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// stolen from HLAPI in the hope of bringing in some of the HLAPI code, however is very, very sparsely used
/// we may want to remove these HLAPI derived classes soon
/// </summary>
public class TSFModuleDescription
{
private int _version;
public int Version { get { return _version; } set { _version = value; } }
/// <summary>
/// See HLAPI_MODULE_TYPE_
/// </summary>
private int _type;
public int Type { get { return _type; } set { _type = value; } }
private TSFRackDescription _parent;
public TSFRackDescription Parent { get { return _parent; } set { _parent = value; } }
private int _source;
public int Source { get { return _source; } set { _source = value; } }
private int _slot;
public int Slot { get { return _slot; } set { _slot = value; } }
private ulong _crc32;
public ulong CRC32 { get { return _crc32; } set { _crc32 = value; } }
private bool _hardwareInfoValid;
public bool HardwareInfoValid { get { return _hardwareInfoValid; } set { _hardwareInfoValid = value; } }
private string _hwSerialNumber;
public string HWSerialNumber { get { return _hwSerialNumber; } set { _hwSerialNumber = value; } }
/// <summary>
/// See HLAPI_MODULE_TOM_TIGGER_
/// </summary>
private int _hwTOMTriggerType;
public int HWTOMTriggerType { get { return _hwTOMTriggerType; } set { _hwTOMTriggerType = value; } }
private int _hwRackPosition;
public int HWRackPosition { get { return _hwRackPosition; } set { _hwRackPosition = value; } }
private int _hwChannelCount;
public int HWChannelCount { get { return _hwChannelCount; } set { _hwChannelCount = value; } }
private List<TSFChannelDescription> _hwChannelList = new List<TSFChannelDescription>();
public TSFChannelDescription[] HWChannelList { get { return _hwChannelList.ToArray(); } set { _hwChannelList = new List<TSFChannelDescription>(value); } }
//The following values are valid after TestTrigger and DownloadData
private bool _downloadDescriptionValid;
public bool DownloadDescriptionValid { get { return _downloadDescriptionValid; } set { _downloadDescriptionValid = value; } }
private bool _downloadTriggerDetected;
public bool DownloadTriggerDetected { get { return _downloadTriggerDetected; } set { _downloadTriggerDetected = value; } }
//The following fields are used for the download process
private char _downloadDataFlag;
public char DownloadDataFlag { get { return _downloadDataFlag; } set { _downloadDataFlag = value; } }
private double _downloadBeginSeconds;
public double DownloadBeginSeconds { get { return _downloadBeginSeconds; } set { _downloadBeginSeconds = value; } }
private double _downloadEndSeconds;
public double DownloadEndSeconds { get { return _downloadEndSeconds; } set { _downloadEndSeconds = value; } }
private double _moduleBatteryVolts;
public double ModuleBatteryVolts { get { return _moduleBatteryVolts; } set { _moduleBatteryVolts = value; } }
public TSFModuleDescription() { }
public TSFModuleDescription(TSFModuleDescription copy, TSFRackDescription rack)
{
_crc32 = copy._crc32;
_downloadBeginSeconds = copy._downloadBeginSeconds;
_downloadDataFlag = copy._downloadDataFlag;
_downloadDescriptionValid = copy._downloadDescriptionValid;
_downloadEndSeconds = copy._downloadEndSeconds;
_downloadTriggerDetected = copy._downloadTriggerDetected;
_hardwareInfoValid = copy._hardwareInfoValid;
_hwChannelCount = copy._hwChannelCount;
_hwChannelList = new List<TSFChannelDescription>();
foreach (var ch in copy._hwChannelList) { _hwChannelList.Add(new TSFChannelDescription(ch, this)); }
_hwRackPosition = copy._hwRackPosition;
_hwSerialNumber = copy._hwSerialNumber;
_hwTOMTriggerType = copy._hwTOMTriggerType;
_moduleBatteryVolts = copy._moduleBatteryVolts;
_parent = rack;
_slot = copy._slot;
_source = copy._source;
_type = copy._type;
_version = copy._version;
}
}
}

View File

@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// stolen from HLAPI
/// used sparsely ... do not expect most fields to be filled out as we use very few fields from it ...
/// </summary>
public class TSFSystemDescription
{
private int _version;
public int Version { get { return _version; } set { _version = value; } }
private int _systemState;
public int SystemState { get { return _systemState; } set { _systemState = value; } }
private int _source;
public int Source { get { return _source; } set { _source = value; } }
private ulong _crc32;
public ulong CRC32 { get { return _crc32; } set { _crc32 = value; } }
// The following fields describe the static hardware system
/// <summary>
/// Are the HW* variables valid?
/// </summary>
private bool _hardwareDescriptionValid = false;
public bool HardwareDescriptionValid { get { return _hardwareDescriptionValid; } set { _hardwareDescriptionValid = value; } }
/// <summary>
/// How many SIM's in the whole system?
/// </summary>
private int _hwSIMCount;
public int HWSIMCount { get { return _hwSIMCount; } set { _hwSIMCount = value; } }
/// <summary>
/// How many TOM's in the whole system?
/// </summary>
private int _hwTOMCount;
public int HWTOMCount { get { return _hwTOMCount; } set { _hwTOMCount = value; } }
/// <summary>
/// How many G5's in the whole system?
/// </summary>
private int _hwG5Count;
public int HWG5Count { get { return _hwG5Count; } set { _hwG5Count = value; } }
/// <summary>
/// How many analog channels in the whole system?
/// </summary>
private int _hwAnalogChannelCount;
public int HWAnalogChannelCount { get { return _hwAnalogChannelCount; } set { _hwAnalogChannelCount = value; } }
/// <summary>
/// How many squib channels in the whole system?
/// </summary>
private int _hwSquibChannelCount;
public int HWSquibChannelCount { get { return _hwSquibChannelCount; } set { _hwSquibChannelCount = value; } }
/// <summary>
/// How many digital output channels in the whole system?
/// </summary>
private int _hwDigitalOutputChannelCount;
public int HWDigitalOutputChannelCount { get { return _hwDigitalOutputChannelCount; } set { _hwDigitalOutputChannelCount = value; } }
/// <summary>
/// How many digital input channels in the whole system?
/// </summary>
private int _hwDigitalInputChannelCount;
public int HWDigitalInputChannelCount { get { return _hwDigitalInputChannelCount; } set { _hwDigitalInputChannelCount = value; } }
/// <summary>
/// Number of elements in HWRack array?
/// </summary>
public int HWRackCount { get { return HWRack.Length; } }
/// <summary>
/// List of racks and their children
/// </summary>
List<TSFRackDescription> _hwRack = new List<TSFRackDescription>();
public TSFRackDescription[] HWRack { get { return _hwRack.ToArray(); } set { _hwRack = new List<TSFRackDescription>(value); } }
//The following fields describe the test system parameters
private bool _testDescriptionValid = false;
public bool TestDescriptionValid { get { return _testDescriptionValid; } set { _testDescriptionValid = value; } }
private double _testSampleRate;
public double TestSampleRate { get { return _testSampleRate; } set { _testSampleRate = value; } }
private double _testPreTriggerSeconds;
public double TestPreTriggerSeconds { get { return _testPreTriggerSeconds; } set { _testPreTriggerSeconds = value; } }
private double _testPostTriggerSeconds;
public double TestPostTriggerSeconds { get { return _testPostTriggerSeconds; } set { _testPostTriggerSeconds = value; } }
private string _testConfigurationId;
public string TestConfigurationId { get { return _testConfigurationId; } set { _testConfigurationId = value; } }
private char _testArmMode;
public char TestArmMode { get { return _testArmMode; } set { _testArmMode = value; } }
private double _testAdjustibleAAFilter;
public double TestAdjustibleAAFilter { get { return _testAdjustibleAAFilter; } set { _testAdjustibleAAFilter = value; } }
private double _testCapacitorDischargeFrequency;
public double TestCapacitorDischargeFrequency { get { return _testCapacitorDischargeFrequency; } set { _testCapacitorDischargeFrequency = value; } }
private DateTime _testModifiedDateTime;
public DateTime TestModifiedDateTime { get { return _testModifiedDateTime; } set { _testModifiedDateTime = value; } }
private double _testTZeroOffset = 0D;
public double TestTZeroOffset { get { return _testTZeroOffset; } set { _testTZeroOffset = value; } }
private int _testLTOffset = 0;
public int TestLTOffset { get { return _testLTOffset; } set { _testLTOffset = value; } }
//The following fields describe the current state of the system
private bool _bSystemInfoValid = false;
public bool SystemInfoValid { get { return _bSystemInfoValid; } set { _bSystemInfoValid = value; } }
private int _sysArmStatus;
public int SysArmStatus { get { return _sysArmStatus; } set { _sysArmStatus = value; } }
private bool _sysLowPowerDetected;
public bool SysLowPowerDetected { get { return _sysLowPowerDetected; } set { _sysLowPowerDetected = value; } }
private bool _sysTriggerFaultDetected;
public bool SysTriggerFaultDetected { get { return _sysTriggerFaultDetected; } set { _sysTriggerFaultDetected = value; } }
private bool _sysStartRecordDetected;
public bool SysStartRecordDected { get { return _sysStartRecordDetected; } set { _sysStartRecordDetected = value; } }
}
}

View File

@@ -0,0 +1,109 @@
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Settings;
using DTS.Slice.Users.UserSettings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DTS.Common.Classes.Sensors;
using DTS.Common.Storage;
namespace DTS.SensorDB
{
public class StreamOutputSettingDefaults : DTS.Common.Base.BasePropertyChanged, IStreamOutputSettingDefaults
{
private ISensorData _defaultStreamOutput;
private bool _useAdvancedUDPStreamProfiles;
public UDPStreamProfile Profile { get => _defaultStreamOutput.StreamOutUDPProfile; set => _defaultStreamOutput.StreamOutUDPProfile = value; }
public bool UseAdvancedUDPStreamProfiles
{
get => _useAdvancedUDPStreamProfiles;
set
{
SetProperty(ref _useAdvancedUDPStreamProfiles, value, "UseAdvancedUDPStreamProfiles");
OnPropertyChanged("AvailableStreamOutUDPProfiles");
if (!_useAdvancedUDPStreamProfiles && !AvailableStreamOutUDPProfiles.Contains(Profile))
{
//turned off advanced & current selection not in basic. set to first or default
Profile = AvailableStreamOutUDPProfiles.FirstOrDefault();
OnPropertyChanged("Profile");
}
}
}
public UDPStreamProfile[] AvailableStreamOutUDPProfiles => StreamOutputRecord.AvailableUDPStreamProfiles(DbOperations.GetConnectionDbVersion(), UseAdvancedUDPStreamProfiles);
public string UDPAddress { get => _defaultStreamOutput.StreamOutUDPAddress; set => _defaultStreamOutput.StreamOutUDPAddress = value; }
public ushort TimeChannelId { get => _defaultStreamOutput.StreamOutUDPTimeChannelId; set => _defaultStreamOutput.StreamOutUDPTimeChannelId = value; }
public ushort DataChannelId { get => _defaultStreamOutput.StreamOutUDPDataChannelId; set => _defaultStreamOutput.StreamOutUDPDataChannelId = value; }
public string TmNSConfig { get => _defaultStreamOutput.StreamOutUDPTmNSConfig; set => _defaultStreamOutput.StreamOutUDPTmNSConfig = value; }
public ushort IRIGTimeDataPacketIntervalMs { get => _defaultStreamOutput.StreamOutIRIGTimeDataPacketIntervalMs; set => _defaultStreamOutput.StreamOutIRIGTimeDataPacketIntervalMs = value; }
public bool Validate()
{
if (!UDPAddress.ToLower().StartsWith("udp") || !Uri.IsWellFormedUriString(UDPAddress, UriKind.Absolute))
{
return false;
}
if (!Common.Utils.Utils.IsTmNSString(TmNSConfig))
{
return false;
}
return true;
}
public static void CommitChange(StreamOutputSettingDefaults settingDefaults, int userID)
{
Defaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUDPStreamProfile, settingDefaults.Profile);
Defaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUDPStreamAddress, settingDefaults.UDPAddress);
Defaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUDPStreamTimeChannelId, settingDefaults.TimeChannelId);
Defaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUDPStreamDataChannelId, settingDefaults.DataChannelId);
Defaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUDPStreamTmNSConfig, settingDefaults.TmNSConfig);
Defaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultIRIGTimeDataPacketIntervalMs, settingDefaults.IRIGTimeDataPacketIntervalMs);
Defaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUseAdvancedUDPStreamProfiles, settingDefaults.UseAdvancedUDPStreamProfiles);
}
public static StreamOutputSettingDefaults GetStreamOutputSettingsDefault(int userID)
{
var sd = new SensorData()
{
StreamOutUDPProfile = (UDPStreamProfile)Enum.Parse(typeof(UDPStreamProfile), Defaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultUDPStreamProfile)),
StreamOutUDPAddress = Defaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultUDPStreamAddress),
StreamOutUDPTimeChannelId = (ushort)Defaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultUDPStreamTimeChannelId),
StreamOutUDPDataChannelId = (ushort)Defaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultUDPStreamDataChannelId),
StreamOutUDPTmNSConfig = Defaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultUDPStreamTmNSConfig),
StreamOutIRIGTimeDataPacketIntervalMs = (ushort)Defaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultIRIGTimeDataPacketIntervalMs),
StreamOutTMATSIntervalMs = StreamOutputRecord.DEFAULT_TMATS_INTERVAL_MS
};
var useAdvancedUDPStreamProfiles = Defaults.GetUserSettingValueBool(userID, PropertyEnums.PropertyIds.DefaultUseAdvancedUDPStreamProfiles);
return new StreamOutputSettingDefaults(sd, useAdvancedUDPStreamProfiles);
}
public static StreamOutputSettingDefaults GetStreamOutputSettingsDefault(string user)
{
var sd = SensorsCollection.SensorsList.GetSensorBySerialNumber(SensorConstants.TEST_SPECIFIC_STREAM_OUT_SERIAL);
return new StreamOutputSettingDefaults(sd, false);
}
private StreamOutputSettingDefaults(SensorData sd, bool useAdvancedUDPStreamProfiles)
{
_defaultStreamOutput = sd;
UseAdvancedUDPStreamProfiles = useAdvancedUDPStreamProfiles;
}
public static void RestoreDefaults(IStreamOutputSettingDefaults sensorDefaults)
{
sensorDefaults.DataChannelId = StreamOutputRecord.DEFAULT_UDP_DATA_CHANNEL_ID;
sensorDefaults.IRIGTimeDataPacketIntervalMs = StreamOutputRecord.DEFAULT_IRIG_TIME_DATA_PACKET_INTERVAL_MS;
sensorDefaults.Profile = StreamOutputRecord.DEFAULT_UDP_PROFILE;
sensorDefaults.TimeChannelId = StreamOutputRecord.DEFAULT_UDP_TIME_CHANNEL_ID;
sensorDefaults.TmNSConfig = StreamOutputRecord.DEFAULT_UDPTMNS_CONFIG;
sensorDefaults.UDPAddress = StreamOutputRecord.DEFAULT_UDP_ADDRESS;
}
}
}

View File

@@ -0,0 +1,133 @@
using System;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
namespace DTS.SensorDB
{
public class SquibSetting : SensorData
{
public string SquibDescription
{
get => SerialNumber;
set
{
SerialNumber = value;
OnPropertyChanged("SquibDescription");
}
}
private bool _bypassCurrentFilter;
public new bool BypassCurrentFilter
{
get => _bypassCurrentFilter;
set => SetProperty(ref _bypassCurrentFilter, value, "BypassCurrentFilter");
}
private bool _bypassVoltageFilter;
public new bool BypassVoltageFilter
{
get => _bypassVoltageFilter;
set => SetProperty(ref _bypassVoltageFilter, value, "BypassVoltageFilter");
}
public string ArticleId
{
get => EID;
set
{
EID = value;
OnPropertyChanged("ArticleId");
}
}
public SquibSetting()
{
SetDefaults(this);
}
public SquibSetting(SquibSetting copy)
: base(copy)
{
SetDefaults(this);
}
public static void SetDefaults(SensorData sd)
{
sd.AxisNumber = 0;
sd.Capacity = 5;
sd.NumberOfAxes = 1;
sd.Manufacturer = "Generic";
sd.Model = "Squib Setting";
sd.Shunt = ShuntMode.None;
sd.CheckOffset = false;
sd.BridgeResistance = -1;
sd.MeasureNoise = false;
sd.MeasureExcitation = false;
sd.Bridge = SensorConstants.BridgeType.SQUIB;
sd.SupportedExcitation = new[]
{ExcitationVoltageOptions.ExcitationVoltageOption.Volt5};
sd.DisplayUnit = "V";
sd.Comment = string.IsNullOrWhiteSpace(sd.UserValue1) ? sd.SerialNumber : sd.UserValue1;
}
public SquibSetting(ISquibDbRecord record)
{
try
{
SetDefaults(this);
DatabaseId = record.Id;
ISOChannelName = record.IsoChannelName;
UserCode = record.UserCode;
UserChannelName = record.UserChannelName;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
Version = record.Version;
SquibToleranceLow = record.SquibToleranceLow;
SquibToleranceHigh = record.SquibToleranceHigh;
SquibOutputCurrent = record.SquibOutputCurrent;
SquibDescription = record.SerialNumber;
SquibMeasurementType = record.MeasurementType;
LimitSquibFireDuration = record.LimitDuration;
DefineDelayInTest = record.DefineDelayInTest;
ModifiedBy = record.LastModifiedBy;
LastModified = record.LastModified;
ISOCode = record.IsoCode;
SquibFireMode = record.FireMode;
SquibFireDurationMS = record.DurationMs;
SquibFireDelayMS = record.DelayMs;
BypassVoltageFilter = record.BypassVoltageFilter;
BypassCurrentFilter = record.BypassCurrentFilter;
ArticleId = record.ArticleId;
UserValue1 = record.UserValue1;
Comment = UserValue1;
UserValue2 = record.UserValue2;
UserValue3 = record.UserValue3;
TagsBlobBytes = record.UserTags;
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
if (string.IsNullOrWhiteSpace(Comment))
{
Comment = SerialNumber;
}
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
var record = new SquibDbRecord(setting, setting.DefineDelayInTest, setting.TagsBlobBytes);
var hr = DbOperations.SensorsSquibUpdateInsert(record);
if (0 == hr) { setting.DatabaseId = record.Id; }
}
}
}

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- This is a msbuild wrapper to facilitate running the NUnit tests -->
<!-- Set the primary target as the "test" -->
<Project DefaultTargets="Test" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- Load nunit support -->
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
<!-- Wrap the existing solution -->
<Target Name="Build">
<Message Text="Starting to Build"/>
<MSBuild Projects="SensorDB.sln" Properties="Configuration=Release" Targets="Rebuild"/>
</Target>
<!-- Run Nunit. This runs second because of DependsOnTargets -->
<Target Name="Test" DependsOnTargets="Build">
<Message Text="Starting to Test"/>
<NUnit Assemblies="SensorDBNunit\bin\release\sensordb nunit.dll"
ContinueOnError="true"
ToolPath="C:\Program Files\NUnit 2.4.8\bin"
OutputXmlFile="NUnitResults.xml" />
</Target>
</Project>

View File

@@ -0,0 +1,415 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTS.Common.Utilities.Logging;
namespace DTS.SensorDB
{
public class MeasurementUnit
{
private string _mainDisplayUnit;
public string MainDisplayUnit
{
get { return _mainDisplayUnit; }
set { _mainDisplayUnit = value; }
}
private string[] _alternateDisplayUnits;
public string[] AlternateDisplayUnits
{
get { return _alternateDisplayUnits; }
set { _alternateDisplayUnits = value; }
}
private string _dimension = "00";
public string Dimension
{
get { return _dimension; }
set { _dimension = value; }
}
public MeasurementUnit(string mainUnit, string[] alternateUnits, MeasurementUnit.UnitConversion[] conversions, string dimension)
{
MainDisplayUnit = mainUnit;
AlternateDisplayUnits = alternateUnits;
UnitConversions = conversions;
Dimension = dimension;
}
public MeasurementUnit(System.Xml.XmlElement node)
{
foreach (var childnode in node.ChildNodes)
{
System.Xml.XmlElement elem = childnode as System.Xml.XmlElement;
if (null == elem) { continue; }
try
{
switch (elem.Name)
{
case "MainDisplayUnit":
MainDisplayUnit = elem.InnerText;
break;
case "AlternateDisplayUnits":
{
var nodes = elem.GetElementsByTagName("String");
List<string> aunits = new List<string>();
foreach (var node2 in nodes)
{
System.Xml.XmlElement element = node2 as System.Xml.XmlElement;
if (null == element) { continue; }
try
{
aunits.Add(element.InnerText);
}
catch (System.Exception) { }
}
AlternateDisplayUnits = aunits.ToArray();
}
break;
case "Dimension":
{
Dimension = elem.InnerText;
}
break;
case "UnitConversions":
{
var nodes = elem.GetElementsByTagName("UnitConversion");
foreach (var node2 in nodes)
{
System.Xml.XmlElement element = node2 as System.Xml.XmlElement;
if (null == element) { continue; }
try
{
_unitConversions.Add(new UnitConversion(element));
}
catch (System.Exception) { }
}
}
break;
default:
System.Diagnostics.Trace.WriteLine("didn't handle " + elem.Name);
break;
}
}
catch (System.Exception ex)
{
APILogger.Log("Failed to parse xml", ex, elem.Name, elem.Value);
}
}
}
public bool UnitMatches(string unit)
{
unit = unit.Trim().ToLower();
if (MainDisplayUnit.ToLower() == unit) { return true; }
foreach (string aunit in AlternateDisplayUnits)
{
if (aunit.ToLower() == unit) { return true; }
}
return false;
}
public double GetScalerConversion(string newUnit)
{
return 1D; //6194 disable display units for the short term
//if (UnitMatches(newUnit)) { return 1D; }
//foreach (var uc in UnitConversions)
//{
// if (uc.UnitMatches(newUnit)) { return uc.Scaler; }
//}
//throw new InvalidCastException(string.Format("No conversion available from {0} to {1}", newUnit, MainDisplayUnit));
}
public double GetScalerConversionFrom(string oldUnit)
{
return 1D; //6194 disable display units for the short term
//if (UnitMatches(oldUnit)) { return 1D; }
//foreach (var uc in UnitConversions)
//{
// if (uc.UnitMatches(oldUnit)) { return 1D / uc.Scaler; }
//}
//throw new InvalidCastException(string.Format("No conversion available from {0} to {1}", oldUnit, MainDisplayUnit));
}
private List<UnitConversion> _unitConversions = new List<UnitConversion>();
public UnitConversion[] UnitConversions
{
get
{
return _unitConversions.ToArray();
}
set
{
if (null == value)
{
return;
}
_unitConversions = new List<UnitConversion>(value);
}
}
public class UnitConversion
{
private string _unit;
public string Unit { get { return _unit; } set { _unit = value; } }
private double _scaler;
public double Scaler { get { return _scaler; } set { _scaler = value; } }
public bool UnitMatches(string unit)
{
return (Unit.ToLower() == unit.Trim().ToLower());
}
public void WriteToXML(System.Xml.XmlWriter writer)
{
writer.WriteStartElement("UnitConversion");
DTS.DASLib.Service.XMLHelper.PutString(writer, "Unit", Unit);
DTS.DASLib.Service.XMLHelper.PutDouble(writer, "Scaler", Scaler);
writer.WriteEndElement();
}
public UnitConversion(string unit, double scaler) { Unit = unit; Scaler = scaler; }
public UnitConversion(System.Xml.XmlElement node)
{
foreach (var childnode in node.ChildNodes)
{
System.Xml.XmlElement elem = childnode as System.Xml.XmlElement;
if (null == elem) { continue; }
try
{
switch (elem.Name)
{
case "Unit":
Unit = elem.InnerText;
break;
case "Scaler":
Scaler = double.Parse(elem.InnerText, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture);
break;
default:
System.Diagnostics.Trace.WriteLine("didn't handle " + elem.Name);
break;
}
}
catch (System.Exception ex)
{
APILogger.Log("Failed to parse xml", ex, elem.Name, elem.Value);
}
}
}
}
public void WriteToXML(System.Xml.XmlWriter writer)
{
writer.WriteStartElement("MeasurementUnit");
DTS.DASLib.Service.XMLHelper.PutString(writer, "MainDisplayUnit", MainDisplayUnit);
DTS.DASLib.Service.XMLHelper.PutString(writer, "Dimension", Dimension);
writer.WriteStartElement("AlternateDisplayUnits");
foreach (var unit in AlternateDisplayUnits)
{
writer.WriteStartElement("String");
writer.WriteValue(unit);
writer.WriteEndElement();
}
writer.WriteEndElement();
//DTS.DASLib.Service.XMLHelper.PutString(writer, "AlternateDisplayUnits", string.Join("×", AlternateDisplayUnits));
writer.WriteStartElement("UnitConversions");
foreach (var uc in UnitConversions) { uc.WriteToXML(writer); }
writer.WriteEndElement();
writer.WriteEndElement();
}
public override string ToString()
{
return MainDisplayUnit;
}
}
public class MeasurementUnitList
{
private static MeasurementUnitList _instance;
private static object MyLock = new object();
private Dictionary<string, MeasurementUnit> _units = new Dictionary<string, MeasurementUnit>();
private MeasurementUnit[] GetAllUnits() { return _units.Values.ToArray(); }
public static MeasurementUnit[] GetAllMeasurementUnits()
{
lock (MyLock)
{
if (null == _instance) { _instance = new MeasurementUnitList(); }
return _instance.GetAllUnits();
}
}
public static MeasurementUnit GetMeasurementUnit(string key)
{
lock (MyLock)
{
return new MeasurementUnit(key, null, null, null);
}
}
private MeasurementUnitList()
{
LoadAllMeasurementUnits();
}
public void SaveToXML()
{
StringBuilder sb = new StringBuilder();
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.OmitXmlDeclaration = false;
settings.Indent = true;
using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlTextWriter.Create(sb, settings))
{
xmlWriter.WriteStartDocument(true);
xmlWriter.WriteStartElement("MeasurementUnits");
var e1 = _units.GetEnumerator();
while (e1.MoveNext())
{
e1.Current.Value.WriteToXML(xmlWriter);
}
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
}
System.IO.File.WriteAllText(FILE_NAME, sb.ToString());
}
private void CreateDefaultMeasurementUnitsFile()
{
MeasurementUnit mu = new MeasurementUnit("g", new string[] { "g" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("m/sec^2", 9.80665D), new MeasurementUnit.UnitConversion("ft/s^2", 32.17405D)}, "AC");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("m/sec^2", new string[] { "m/sec^2", "m/s^2", "m/sec2", "m/s2" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("g", .101971621), new MeasurementUnit.UnitConversion("ft/s^2", 3.28084D),
new MeasurementUnit.UnitConversion("cm/s^2", 100D)}, "AC");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("deg", new string[] { "deg", "degree", "degrees", "°" }, new MeasurementUnit.UnitConversion[0], "AN");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("Nm", new string[] { "Nm", "N -m", "N-m" }, new MeasurementUnit.UnitConversion[0], "DC");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("mm", new string[] { "mm", "M-m", "M -m" }, new MeasurementUnit.UnitConversion[0], "DC");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("deg/sec", new string[] { "deg/sec", "degrees/sec", "d/sec", "deg/s" }, new MeasurementUnit.UnitConversion[0], "AA");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("kN", new string[] { "kn", "K-n", "k -n", "kilonewton" }, new MeasurementUnit.UnitConversion[]{
new MeasurementUnit.UnitConversion("N", 1000)
}, "FO");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("N", new string[] { "n", "newton" }, new MeasurementUnit.UnitConversion[]{
new MeasurementUnit.UnitConversion("kN", .001D)
}, "FO");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("ft/s^2", new string[] { "ft/s2", "ft/s^2", "ft/sec^2" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("cm/s^2", 30.48D), new MeasurementUnit.UnitConversion("m/sec^2", .3048D)}, "AC");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("cm/s^2", new string[] { "cm/s^2", "cm/s2", "cm/sec^2" }, new MeasurementUnit.UnitConversion[]{
new MeasurementUnit.UnitConversion("ft/s^2", .032808D), new MeasurementUnit.UnitConversion("m/sec^2", .01D)
}, "AC");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("Ampere", new string[] { "Amp", "Amper", "Amps" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("mAmp", 1000D)
}, "CU");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("mAmp", new string[] { "mAmp", "m Amp", "milliampere", "milliamp" }, new MeasurementUnit.UnitConversion[]{
new MeasurementUnit.UnitConversion("Ampere", .001D)}, "CU");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("A", new string[] { "Amp", "Ampere" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("mAmp", 1000)}, "CU");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("Hz", new string[] { "hertz", "cycle/sec", "cyc/s" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("kHz", .001D)}, "FR");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("kHz", new string[] { "kHertz", "kilohertz" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("Hz", 1000D)}, "FR");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("m", new string[] { "m", "Meter" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("mm", 100D)}, "DC");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("V", new string[] { "volt", "VO" }, new MeasurementUnit.UnitConversion[] {
new MeasurementUnit.UnitConversion("mV", 100D)}, "VO");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("mV", new string[] { "mv", "millivolt", "mVolt" }, new MeasurementUnit.UnitConversion[]{
new MeasurementUnit.UnitConversion("V", .001D)}, "VO");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("με", new string[] { "microstrain", "με", "micro strain" }, new MeasurementUnit.UnitConversion[0], "??");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("Pa", new string[] { "PA", "Pascal", "kg/m^2" }, new MeasurementUnit.UnitConversion[]{
new MeasurementUnit.UnitConversion("kPa", 1000D), new MeasurementUnit.UnitConversion("hPA", 100), new MeasurementUnit.UnitConversion("MPa", 1000000D)}
, "??");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
mu = new MeasurementUnit("kPa", new string[] { "KPA", "kilopascal", "KiloPascal" }, new MeasurementUnit.UnitConversion[]{
new MeasurementUnit.UnitConversion("Pa", 1D/1000D)}, "??");
if (!_units.ContainsKey(mu.MainDisplayUnit)) { _units.Add(mu.MainDisplayUnit, mu); }
SaveToXML();
}
public static bool ContainsMeasurementUnit(string unit)
{
lock (MyLock)
{
if (null == _instance) { _instance = new MeasurementUnitList(); }
var units = from u in _instance.GetAllUnits() where u.UnitMatches(unit) select u;
if (units.Count() > 0) { return true; }
else { return false; }
}
}
private void LoadAllMeasurementUnits()
{
if (!System.IO.File.Exists(FILE_NAME))
{
CreateDefaultMeasurementUnitsFile();
}
else
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
string xml = System.IO.File.ReadAllText(FILE_NAME);
doc.LoadXml(xml);
var nodes = doc.GetElementsByTagName("MeasurementUnits");
foreach (var node in nodes)
{
System.Xml.XmlElement element = node as System.Xml.XmlElement;
if (null == element) { continue; }
foreach (var childNode in element.GetElementsByTagName("MeasurementUnit"))
{
System.Xml.XmlElement elem = childNode as System.Xml.XmlElement;
if (null == elem) { continue; }
LoadMeasurementUnit(elem);
}
}
CreateDefaultMeasurementUnitsFile();
}
}
private const string FILE_NAME = "MeasurementUnits.xml";
private void LoadMeasurementUnit(System.Xml.XmlElement node)
{
try
{
MeasurementUnit mu = new MeasurementUnit(node);
if (!_units.ContainsKey(mu.MainDisplayUnit))
{
_units.Add(mu.MainDisplayUnit, mu);
}
else
{
_units[mu.MainDisplayUnit] = mu;
}
}
catch (System.Exception ex) { APILogger.Log("failed to get node from measurement unit db, ", ex); }
}
}
}

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="DTS.SensorDB.Properties.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</sectionGroup>
</configSections>
<applicationSettings>
<DTS.SensorDB.Properties.Settings1>
<setting name="ZeroMethod" serializeAs="String">
<value>1</value>
</setting>
</DTS.SensorDB.Properties.Settings1>
</applicationSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup></configuration>

View File

@@ -0,0 +1,477 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DTS.SensorDB {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Strings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Strings() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DTS.SensorDB.Strings", typeof(Strings).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Prefiltered &gt; CFC 1000 (P).
/// </summary>
internal static string FilterClassType_None {
get {
return ResourceManager.GetString("FilterClassType_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unfiltered (0).
/// </summary>
internal static string FilterClassType_Unfiltered {
get {
return ResourceManager.GetString("FilterClassType_Unfiltered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorCalibration: Expected version {0}, found version {1}.
/// </summary>
internal static string SensorCalibration_Ctor_Err1 {
get {
return ResourceManager.GetString("SensorCalibration_Ctor_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorData: Expected version {0}, found version {1}.
/// </summary>
internal static string SensorData_Ctor_Err1 {
get {
return ResourceManager.GetString("SensorData_Ctor_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorCalibration): newCal is null.
/// </summary>
internal static string SensorDBTables_Add_SensorCalibration_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorCalibration_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorCalibration): newCal.SerialNumber is null.
/// </summary>
internal static string SensorDBTables_Add_SensorCalibration_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorCalibration_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorCalibration): newCal.SerialNumber({0}) doesn&apos;t exist.
/// </summary>
internal static string SensorDBTables_Add_SensorCalibration_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorCalibration_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorData): newSensor is null.
/// </summary>
internal static string SensorDBTables_Add_SensorData_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorData_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorData): newSensor.SerialNumber is null.
/// </summary>
internal static string SensorDBTables_Add_SensorData_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorData_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorData): newSensor.SerialNumber({0}) is not unique.
/// </summary>
internal static string SensorDBTables_Add_SensorData_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorData_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorData): newSensor.Model({0}) doesn&apos;t exist.
/// </summary>
internal static string SensorDBTables_Add_SensorData_Err4 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorData_Err4", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorData): newSensor.Id({0}) is not unique.
/// </summary>
internal static string SensorDBTables_Add_SensorData_Err5 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorData_Err5", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorModel): newModel is null.
/// </summary>
internal static string SensorDBTables_Add_SensorModel_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorModel_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorModel): newModel.Name is null.
/// </summary>
internal static string SensorDBTables_Add_SensorModel_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorModel_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Add(SensorModel): newModel.Name({0}) is not unique.
/// </summary>
internal static string SensorDBTables_Add_SensorModel_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Add_SensorModel_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Close: Trying to close DB with dirty tables.
/// </summary>
internal static string SensorDBTables_Close_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Close_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorCalibration): calib is null.
/// </summary>
internal static string SensorDBTables_Delete_SensorCalibration_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorCalibration_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorCalibration): calib.SerialNumber is null.
/// </summary>
internal static string SensorDBTables_Delete_SensorCalibration_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorCalibration_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorCalibration): Calibrations table is corrupt, there&apos;s more than one entry with same SerialNumber and date.
/// </summary>
internal static string SensorDBTables_Delete_SensorCalibration_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorCalibration_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorData): sensor is null.
/// </summary>
internal static string SensorDBTables_Delete_SensorData_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorData_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorData): sensor.SerialNumber is null.
/// </summary>
internal static string SensorDBTables_Delete_SensorData_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorData_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorData): Sensors table is corrupt, there&apos;s more than one entry with same SerialNumber.
/// </summary>
internal static string SensorDBTables_Delete_SensorData_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorData_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorModel): model is null.
/// </summary>
internal static string SensorDBTables_Delete_SensorModel_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorModel_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorModel): model.Name is null.
/// </summary>
internal static string SensorDBTables_Delete_SensorModel_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorModel_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Delete(SensorModel): Model table is corrupt, there&apos;s more than one entry with same name.
/// </summary>
internal static string SensorDBTables_Delete_SensorModel_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Delete_SensorModel_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.GetCalibrationBySerialNumberAndDate: Duplicate entries for {0} and {1}.
/// </summary>
internal static string SensorDBTables_GetCalibrationBySerialNumberAndDate_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_GetCalibrationBySerialNumberAndDate_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.GetLatestSensitivityBySerialNumber: Sensor {0} doesn&apos;t have any calibration entries.
/// </summary>
internal static string SensorDBTables_GetLatestSensitivityBySerialNumber_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_GetLatestSensitivityBySerialNumber_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorCalibration): calib is null.
/// </summary>
internal static string SensorDBTables_Update_SensorCalibration_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorCalibration_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorCalibration): calib.SerialNumber is null.
/// </summary>
internal static string SensorDBTables_Update_SensorCalibration_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorCalibration_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorCalibration): Calibrations table is corrupt, there&apos;s more than one entry with same SerialNumber and date.
/// </summary>
internal static string SensorDBTables_Update_SensorCalibration_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorCalibration_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorData): sensor parameter is null.
/// </summary>
internal static string SensorDBTables_Update_SensorData_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorData_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorData): sensor.SerialNumber is null.
/// </summary>
internal static string SensorDBTables_Update_SensorData_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorData_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorData): Sensors table is corrupt, there&apos;s more than one entry with same SerialNumber.
/// </summary>
internal static string SensorDBTables_Update_SensorData_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorData_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorData): the new sensor.Id({0}) is not unique.
/// </summary>
internal static string SensorDBTables_Update_SensorData_Err4 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorData_Err4", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorModel): model is null.
/// </summary>
internal static string SensorDBTables_Update_SensorModel_Err1 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorModel_Err1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorModel): model.Name is null.
/// </summary>
internal static string SensorDBTables_Update_SensorModel_Err2 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorModel_Err2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorDBTables.Update(SensorModel): Model table is corrupt, there&apos;s more than one entry with same name.
/// </summary>
internal static string SensorDBTables_Update_SensorModel_Err3 {
get {
return ResourceManager.GetString("SensorDBTables_Update_SensorModel_Err3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to At Capacity.
/// </summary>
internal static string SensorFields_AtCapacity {
get {
return ResourceManager.GetString("SensorFields_AtCapacity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Capacity (EU).
/// </summary>
internal static string SensorFields_CapacityOutputIsBasedOn {
get {
return ResourceManager.GetString("SensorFields_CapacityOutputIsBasedOn", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Engineering Units.
/// </summary>
internal static string SensorFields_EngineeringUnits {
get {
return ResourceManager.GetString("SensorFields_EngineeringUnits", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Excitation.
/// </summary>
internal static string SensorFields_Excitation {
get {
return ResourceManager.GetString("SensorFields_Excitation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Non-Linear Format.
/// </summary>
internal static string SensorFields_NonLinearFormat {
get {
return ResourceManager.GetString("SensorFields_NonLinearFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sensitivity.
/// </summary>
internal static string SensorFields_Sensitivity {
get {
return ResourceManager.GetString("SensorFields_Sensitivity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sensitivity Units.
/// </summary>
internal static string SensorFields_SensitivityUnits {
get {
return ResourceManager.GetString("SensorFields_SensitivityUnits", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ZeroPoint.
/// </summary>
internal static string SensorFields_ZeroPoint {
get {
return ResourceManager.GetString("SensorFields_ZeroPoint", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SensorModel: Expected version {0}, found version {1}.
/// </summary>
internal static string SensorModel_Ctor_Err1 {
get {
return ResourceManager.GetString("SensorModel_Ctor_Err1", resourceCulture);
}
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// helper class for region of interest section of INI
/// </summary>
public class TSFINIRegionOfInterest
{
/// <summary>
/// Start in seconds of ROI relative to T0
/// </summary>
public double StartSeconds { get; set; }
/// <summary>
/// end in seconds of ROI relative to T0
/// </summary>
public double EndSeconds { get; set; }
/// <summary>
/// reads section from a line,
/// returns true if read successfully
/// false if there were errors
/// </summary>
/// <param name="line"></param>
/// <param name="currentLine"></param>
/// <param name="errors"></param>
/// <returns></returns>
public bool ReadFrom(string line, int currentLine, ref List<TDCINIError> errors)
{
string[] tokens = line.Split(new char[] { ',' });
if (2 != tokens.Length)
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ROI_INVALID, line, currentLine));
return false;
}
double d;
if (!double.TryParse(tokens[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ROI_INVALID, line, currentLine));
return false;
}
else { StartSeconds = d; }
if (!double.TryParse(tokens[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ROI_INVALID, line, currentLine));
return false;
}
else { EndSeconds = d; }
return true;
}
}
}

View File

@@ -0,0 +1,49 @@
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
namespace DTS.SensorDB
{
/// <summary>
/// this class handles the updating the default squib settings
/// </summary>
public sealed class DigitalOutputDefaults : DTS.Common.Base.BasePropertyChanged, IDigitalOutDefaults
{
private ISensorData _defaultOut;
public DigitalOutputModes OutputMode { get => _defaultOut.DigitalOutputMode; set => _defaultOut.DigitalOutputMode = value; }
private static DigitalOutputModes[] _outputModes = new DigitalOutputModes[] { DigitalOutputModes.CCNC, DigitalOutputModes.CCNO, DigitalOutputModes.FVHL, DigitalOutputModes.FVLH };
public DigitalOutputModes[] AvailableModes { get => _outputModes; }
public double DelayMS { get => _defaultOut.DigitalOutputDelayMS; set => _defaultOut.DigitalOutputDelayMS = value; }
public bool LimitDuration
{
get => _defaultOut.DigitalOutputLimitDuration;
set
{
_defaultOut.DigitalOutputLimitDuration = value;
OnPropertyChanged("LimitDuration");
}
}
public double DurationMS { get => _defaultOut.DigitalOutputDurationMS; set => _defaultOut.DigitalOutputDurationMS = value; }
public static void CommitChange(DigitalOutputDefaults settingDefaults, string user)
{
DTS.SensorDB.SensorsCollection.SensorsList.Commit(user, (DTS.SensorDB.SensorData)settingDefaults._defaultOut, false);
}
public static DigitalOutputDefaults GetDigitalOutDefault(string user)
{
var sd = DTS.SensorDB.SensorsCollection.SensorsList.GetSensorBySerialNumber(SensorConstants.TEST_SPECIFIC_DIGITAL_OUT_SERIAL);
return new DigitalOutputDefaults(sd);
}
private DigitalOutputDefaults(ISensorData defaultOut)
{
_defaultOut = defaultOut;
}
}
}

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectView>ProjectFiles</ProjectView>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,79 @@
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Slice.Users.UserSettings;
using System;
using System.IO.Ports;
namespace DTS.SensorDB
{
public sealed class UartSettingDefaults : DTS.Common.Base.BasePropertyChanged, IUartSettingDefaults
{
private ISensorData _defaultUart;
public uint BaudRate { get => _defaultUart.UartBaudRate; set => _defaultUart.UartBaudRate = value; }
public uint DataBits { get => _defaultUart.UartDataBits; set => _defaultUart.UartDataBits = value; }
public StopBits StopBits { get => _defaultUart.UartStopBits; set => _defaultUart.UartStopBits = value; }
private static StopBits[] _stopBits = new StopBits[] { StopBits.None, StopBits.One, StopBits.OnePointFive, StopBits.Two };
public StopBits[] AvailableStopBits { get => _stopBits; }
public Parity Parity { get => _defaultUart.UartParity; set => _defaultUart.UartParity = value; }
private static Parity[] _parities = new Parity[] { Parity.None, Parity.Odd, Parity.Even, Parity.Mark, Parity.Space };
public Parity[] AvailableParities { get => _parities; }
//FB 30486 Hardcode FlowControl to NONE for UART sensor type
public Handshake FlowControl { get => Handshake.None; }
private static Handshake[] _flowControls = new Handshake[] { Handshake.None };
public Handshake[] AvailableFlowControls { get => _flowControls; }
public UartDataFormat DataFormat { get => _defaultUart.UartDataFormat; set => _defaultUart.UartDataFormat = value; }
private static UartDataFormat[] _dataFormats = new UartDataFormat[] { UartDataFormat.Binary, UartDataFormat.PlainText, UartDataFormat.NMEA };
public UartDataFormat[] AvailableDataFormats { get => _dataFormats; }
public bool Validate()
{
return true;
}
public static void CommitChange(UartSettingDefaults settingDefaults, int userID)
{
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUARTBaudRate, settingDefaults.BaudRate);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUARTDataBits, settingDefaults.DataBits);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUARTStopBits, settingDefaults.StopBits);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUARTParity, settingDefaults.Parity);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUARTFlowControl, settingDefaults.FlowControl);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultUARTDataFormat, settingDefaults.DataFormat);
}
public static UartSettingDefaults GetUartSettingsDefault(int userID)
{
var sd = new SensorData()
{
UartBaudRate = (uint)TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultUARTBaudRate),
UartDataBits = (uint)TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultUARTDataBits),
UartStopBits = (StopBits)Enum.Parse(typeof(StopBits), TestSetupDefaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultUARTStopBits)),
UartParity = (Parity)Enum.Parse(typeof(Parity), TestSetupDefaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultUARTParity)),
//FB 30486 Hardcode FlowControl to NONE for UART sensor type
UartDataFormat = (UartDataFormat)Enum.Parse(typeof(UartDataFormat), TestSetupDefaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultUARTDataFormat))
};
return new UartSettingDefaults(sd);
}
private UartSettingDefaults(ISensorData defaultUart)
{
_defaultUart = defaultUart;
}
/// <summary>
/// restores digital input settings to defaults
/// </summary>
/// <param name="sensorDefaults"></param>
public static void RestoreDefaults(IUartSettingDefaults sensorDefaults)
{
sensorDefaults.BaudRate = Common.Constant.EmbeddedSensors.BAUD_RATE_DEFAULT;
sensorDefaults.DataBits = UARTRecord.UART_DATABITS_DEFAULT;
sensorDefaults.DataFormat = UARTRecord.UART_DATAFORMAT_DEFAULT;
sensorDefaults.Parity = UARTRecord.UART_PARITY_DEFAULT;
sensorDefaults.StopBits = UARTRecord.UART_STOPBITS_DEFAULT;
}
}
}

View File

@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// handles the CalculateChannelInformation section of the TSF
/// </summary>
public class TSFCalculatedChannelInformationSection
{
private const string SECTION_START_HEADER = "---- Start Calculated Channel Information ----";
private const string COLUMN_HEADER = "chan,descrip,processtype,1stchan,2ndchan,3rdchan,value,EU,expmaxrange";
private const string SECTION_END_HEADER = "---- End Calculated Channel Information ----";
private List<TSFCalculatedChannelEntry> _calculatedChannels = new List<TSFCalculatedChannelEntry>();
public TSFCalculatedChannelEntry[] CalculatedChannels
{
get { return _calculatedChannels.ToArray(); }
set { _calculatedChannels = new List<TSFCalculatedChannelEntry>(value); }
}
/// <summary>
/// reads section from TSF
/// assumes currentline is the start of the section
/// </summary>
/// <param name="lines"></param>
/// <param name="currentLine"></param>
/// <param name="errors"></param>
public void ReadFrom(List<string> lines, ref int currentLine, ref List<ReadTSFError> errors)
{
_calculatedChannels.Clear();
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string sectionHeader = lines[currentLine++];
if (sectionHeader != SECTION_START_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.CALCULATEDCHANNELSSECTION_INVALIDSECTIONHEADER, currentLine, sectionHeader));
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string columnsHeader = lines[currentLine++];
if (columnsHeader != COLUMN_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.CALCULATEDCHANNELSECTION_INVALIDCOLUMNHEADER, currentLine, columnsHeader));
return;
}
var invariant = System.Globalization.CultureInfo.InvariantCulture;
bool done = false;
List<TSFCalculatedChannelEntry> calculatedChannels = new List<TSFCalculatedChannelEntry>();
while (!done)
{
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string line = lines[currentLine++];
if (!line.Contains("End Calculated Channel Information"))
{
string[] tokens = line.Split(new char[] { ',' });
TSFCalculatedChannelEntry cc = new TSFCalculatedChannelEntry();
for (int iCurField = 0; iCurField < tokens.Length; iCurField++)
{
string s = tokens[iCurField];
TSFCalculatedChannelEntry.Fields field = (TSFCalculatedChannelEntry.Fields)iCurField;
switch (field)
{
case TSFCalculatedChannelEntry.Fields.chan:
try { cc.Chan = Convert.ToInt32(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_CHAN_FIELD, currentLine, s)); }
break;
case TSFCalculatedChannelEntry.Fields.descrip: cc.Description = s; break;
case TSFCalculatedChannelEntry.Fields.EU: cc.EU = s; break;
case TSFCalculatedChannelEntry.Fields.expmaxrange:
try { cc.ExpMaxRange = Convert.ToDouble(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_EXPMAXRANGE, currentLine, s)); }
break;
case TSFCalculatedChannelEntry.Fields.firstchan:
try { cc.FirstChan = Convert.ToInt32(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_FIRSTCHAN, currentLine, s)); }
break;
case TSFCalculatedChannelEntry.Fields.processtype:
try { cc.ProcessType = Convert.ToInt32(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_PROCESSTYPE, currentLine, s)); }
break;
case TSFCalculatedChannelEntry.Fields.progress2:
try { cc.Progress2 = Convert.ToDouble(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_PROGRESS2, currentLine, s)); }
break;
case TSFCalculatedChannelEntry.Fields.progress3:
try { cc.Progress3 = Convert.ToDouble(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_PROGRESS3, currentLine, s)); }
break;
case TSFCalculatedChannelEntry.Fields.secondchan:
try { cc.SecondChan = Convert.ToInt32(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_SECONDCHAN, currentLine, s)); }
break;
case TSFCalculatedChannelEntry.Fields.thirdchan:
try { cc.ThirdChan = Convert.ToInt32(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_THIRDCHAN, currentLine, s)); }
break;
case TSFCalculatedChannelEntry.Fields.value:
try { cc.Value = Convert.ToDouble(s, invariant); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_CALCULATED_CHANNEL_INVALID_VALUE, currentLine, s)); }
break;
}
}
calculatedChannels.Add(cc);
}
else { done = true; }
CalculatedChannels = calculatedChannels.ToArray();
}
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// helper class for SmartBatteryThreshold section in ini
/// </summary>
public class INISmartBatteryThresholds
{
/// <summary>
/// time in minutes for Yellow battery warning
/// </summary>
public int Yellow { get; set; }
/// <summary>
/// time in minutes for Red battery warning
/// </summary>
public int Red { get; set; }
public bool ReadFrom(string line, int curLine, ref List<TDCINIError> errors)
{
string[] tokens = line.Split(new char[] { ',' });
if (2 != tokens.Length)
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_SmartBatteryStatusThresholds, line, curLine));
return false;
}
int temp;
if (!int.TryParse(tokens[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out temp))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_SmartBatteryStatusThresholds, line, curLine));
return false;
}
else { Yellow = temp; }
if (!int.TryParse(tokens[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out temp))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_SmartBatteryStatusThresholds, line, curLine));
return false;
}
else { Red = temp; }
return true;
}
}
}

View File

@@ -0,0 +1,275 @@
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors.SensorSettingsModule;
using DTS.Common.Settings;
using System;
using System.Xml;
namespace DTS.SensorDB
{
public class CalibrationPolicy : Common.Base.BasePropertyChanged, ICalibrationPolicy
{
private SensorConstants.SensorCalPolicy _selectedCalPolicy;
/// <summary>
/// returns the currently selected calibration policy
/// </summary>
public SensorConstants.SensorCalPolicy SelectedCalPolicy
{
get => _selectedCalPolicy;
set => SetProperty(ref _selectedCalPolicy, value, "SelectedCalPolicy");
}
private static SensorConstants.SensorCalPolicy[] _availableCalPolicies = new[]
{SensorConstants.SensorCalPolicy.AllowAlways, SensorConstants.SensorCalPolicy.DONT_ALLOW};
/// <summary>
/// returns all the available calibration policies
/// </summary>
public SensorConstants.SensorCalPolicy[] AvailableSensorCalPolicies => _availableCalPolicies;
private int _warningPeriod;
/// <summary>
/// returns the period in days before the calibration is due for a sensor to warn
/// </summary>
public int WarningPeriod
{
get => _warningPeriod;
set => SetProperty(ref _warningPeriod, value, "WarningPeriod");
}
private bool _useSensorFirstUseDate = true;
/// <summary>
/// indicates whether calibration interval starts after calibration or first use
/// 13065 Sensor "First Use" Date
/// </summary>
public bool UseSensorFirstUseDate
{
get => _useSensorFirstUseDate;
set => SetProperty(ref _useSensorFirstUseDate, value, "UseSensorFirstUseDate");
}
public bool SensorAssemblyEnabled
{
get => DTS.Common.Storage.DbOperations.GetConnectionDbVersion() >= Common.Constants.SENSOR_ASSEMBLY_DB_VERSION;
}
private bool _dontAllowDataCollectionIfOverused = false;
/// <summary>
/// Indicates whether or not to keep track of, and validate Test Setups based on, sensor overuse.
/// </summary>
public bool DontAllowDataCollectionIfOverused
{
get => SensorAssemblyEnabled && _dontAllowDataCollectionIfOverused;
set
{
SetProperty(ref _dontAllowDataCollectionIfOverused, value, "DontAllowDataCollectionIfOverused");
}
}
public bool AllowInspectBeforeUseEnabled
{
get => DTS.Common.Storage.DbOperations.GetConnectionDbVersion() >= Common.Constants.ALLOW_INSPECT_BEFORE_USE_DB_VERSION;
}
private bool _allowInspectBeforeUse = false;
//FB 43142
public bool AllowInspectBeforeUse
{
get => AllowInspectBeforeUseEnabled && _allowInspectBeforeUse;
set
{
SetProperty(ref _allowInspectBeforeUse, value, "AllowInspectBeforeUse");
}
}
private int _usageRemainingForWarning;
/// <summary>
/// A warning will be displayed if a sensor's usage is within this amount of its maximum.
/// </summary>
public int UsageRemainingForWarning
{
get => _usageRemainingForWarning;
set => SetProperty(ref _usageRemainingForWarning, value, "UsageRemainingForWarning");
}
private int _defaultMaxUsageAllowed;
/// <summary>
/// The default maximum number of uses for sensors
/// </summary>
public int DefaultMaxUsageAllowed
{
get => _defaultMaxUsageAllowed;
set => SetProperty(ref _defaultMaxUsageAllowed, value, "DefaultMaxUsageAllowed");
}
protected CalibrationPolicy(SensorConstants.SensorCalPolicy calPolicy,
int warningPeriod,
bool useFirstUseDate,
bool dontAllowDataCollectionIfOverused,
int usageRemainingForWarning,
int defaultMaxUsageAllowed,
bool allowInspectBeforeUse)
{
WarningPeriod = warningPeriod;
SelectedCalPolicy = calPolicy;
UseSensorFirstUseDate = useFirstUseDate;
DontAllowDataCollectionIfOverused = dontAllowDataCollectionIfOverused;
UsageRemainingForWarning = usageRemainingForWarning;
DefaultMaxUsageAllowed = defaultMaxUsageAllowed;
AllowInspectBeforeUse = allowInspectBeforeUse;
}
/// <summary>
/// the key for the setting in the db for calibration policy
/// </summary>
private const string SENSOR_CAL_POLICY_KEY = "SensorCalPolicy";
/// <summary>
/// the key for the setting in the db for the warning period
/// </summary>
private const string SENSOR_WARNING_PERIOD_KEY = "SensorCalWarningPeriodDays";
/// <summmary>
/// the key for sensor first use setting in db
/// </summary>
private const string SENSOR_FIRST_USE_KEY = "UseSensorFirstUseDate";
/// <summary>
/// the key for inspect before use setting in db
/// </summary>
private const string ALLOW_INSPECT_BEFORE_USE = "AllowInspectBeforeUse";
/// <summary>
/// The key for sensor overuse setting in db
/// </summary>
private const string SENSOR_OVERUSE_KEY = "DontAllowDataCollectionIfOverused";
/// <summary>
/// The key for sensor overuse setting in db
/// </summary>
private const string SENSOR_USAGE_REMAINING_WARNING_KEY = "UsageRemainingForWarning";
/// <summary>
/// The default maximum number of uses for sensors
/// </summary>
private const string SENSOR_DEFAULT_MAX_USAGE_KEY = "DefaultMaxUsageAllowed";
/// <summary>
/// retrieves calibration policies for sensors from the db and returns it
/// </summary>
/// <returns></returns>
public static ICalibrationPolicy GetCalibrationPolicy()
{
var s = SettingsDB.GetGlobalValue(SENSOR_CAL_POLICY_KEY, SensorConstants.CAL_SENSOR_POLICY_DEFAULT.ToString());
SensorConstants.SensorCalPolicy policy;
Enum.TryParse(s, out policy);
var period = SettingsDB.GetGlobalValueInt(SENSOR_WARNING_PERIOD_KEY,
SensorConstants.CAL_SENSOR_POLICY_WARNING_DAYS_DEFAULT);
var firstUse = SettingsDB.GetGlobalValueBool(SENSOR_FIRST_USE_KEY, SensorConstants.SENSOR_FIRST_USE_DEFAULT);
var allowInspectBeforeUse = SettingsDB.GetGlobalValueBool(ALLOW_INSPECT_BEFORE_USE, SensorConstants.AllowInspectBeforeUse);
var overuse = SettingsDB.GetGlobalValueBool(SENSOR_OVERUSE_KEY, SensorConstants.SENSOR_OVERUSE_DEFAULT);
var usageRemainingForWarning = SettingsDB.GetGlobalValueInt(SENSOR_USAGE_REMAINING_WARNING_KEY, SensorConstants.SENSOR_USAGE_REMAINING_FOR_WARNING_DEFAULT);
var defaultMaxUsage = SettingsDB.GetGlobalValueInt(SENSOR_DEFAULT_MAX_USAGE_KEY, SensorConstants.SENSOR_DEFAULT_MAX_USAGE_DEFAULT);
return new CalibrationPolicy(policy, period, firstUse, overuse, usageRemainingForWarning, defaultMaxUsage, allowInspectBeforeUse);
}
/// <summary>
/// writes calibration policies to the db
/// </summary>
/// <param name="policy"></param>
public static void WriteCalibrationPolicyToDb(ICalibrationPolicy policy)
{
SettingsDB.SetGlobalValue(SENSOR_CAL_POLICY_KEY, policy.SelectedCalPolicy.ToString());
SettingsDB.SetGlobalValueInt(SENSOR_WARNING_PERIOD_KEY, policy.WarningPeriod);
SensorConstants.SensorCalPolicyCurrent = policy.SelectedCalPolicy;
SensorConstants.SensorCalOutOfDateWarningPeriodDays = policy.WarningPeriod;
SettingsDB.SetGlobalValueBoolean(SENSOR_FIRST_USE_KEY, policy.UseSensorFirstUseDate);
SensorConstants.UseSensorFirstUseDate = policy.UseSensorFirstUseDate;
SettingsDB.SetGlobalValueBoolean(SENSOR_OVERUSE_KEY, policy.DontAllowDataCollectionIfOverused);
SensorConstants.DontAllowDataCollectionIfOverused = policy.DontAllowDataCollectionIfOverused;
SettingsDB.SetGlobalValueInt(SENSOR_USAGE_REMAINING_WARNING_KEY, policy.UsageRemainingForWarning);
SensorConstants.UsageRemainingForWarning = policy.UsageRemainingForWarning;
SettingsDB.SetGlobalValueInt(SENSOR_DEFAULT_MAX_USAGE_KEY, policy.DefaultMaxUsageAllowed);
SensorConstants.DefaultMaxUsageAllowed = policy.DefaultMaxUsageAllowed;
//FB 43142
SettingsDB.SetGlobalValueBoolean(ALLOW_INSPECT_BEFORE_USE, policy.AllowInspectBeforeUse);
SensorConstants.AllowInspectBeforeUse = policy.AllowInspectBeforeUse;
}
/// <summary>
/// restores the defaults in the db of calibration policies
/// </summary>
public static void RestoreDefaults()
{
SettingsDB.SetGlobalValue(SENSOR_CAL_POLICY_KEY, SensorConstants.CAL_SENSOR_POLICY_DEFAULT.ToString());
SettingsDB.SetGlobalValueInt(SENSOR_WARNING_PERIOD_KEY, SensorConstants.CAL_SENSOR_POLICY_WARNING_DAYS_DEFAULT);
SettingsDB.SetGlobalValueBoolean(SENSOR_FIRST_USE_KEY, SensorConstants.SENSOR_FIRST_USE_DEFAULT);
SettingsDB.SetGlobalValueBoolean(SENSOR_OVERUSE_KEY, SensorConstants.SENSOR_OVERUSE_DEFAULT);
SettingsDB.SetGlobalValueInt(SENSOR_USAGE_REMAINING_WARNING_KEY, SensorConstants.SENSOR_USAGE_REMAINING_FOR_WARNING_DEFAULT);
SettingsDB.SetGlobalValueInt(SENSOR_DEFAULT_MAX_USAGE_KEY, SensorConstants.SENSOR_DEFAULT_MAX_USAGE_DEFAULT);
//FB 43142
SettingsDB.SetGlobalValueBoolean(ALLOW_INSPECT_BEFORE_USE, SensorConstants.ALLOW_INSPECT_BEFORE_USE_DEFAULT);
}
public void ReadXML(System.Xml.XmlElement root)
{
foreach (var node in root.ChildNodes)
{
if (node is System.Xml.XmlElement) { ProcessXMLElement(node as System.Xml.XmlElement); }
}
}
private void ProcessXMLElement(System.Xml.XmlElement node)
{
if (Enum.TryParse(node.Name, out CalPolicyXMLFields field))
{
switch (field)
{
case CalPolicyXMLFields.SelectedCalPolicy:
if (Enum.TryParse(node.InnerText, out SensorConstants.SensorCalPolicy calPolicy))
{
SelectedCalPolicy = calPolicy;
}
break;
case CalPolicyXMLFields.UseSensorFirstUseDate: UseSensorFirstUseDate = Convert.ToBoolean(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case CalPolicyXMLFields.WarningPeriod: WarningPeriod = Convert.ToInt32(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case CalPolicyXMLFields.DontAllowDataCollectionIfOverused: DontAllowDataCollectionIfOverused = Convert.ToBoolean(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case CalPolicyXMLFields.UsageRemainingForWarning: UsageRemainingForWarning = Convert.ToInt32(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case CalPolicyXMLFields.DefaultMaxUsageAllowed: DefaultMaxUsageAllowed = Convert.ToInt32(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
default: throw new NotSupportedException("CalibrationPolicy::ProcessXMLElement unsupported field: " + field);
}
}
}
public void WriteXML(ref XmlWriter writer)
{
writer.WriteStartElement("CalibrationPolicy");
writer.WriteStartElement(CalPolicyXMLFields.SelectedCalPolicy.ToString());
writer.WriteString(SelectedCalPolicy.ToString());
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.UseSensorFirstUseDate.ToString());
writer.WriteString(UseSensorFirstUseDate.ToString());
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.WarningPeriod.ToString());
writer.WriteString(WarningPeriod.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.DontAllowDataCollectionIfOverused.ToString());
writer.WriteString(DontAllowDataCollectionIfOverused.ToString());
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.UsageRemainingForWarning.ToString());
writer.WriteString(UsageRemainingForWarning.ToString());
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.DefaultMaxUsageAllowed.ToString());
writer.WriteString(DefaultMaxUsageAllowed.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
}
public enum CalPolicyXMLFields
{
SelectedCalPolicy,
UseSensorFirstUseDate,
WarningPeriod,
DontAllowDataCollectionIfOverused,
UsageRemainingForWarning,
DefaultMaxUsageAllowed
}
}

View File

@@ -0,0 +1,84 @@
using DTS.Common.Classes;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
using System;
using System.Data;
using System.Data.SqlClient;
namespace DTS.SensorDB
{
public class StreamOutputSetting : SensorData
{
///<summary>
///</summary>
public StreamOutputSetting() : base()
{
SetDefaults(this);
}
public StreamOutputSetting(StreamOutputSetting copy) : base(copy)
{
SetDefaults(this);
}
public StreamOutputSetting(IStreamOutputRecord record)
{
SetDefaults(this);
try
{
DatabaseId = record.Id;
SerialNumber = record.SerialNumber;
StreamOutUDPProfile = record.StreamOutUDPProfile;
StreamOutUDPAddress = record.StreamOutUDPAddress;
StreamOutUDPTimeChannelId = record.StreamOutUDPTimeChannelId;
StreamOutUDPDataChannelId = record.StreamOutUDPDataChannelId;
StreamOutUDPTmNSConfig = record.StreamOutUDPTmNSConfig;
StreamOutIRIGTimeDataPacketIntervalMs = record.StreamOutIRIGTimeDataPacketIntervalMs;
StreamOutTMATSIntervalMs = record.StreamOutTMATSIntervalMs;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
LastModified = record.LastModified;
LastUpdatedBy = record.LastUpdatedBy;
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
}
public static void SetDefaults(SensorData sd)
{
sd.SupportedExcitation = new Common.Enums.ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Undefined };
sd.Bridge = SensorConstants.BridgeType.StreamOut;
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 1;
sd.DisplayUnit = "";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 0;
sd.OffsetToleranceLow = 0;
sd.Model = "Stream Output Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
IStreamOutputRecord record = new StreamOutputRecord(setting);
var hr = DbOperations.SensorsStreamOutputUpdateInsert(ref record);
if (0 == hr)
{
setting.DatabaseId = record.Id;
}
}
}
}

View File

@@ -0,0 +1,53 @@
using DTS.Slice.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTS.SensorDB
{
public static class FactorySensorModel
{
public static SensorModel CreateModelFromSensor(SensorData sd, SensorCalibration sc, User currentUser)
{
var model = new SensorModel();
model.Calibration = new SensorCalibration(sc);
model.AxisNumber = sd.AxisNumber;
model.Bridge = sd.Bridge;
model.BridgeResistance = sd.BridgeResistance;
model.CalInterval = sd.CalInterval;
model.Capacity = sd.Capacity;
model.CheckOffset = sd.CheckOffset;
model.CouplingMode = sd.CouplingMode;
model.Direction = sd.Direction;
model.SupportedExcitation = sd.SupportedExcitation;
model.Filter = sd.Filter;
model.IgnoreRange = sd.IgnoreRange;
model.Invert = sd.Invert;
model.LastModified = DateTime.Now;
model.LastUpdatedBy = currentUser.UserName;
model.Manufacturer = sd.Manufacturer;
model.DisplayUnit = sd.DisplayUnit;
model.Model = sd.Model;
model.NumberOfAxes = sd.NumberOfAxes;
model.OffsetToleranceHigh = sd.OffsetToleranceHigh;
model.OffsetToleranceLow = sd.OffsetToleranceLow;
model.PhysicalDimension = sd.PhysicalDimension;
model.Polarity = sd.Polarity;
//
model.RangeHigh = sd.RangeHigh;
model.RangeLow = sd.RangeLow;
model.RangeMedium = sd.RangeMedium;
model.Shunt = sd.Shunt;
model.UniPolar = sd.UniPolar;
model.UserPartNumber = sd.UserSerialNumber;
model.Version = sd.Version;
return model;
}
}
}

View File

@@ -0,0 +1,38 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual C# Express 2008
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SensorDB", "SensorDB.csproj", "{444EF10C-046E-47AD-A9A5-17318D488723}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SensorDB NUnit", "SensorDBNUnit\SensorDB NUnit.csproj", "{28F0A3B9-1B28-49E1-908C-1E2CEE3B34A0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTS.DAS.Concepts", "Concepts\DTS.DAS.Concepts.csproj", "{03D8C736-36EB-4CD1-A6D9-130452B23239}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTS.Utilities", "Concepts\DTS.Utilities\DTS.Utilities.csproj", "{03EACE47-EA59-44AC-B49D-956E4DC4D618}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{444EF10C-046E-47AD-A9A5-17318D488723}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{444EF10C-046E-47AD-A9A5-17318D488723}.Debug|Any CPU.Build.0 = Debug|Any CPU
{444EF10C-046E-47AD-A9A5-17318D488723}.Release|Any CPU.ActiveCfg = Release|Any CPU
{444EF10C-046E-47AD-A9A5-17318D488723}.Release|Any CPU.Build.0 = Release|Any CPU
{28F0A3B9-1B28-49E1-908C-1E2CEE3B34A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{28F0A3B9-1B28-49E1-908C-1E2CEE3B34A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{28F0A3B9-1B28-49E1-908C-1E2CEE3B34A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{28F0A3B9-1B28-49E1-908C-1E2CEE3B34A0}.Release|Any CPU.Build.0 = Release|Any CPU
{03D8C736-36EB-4CD1-A6D9-130452B23239}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03D8C736-36EB-4CD1-A6D9-130452B23239}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03D8C736-36EB-4CD1-A6D9-130452B23239}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03D8C736-36EB-4CD1-A6D9-130452B23239}.Release|Any CPU.Build.0 = Release|Any CPU
{03EACE47-EA59-44AC-B49D-956E4DC4D618}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{03EACE47-EA59-44AC-B49D-956E4DC4D618}.Debug|Any CPU.Build.0 = Debug|Any CPU
{03EACE47-EA59-44AC-B49D-956E4DC4D618}.Release|Any CPU.ActiveCfg = Release|Any CPU
{03EACE47-EA59-44AC-B49D-956E4DC4D618}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,644 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DTS.Common.Classes.Sensors;
using DTS.Common.DAS.Concepts;
using DTS.Common.Enums.Sensors;
namespace DTS.SensorDB
{
/// <summary>
/// class for to and from Sensor Information Files (*.SIF)
/// These are TDC sensor information files
/// </summary>
public class SensorInformationFile
{
/// <summary>
/// just chose this out of the latest version of TDAS I have's .ini (which is actually 7.1.1x)
/// as far as I know it doesn't need to be set, it may just be for informational purposes
/// </summary>
public const string LASTKNOWN_TDCSOFTWAREVERSION = "7.1.1w";
/// <summary>
/// The SIF is a linear text file, with either a blank line, or a header, or a data entry
/// on each line
/// here are all the possible headers/lines we can find,
/// we probably expect to see all of them, but it's probably not fatal if we don't see
/// say description or something
/// </summary>
public enum Fields
{
SoftwareVersion,
DummyLine1,
ChannelDescription,
SerialNumber,
OffsetLowTol,
OffsetHighTol,
CalMode,
CalStep,
ShuntValue,
ProportionalToExcitation,
Sensitivity,
Gain,
ExcitationVoltage,
EngUnits,
SoftwareFilter,
InvertData,
ZeroReference,
DesiredMaxRangeInEU,
CalibrationDate,
RemoveNaturalSensorOffset,
InitialEUValue,
SensorIDType,
SensorID,
ISOCode,
SensorCategory
}
/// <summary>
/// saves a sensor calibration and sensor data entry to a SIF
/// will back up the file first before saving it
/// </summary>
/// <param name="sd">input sensor data</param>
/// <param name="sc">input sensor calibration</param>
/// <param name="filename">the filename including path to save to</param>
/// <param name="errors">any errors or warnings during the export</param>
/// <returns>true if the file was saved, false if the file was not saved</returns>
public static bool SaveSIF(SensorData sd, SensorCalibration sc, string filename, ref List<string> errors)
{
try
{
BackupFile(filename);
WriteSIF(filename, sd, sc, ref errors);
}
catch (Exception ex)
{
errors.Add(ex.Message);
return false;
}
return true;
}
public const string ERROR_SEPARATOR = " - ";
/// <summary>
/// retrieves a sensor from a SIF
/// </summary>
/// <param name="filename">filename and full path to file to read</param>
/// <param name="sd">sensor data (may be null if file could not be processed)</param>
/// <param name="sc">sensor calibration (may be ull if file could not be processed)</param>
/// <param name="errors">any warnings or errors that occurred during processing the file</param>
/// <returns>true if sensor was read, false if sensor could not be read</returns>
public static bool LoadFromSIF(string filename, out SensorData sd, out SensorCalibration sc, ref List<string> errors)
{
sd = null;
sc = null;
try
{
//check the file exists
if (!File.Exists(filename)) { return false; }
var lines = File.ReadAllLines(filename);
sd = new SensorData();
sc = new SensorCalibration();
var category = TDCSensorCategory.Normal;
var sensitivities = new List<double>();
//go through all the lines in the file, a lot of times we'll jump two lines
//but we don't assume that, we just assume one line then jump two when we need to
for (var i = 0; i < lines.Length; i++)
{
var field = GetFieldForTag(lines[i]);
int y = 0;
switch (field)
{
case Fields.CalibrationDate:
{
i++;//also handle the data line
var tokens = lines[i].Split(new[] { "_" }, StringSplitOptions.None);
if (3 != tokens.Length) { throw new InvalidDataException(field.ToString()); }
if (!int.TryParse(tokens[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out int m))
{ throw new InvalidDataException(field.ToString()); }
if (!int.TryParse(tokens[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out int d))
{ throw new InvalidDataException(field.ToString()); }
if (!int.TryParse(tokens[2], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out y))
{ throw new InvalidDataException(field.ToString()); }
sc.CalibrationDate = new DateTime(y, m, d);
}
break;
case Fields.CalMode:
{
i++; //also handle the data line
var cm = new CalMode(lines[i]);
sd.Shunt = cm.ShuntCheck ? ShuntMode.Emulation : ShuntMode.None;
sd.Bridge = cm.FullBridge ? SensorConstants.BridgeType.FullBridge : SensorConstants.BridgeType.HalfBridge;
sd.ByPassFilter = !cm.Filter;
}
break;
case Fields.CalStep: i++; break;//not used by datapro
case Fields.ChannelDescription:
{
i++; //also handle the data line
sd.Comment = lines[i];
}
break;
case Fields.DesiredMaxRangeInEU:
{
i++; //also handle the data line
if (double.TryParse(lines[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
{
//the SIF doesn't have ranges in it, so we just set all the ranges to one value to avoid confusion
sd.Capacity = d;
sd.RangeHigh = d;
sd.RangeMedium = d;
sd.RangeLow = d;
}
else { throw new InvalidDataException(field + ERROR_SEPARATOR + lines[i]); }
}
break;
case Fields.DummyLine1: break; //empty line
case Fields.EngUnits:
{
i++; //also handle the data line
// This call insures that the display unit will be added to the list.
MeasurementUnitList.GetMeasurementUnit(lines[i]);
//store EU into both storage areas. DataPRO has display units and cal units
//so we just set both to the same unit since SIF only has one
sd.DisplayUnit = lines[i];
Array.ForEach(sc.Records.Records, record => record.EngineeringUnits = lines[i]); //FB16398: set units on all records, not just first
}
break;
case Fields.ExcitationVoltage:
{
i++; //also handle the data line
if (double.TryParse(lines[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
{
var excitation = Test.Module.Channel.Sensor.GetExcitationVoltageEnumFromMagnitude(d);
sd.SupportedExcitation = new[] { excitation };
sc.Records.Records[0].Excitation = excitation;
}
else { throw new InvalidDataException(field + ERROR_SEPARATOR + lines[i]); }
}
break;
case Fields.Gain: i++; break;//not used
case Fields.InitialEUValue:
{
i++; //also handle the data line
if (double.TryParse(lines[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
{
sc.InitialOffsets = new InitialOffsets(new InitialOffset(d));
}
else { throw new InvalidDataException(field + ERROR_SEPARATOR + lines[i]); }
}
break;
case Fields.InvertData:
{
i++; //also handle the data line
switch (lines[i].ToUpper())
{
case "0":
case "N":
case "F":
sd.Invert = false;
break;
default:
sd.Invert = true;
break;
}
}
break;
case Fields.ISOCode:
{
i++; //also handle the data line
sd.ISOCode = sd.BuildIsoCodeFromFilter(lines[i], sd.Filter.FClass);
}
break;
case Fields.OffsetHighTol:
{
i++; //also handle the data line
if (double.TryParse(lines[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
{
sd.OffsetToleranceHigh = d;
}
else { throw new InvalidDataException(field + ERROR_SEPARATOR + lines[i]); }
}
break;
case Fields.OffsetLowTol:
{
i++; //also handle the data line
if (double.TryParse(lines[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
{
sd.OffsetToleranceLow = d;
}
else { throw new InvalidDataException(field + ERROR_SEPARATOR + lines[i]); }
}
break;
case Fields.ProportionalToExcitation:
{
i++; //also handle the data line
switch (lines[i].ToUpper())
{
case "0":
case "N":
case "F":
sc.IsProportional = false;
break;
default:
sc.IsProportional = true;
break;
}
}
break;
case Fields.RemoveNaturalSensorOffset:
{
i++; //also handle the data line
switch (lines[i].ToUpper())
{
case "0":
case "N":
case "F":
sc.RemoveOffset = false;
break;
default:
sc.RemoveOffset = true;
break;
}
}
break;
case Fields.Sensitivity:
{
i++; //also handle the data line
//sensitivities in the SIF can vary based on software version, some versions may only have one decimal
//some will have 4 (polynomial) note that having 4 entries doesn't mean that all 4 entries are used
var tokens = lines[i].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
sensitivities.Clear();
foreach (var t in tokens)
{
if (double.TryParse(t, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
{
sensitivities.Add(d);
}
}
}
break;
case Fields.SensorCategory:
{
i++; //also handle the data line
if (int.TryParse(lines[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out int temp))
{
category = (TDCSensorCategory)temp;
}
else
{
throw new InvalidDataException(field + ERROR_SEPARATOR + lines[i]);
}
}
break;
case Fields.SensorID:
{
i++; //also handle the data line
sd.EID = lines[i];
if (sd.EID.ToLower().Contains("none")) { sd.EID = ""; }
}
break;
case Fields.SensorIDType: i++; break;//not used currently
case Fields.SerialNumber:
{
i++; //also handle the data line
sd.SerialNumber = lines[i];
sc.SerialNumber = lines[i];
}
break;
case Fields.ShuntValue:
{
i++; //also handle the data line
if (double.TryParse(lines[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
{
sd.BridgeResistance = d;
}
else { throw new InvalidDataException(field + ERROR_SEPARATOR + lines[i]); }
}
break;
case Fields.SoftwareFilter:
{
i++; //also handle the data line
if (string.IsNullOrEmpty(lines[i]))
{
sd.Filter.FClass = FilterClassType.None;
}
else if (double.TryParse(lines[i], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out double d))
{
sd.Filter = new FilterClass(d);
}
else { throw new InvalidDataException(field + ERROR_SEPARATOR + lines[i]); }
}
break;
case Fields.SoftwareVersion:
if (false == string.IsNullOrEmpty(lines[i + 1]))
{
//need to read advance the line if the version is on the next line
if (int.TryParse(lines[i + 1][0].ToString(), out var notUsed)) { i++; }
}
break;
case Fields.ZeroReference:
{
i++; //also handle the data line
//note that the SIF doesn't contain the average window start/stop for average over time
var zr = new ZeroRef(lines[i]);
switch (zr.ZeroMethod)
{
case ZeroRef.ZeroType.AverageOverTime:
sc.ZeroMethods.Methods[0].Method = ZeroMethodType.AverageOverTime;
break;
case ZeroRef.ZeroType.UsePreEventDiagnostics:
sc.ZeroMethods.Methods[0].Method = ZeroMethodType.UsePreEventDiagnosticsZero;
break;
case ZeroRef.ZeroType.UseZeroMv:
sc.ZeroMethods.Methods[0].Method = ZeroMethodType.None;
break;
}
}
break;
default: throw new NotSupportedException("unknown field: " + field);
}
}
//now set the sensitivities based on what the sensor category is
switch (category)
{
case TDCSensorCategory.IRTracc:
if (2 > sensitivities.Count) { throw new NotSupportedException(category + ERROR_SEPARATOR + "requires 2 sensitivity entries"); }
sc.NonLinear = true;
if (sc.Records.Records[0].Poly.NonLinearStyle == NonLinearStyles.IRTraccAverageOverTime)
{
sc.Records.Records[0].Poly.NonLinearStyle = NonLinearStyles.IRTraccAverageOverTime;
sc.ZeroMethods.Methods[0].Method = ZeroMethodType.AverageOverTime;
sc.Records.Records[0].Poly.MMPerV = 1000D / sensitivities[0];
sc.Records.Records[0].Poly.LinearizationExponent = sensitivities[1];
}
break;
case TDCSensorCategory.Normal:
case TDCSensorCategory.POT:
sc.Records.Records[0].Sensitivity = sensitivities[0]; break;
case TDCSensorCategory.Polynomial:
if (8 != sensitivities.Count) { throw new InvalidDataException(category + ERROR_SEPARATOR + "requires 4 sensitivity entries"); }
sc.NonLinear = true;
sc.Records.Records[0].Poly.NonLinearStyle = NonLinearStyles.Polynomial;
sc.Records.Records[0].Poly.SetCoefficient(3D, sensitivities[2]);
sc.Records.Records[0].Poly.SetCoefficient(2D, sensitivities[3]);
sc.Records.Records[0].Poly.SetCoefficient(1D, sensitivities[4]);
sc.Records.Records[0].Poly.SetCoefficient(0D, sensitivities[5]);
sc.ZeroMethods.Methods[0].Method = ZeroMethodType.None;
break;
default: throw new NotSupportedException("unknown category: " + category);
}
}
catch (Exception ex)
{
errors.Add(ex.Message);
return false;
}
return true;
}
/// <summary>
/// returns the string header for a given field
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
public static string GetTagForField(Fields field)
{
//treating these as all hardcoded as they are in TDC
switch (field)
{
case Fields.CalibrationDate: return "---- Calibration Date M_D_Y ----";
case Fields.CalMode: return "---- Cal Mode - I=Voltage Insertion, S=Shunt ----";
case Fields.CalStep: return "---- Cal Step - shunt resistor (Ohms) ----";
case Fields.ChannelDescription: return "---- Channel Description ----";
case Fields.DesiredMaxRangeInEU: return "---- Desired Max Range in Eng Units ----";
case Fields.DummyLine1: return "";
case Fields.EngUnits: return "---- Eng Unit ----";
case Fields.ExcitationVoltage: return "---- Excitation Voltage must be a valid voltage from list ----";
case Fields.Gain: return "---- Gain - must be a valid gain from list ----";
case Fields.InitialEUValue: return "---- Initial EU Value ----";
case Fields.InvertData: return "---- Invert Data - 0=no invert, 1=yes invert ----";
case Fields.ISOCode: return "---- ISO Code ----";
case Fields.OffsetHighTol: return "---- Offset High Tol (mV) ----";
case Fields.OffsetLowTol: return "---- Offset Low Tol (mV) ----";
case Fields.ProportionalToExcitation: return "---- Proportional to Excitation ----";
case Fields.RemoveNaturalSensorOffset: return "---- Remove Natural Sensor Offset? ----";
case Fields.Sensitivity: return "---- Sensitivity (mV/V/eng unit) ----";
case Fields.SensorCategory: return "---- Sensor Category (Use 0 for most sensors) ----";
case Fields.SensorID: return "---- Sensor ID No ----";
case Fields.SensorIDType: return "---- Sensor ID Type ----";
case Fields.SerialNumber: return "---- Serial Number ----";
case Fields.ShuntValue: return "---- Shunt Value - corresponding value of shunt resistor in Eng Units ----";
case Fields.SoftwareFilter: return "---- Software Filter, -3dB point (Hz) ----";
case Fields.SoftwareVersion: return "Software Version: ";
case Fields.ZeroReference: return "---- Zero Reference - 0=use 30 msec avg, 1=use prezero, 2=equals zero mV ----";
default:
throw new NotSupportedException("unknown field: " + field);
}
}
/// <summary>
/// returns a field given a header line
/// </summary>
/// <param name="tag"></param>
/// <returns></returns>
public static Fields GetFieldForTag(string tag)
{
if (tag.StartsWith(GetTagForField(Fields.SoftwareVersion))) { return Fields.SoftwareVersion; }
switch (tag)
{
case "---- Calibration Date M_D_Y ----": return Fields.CalibrationDate;
case "---- Cal Mode - I=Voltage Insertion, S=Shunt ----": return Fields.CalMode;
case "---- Cal Step - shunt resistor (Ohms) ----": return Fields.CalStep;
case "---- Channel Description ----": return Fields.ChannelDescription;
case "---- Desired Max Range in Eng Units ----": return Fields.DesiredMaxRangeInEU;
case "": return Fields.DummyLine1;
case "---- Eng Unit ----": return Fields.EngUnits;
case "---- Excitation Voltage must be a valid voltage from list ----": return Fields.ExcitationVoltage;
case "---- Gain - must be a valid gain from list ----": return Fields.Gain;
case "---- Initial EU Value ----":
case "---- Initial EU Value": // Older TDC sifs have this
return Fields.InitialEUValue;
case "---- Invert Data - 0=no invert, 1=yes invert ----": return Fields.InvertData;
case "---- ISO Code ----": return Fields.ISOCode;
case "---- Offset High Tol (mV) ----": return Fields.OffsetHighTol;
case "---- Offset Low Tol (mV) ----": return Fields.OffsetLowTol;
case "---- Proportional to Excitation ----": return Fields.ProportionalToExcitation;
case "---- Remove Natural Sensor Offset? ----": return Fields.RemoveNaturalSensorOffset;
case "---- Sensitivity (mV/V/eng unit) ----": return Fields.Sensitivity;
case "---- Sensor Category (Use 0 for most sensors) ----": return Fields.SensorCategory;
case "---- Sensor ID No ----": return Fields.SensorID;
case "---- Sensor ID Type ----": return Fields.SensorIDType;
case "---- Serial Number ----": return Fields.SerialNumber;
case "---- Shunt Value - corresponding value of shunt resistor in Eng Units ----": return Fields.ShuntValue;
case "---- Software Filter, -3dB point (Hz) ----":
case "---- Software Filter, -3dB point (HZ) ----": // Older TDC sifs have this
return Fields.SoftwareFilter;
case "Software Version: ":
case "Software Version:": // Older TDC sifs have this
return Fields.SoftwareVersion;
case "---- Zero Reference - 0=use 30 msec avg, 1=use prezero, 2=equals zero mV ----": return Fields.ZeroReference;
default:
throw new NotSupportedException("unknown field: " + tag);
}
}
/// <summary>
/// moves file to a backup destination location
/// will delete existing backup if it's already present
/// </summary>
/// <param name="fileName"></param>
private static void BackupFile(string fileName)
{
if (File.Exists(fileName))
{
var fi = new FileInfo(fileName);
var backupName = fileName.Replace(fi.Extension, ".BAK");
if (File.Exists(backupName)) { File.Delete(backupName); }
File.Move(fileName, backupName);
}
}
/// <summary>
/// these are constants from TDAS Control for the field SensorCategory
/// </summary>
public enum TDCSensorCategory
{
Normal = 0,
POT = 1,
IRTracc = 2,
Polynomial = 3
}
/// <summary>
/// Writes a sensor entry and calibration to a Sensor Information File (SIF)
/// </summary>
/// <param name="filename">filename and full path to file to write</param>
/// <param name="sd"></param>
/// <param name="sc"></param>
/// <param name="errors">any errors or warnings that occurred during writing</param>
private static void WriteSIF(string filename, SensorData sd, SensorCalibration sc, ref List<string> errors)
{
var sb = new StringBuilder(1500);
var fields = Enum.GetValues(typeof(Fields)).Cast<Fields>().ToArray();
var capacity = sd.Capacity * MeasurementUnitList.GetMeasurementUnit(sc.Records.Records[0].EngineeringUnits).GetScalerConversionFrom(sd.DisplayUnit);
var excitation = Test.Module.Channel.Sensor.GetExcitationVoltageMagnitudeFromEnum(sd.SupportedExcitation[0]);
var calmode = new CalMode() { Filter = !sd.ByPassFilter, FullBridge = sd.Bridge == SensorConstants.BridgeType.FullBridge, ShuntCheck = sd.Shunt == ShuntMode.Emulation };
ZeroRef zeroref = null;
//TODO: linear/nonlinear
switch (sc.ZeroMethods.Methods[0].Method)
{
case ZeroMethodType.AverageOverTime: zeroref = new ZeroRef(ZeroRef.ZeroType.AverageOverTime); break;
case ZeroMethodType.None: zeroref = new ZeroRef(ZeroRef.ZeroType.UseZeroMv); break;
case ZeroMethodType.UsePreEventDiagnosticsZero: zeroref = new ZeroRef(ZeroRef.ZeroType.UsePreEventDiagnostics); break;
default: throw new NotSupportedException("unknown zero method type: " + sc.ZeroMethods.Methods[0].Method);
}
foreach (var f in fields)
{
if (f == Fields.SoftwareVersion)
{
sb.AppendFormat("{0}{1}\n", GetTagForField(f), LASTKNOWN_TDCSOFTWAREVERSION);
}
else
{
var tag = GetTagForField(f);
sb.AppendLine(tag);
switch (f)
{
case Fields.CalibrationDate: sb.AppendFormat("{0}_{1}_{2}\n", sc.CalibrationDate.Month, sc.CalibrationDate.Day, sc.CalibrationDate.Year); break;
case Fields.CalMode: sb.AppendLine(calmode.ToString()); break;
case Fields.CalStep: sb.AppendLine("-1"); break;//for now we only support emulation?
case Fields.ChannelDescription: sb.AppendLine(sd.Comment); break;
case Fields.DesiredMaxRangeInEU: sb.AppendLine(capacity.ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case Fields.DummyLine1: break;
case Fields.EngUnits: sb.AppendLine(sc.Records.Records[0].EngineeringUnits); break;
case Fields.ExcitationVoltage: sb.AppendFormat("{0:0.0}", excitation); break;
case Fields.Gain: sb.AppendFormat("1.0"); break;//not used in datapro ... maybe we need to calculate it
case Fields.InitialEUValue: sb.Append(SensorData.GetInitialEUValue(sc, sd.SupportedExcitation[0], sc.InitialOffsets.Offsets[0]).ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case Fields.InvertData:
if (sd.Invert) { sb.AppendLine("1"); }
else { sb.AppendLine("0"); }
break;
case Fields.ISOCode: sb.AppendLine(sd.ISOCode); break;
case Fields.OffsetHighTol: sb.AppendLine(sd.OffsetToleranceHigh.ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case Fields.OffsetLowTol: sb.AppendLine(sd.OffsetToleranceLow.ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case Fields.ProportionalToExcitation:
if (sc.IsProportional) { sb.AppendLine("Y"); }
else { sb.AppendLine("N"); }
break;
case Fields.RemoveNaturalSensorOffset:
if (sc.RemoveOffset) { sb.AppendLine("Y"); }
else { sb.AppendLine("N"); }
break;
case Fields.Sensitivity:
if (sc.NonLinear)
{
double d1 = 1, d2 = 0, d3 = 0, d4 = 0, d5 = 0, d6 = 0, d7 = 0, d8 = 0;
if (sc.Records.Records[0].Poly.NonLinearStyle == NonLinearStyles.Polynomial)
{
d8 = sc.Records.Records[0].Poly.GetCoefficient(5D);
d7 = sc.Records.Records[0].Poly.GetCoefficient(4D);
d6 = sc.Records.Records[0].Poly.GetCoefficient(3D);
d5 = sc.Records.Records[0].Poly.GetCoefficient(2D);
d4 = sc.Records.Records[0].Poly.GetCoefficient(1D);
d3 = sc.Records.Records[0].Poly.GetCoefficient(0D);
}
else
{
d1 = sc.Records.Records[0].Poly.MMPerV / 1000D;
d2 = sc.Records.Records[0].Poly.LinearizationExponent;
}
sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7}\n",
d1.ToString("F12", System.Globalization.CultureInfo.InvariantCulture),
d2.ToString("F12", System.Globalization.CultureInfo.InvariantCulture),
d3.ToString("F12", System.Globalization.CultureInfo.InvariantCulture),
d4.ToString("F12", System.Globalization.CultureInfo.InvariantCulture),
d5.ToString("F12", System.Globalization.CultureInfo.InvariantCulture),
d6.ToString("F12", System.Globalization.CultureInfo.InvariantCulture),
d7.ToString("F12", System.Globalization.CultureInfo.InvariantCulture),
d8.ToString("F12", System.Globalization.CultureInfo.InvariantCulture));
}
else { sb.AppendLine(sc.Records.Records[0].Sensitivity.ToString("F12", System.Globalization.CultureInfo.InvariantCulture)); }
break;
case Fields.SensorCategory:
var cat = TDCSensorCategory.Normal;
if (sc.NonLinear)
{
if (sc.Records.Records[0].Poly.NonLinearStyle == NonLinearStyles.Polynomial)
{
cat = TDCSensorCategory.Polynomial;
}
else { cat = TDCSensorCategory.IRTracc; }
}
sb.AppendLine(((int)cat).ToString(System.Globalization.CultureInfo.InvariantCulture));
break;
case Fields.SensorID: sb.AppendLine(sd.EID); break;
case Fields.SensorIDType: sb.AppendLine("Dallas"); break; //D or S?
case Fields.SerialNumber: sb.AppendLine(sd.SerialNumber); break;
case Fields.ShuntValue: sb.AppendLine(sd.BridgeResistance.ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case Fields.SoftwareFilter: sb.AppendLine(sd.Filter.Frequency.ToString("F0", System.Globalization.CultureInfo.InvariantCulture)); break;
case Fields.SoftwareVersion: break;
case Fields.ZeroReference: sb.AppendLine(zeroref.ToString()); break;
default:
throw new NotSupportedException("unsupported field: " + f);
}
}
}
}
}
}

View File

@@ -0,0 +1,298 @@
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Interface.Sensors.SoftwareFilters;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using DTS.Common.Settings;
using Prism.Events;
namespace DTS.SensorDB
{
public class AnalogSettingDefaults : Common.Base.BasePropertyChanged, IAnalogDefaults
{
private List<ISoftwareFilter> _softwareFilters;
private IEventAggregator _eventAggregator;
public AnalogSettingDefaults()
{
_softwareFilters = SoftwareFilter.GetSoftwareFilters().ToList();
_eventAggregator = ContainerLocator.Container.Resolve<IEventAggregator>();
_eventAggregator.GetEvent<DTS.Common.Events.Sensors.SensorsList.SensorSavedEvent>().Subscribe(SelectSoftwareFilter);
}
//FB 13120 select default filter for new add hoc filter
private void SelectSoftwareFilter(double frequency)
{
if (_softwareFilters.Where(p => p.Frequency == frequency).Any())
{
return;
}
SoftwareFilter softwareFilter = new SoftwareFilter(-1, frequency.ToString(), 'S', DateTime.Now, "", frequency, true);
foreach (var sf in _softwareFilters)
{
sf.IsDefault = false;
}
_softwareFilters.Add(softwareFilter);
Save();
SelectedFilterOption = new FilterClass(FilterClassType.AdHoc, frequency);
OnPropertyChanged("FilterOptions");
}
//Fb 13120 save the filters to db
public void Save()
{
foreach (var sf in _softwareFilters)
{
sf.Commit();
}
}
//FB 13120 identify the selected filter option to be used in combo box
public IFilterClass SelectedFilterOption
{
get
{
var softwareFilter = _softwareFilters.Find(p => p.IsDefault);
FilterClass fc = null;
if (softwareFilter?.Id == 1)
{
fc = new FilterClass(FilterClassType.Unfiltered);
}
else if (softwareFilter?.Id == 2)
{
fc = new FilterClass(FilterClassType.None);
}
else if (softwareFilter?.ISOCode == 'S')
{
fc = new FilterClass(FilterClassType.AdHoc, softwareFilter.Frequency);
}
else
{
foreach (var fct in Enum.GetValues(typeof(FilterClassType))
.Cast<FilterClassType>().ToArray())
{
if (fct == FilterClassType.AdHoc
|| fct == FilterClassType.CFC10)
{
continue;
}
if (fct.ToString() == softwareFilter?.Description.Replace(" ", ""))
{
fc = new FilterClass(fct);
break;
}
}
}
return fc;
}
set
{
if (value == null)
return;
foreach (var sf in _softwareFilters)
{
sf.IsDefault = false;
}
ISoftwareFilter softwareFilter = null;
if (value.FClass == FilterClassType.Unfiltered)
{
softwareFilter = _softwareFilters.Find(p => p.Id == 1);
}
else if (value.FClass == FilterClassType.None)
{
softwareFilter = _softwareFilters.Find(p => p.Id == 2);
}
else if (value.FClass == FilterClassType.AdHoc && !_softwareFilters.Where(p => p.Frequency == value.Frequency).Any())
{
_filterOptions.Add(new FilterClass(FilterClassType.AdHoc, value.Frequency));
_softwareFilters.Add(new SoftwareFilter(-1, value.Frequency.ToString(), 'S', DateTime.Now, "", value.Frequency, false));
softwareFilter = _softwareFilters.Find(p => p.Frequency == value.Frequency);
}
else
{
softwareFilter = _softwareFilters.Find(p => p.Frequency == value.Frequency);
}
softwareFilter.IsDefault = true;
OnPropertyChanged("SelectedFilterOption");
}
}
public static IAnalogDefaults GetAnalogDefaults()
{
return new AnalogSettingDefaults();
}
private List<IFilterClass> _filterOptions;
//FB 13120 available filter classes to be used in drop down
public List<IFilterClass> FilterOptions
{
get
{
if (null == _filterOptions)
{
var softwareFilters = SoftwareFilter.GetSoftwareFilters();
var customFilters = softwareFilters.Where(p => p.ISOCode == 'S');
_filterOptions = new List<IFilterClass>();
foreach (var fct in Enum.GetValues(typeof(FilterClassType))
.Cast<FilterClassType>().ToArray())
{
if (fct == FilterClassType.AdHoc
|| fct == FilterClassType.CFC10)
{
//Dont include until we can handle this type.
continue;
}
FilterClass fc = new FilterClass(fct);
_filterOptions.Add(fc);
}
foreach (var filter in customFilters)
{
FilterClass fc = new FilterClass(FilterClassType.AdHoc, filter.Frequency);
_filterOptions.Add(fc);
}
}
_filterOptions.Sort(CompareFilters);
return _filterOptions;
}
}
//FB 18727 UseMeasuredExcitation setting
public bool UseMeasuredExcitation
{
get
{
return SettingsDB.GetGlobalValueBool(Common.Constants.UseMeasuredExcitation, false);
}
set
{
SettingsDB.SetGlobalValueBoolean(Common.Constants.UseMeasuredExcitation, value);
OnPropertyChanged(Common.Constants.UseMeasuredExcitation);
}
}
public bool TrackAnalogDiagnosticsEnabled
{
get => DTS.Common.Storage.DbOperations.GetConnectionDbVersion() >= Common.Constants.TRACK_ANALOG_DIAGNOSTICS_DB_VERSION;
}
//http://manuscript.dts.local/f/cases/39148/DataPRO-Instrumentation-Tracking-Functions-FAA-Request-Diagnostics-Tracking
public bool TrackAnalogDiagnostics
{
get => TrackAnalogDiagnosticsEnabled && SettingsDB.GetGlobalValueBool(Common.Constants.TrackAnalogDiagnostics, false);
set
{
SettingsDB.SetGlobalValueBoolean(Common.Constants.TrackAnalogDiagnostics, value);
OnPropertyChanged(Common.Constants.TrackAnalogDiagnostics);
}
}
private static int CompareFilters(IFilterClass f1, IFilterClass f2)
{
if (f1 == null)
{
if (f2 == null)
{
// both null, equal
return 0;
}
// left null but not right
return -1;
}
if (f2 == null)
{
// left not null, right null
return 1;
}
if (f1.FClass != FilterClassType.None)
return f2.FClass == FilterClassType.None ? 1 : f1.Frequency.CompareTo(f2.Frequency);
if (f2.FClass == FilterClassType.None)
{
return 0;
}
return -1;
}
public bool Validate()
{
return true;
}
public void ReadXML(System.Xml.XmlElement root)
{
var frequency = 0D;
var fClass = FilterClassType.None;
foreach (var node in root.ChildNodes)
{
if (node is System.Xml.XmlElement nodex)
{
if (Enum.TryParse(nodex.Name, out FilterXMLFields field))
{
switch (field)
{
case FilterXMLFields.Frequency:
frequency = Convert.ToDouble(nodex.InnerText);
break;
case FilterXMLFields.FClass:
if (Enum.TryParse(nodex.InnerText, out FilterClassType filterClass))
{
fClass = filterClass;
}
break;
default:
throw new NotSupportedException(
"AnalogSettingDefaults::ReadXML unsupported field: " + field);
}
}
}
}
SelectedFilterOption = new FilterClass(fClass, frequency);
}
public void WriteXML(ref System.Xml.XmlWriter writer)
{
writer.WriteStartElement("AnalogSettingDefaults");
writer.WriteStartElement("SelectedFilterOption");
writer.WriteStartElement(FilterXMLFields.Frequency.ToString());
writer.WriteString(SelectedFilterOption.Frequency.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteEndElement();
writer.WriteStartElement(FilterXMLFields.FClass.ToString());
writer.WriteString(SelectedFilterOption.FClass.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
}
/// <summary>
/// restores digital input settings to defaults
/// </summary>
/// <param name="sensorDefaults"></param>
public static void RestoreDefaults(IAnalogDefaults sensorDefaults)
{
sensorDefaults.TrackAnalogDiagnostics = false;
}
}
public enum FilterXMLFields
{
FilterName,
Frequency,
FClass
}
}

View File

@@ -0,0 +1,983 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using DTS.Common.Classes.Sensors;
using DTS.DASLib.Service;
using System.ComponentModel;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
namespace DTS.SensorDB
{
#region Support classes and enums
public enum ShuntMode
{
None,
Emulation,
Internal,
External
}
public enum BridgeLeg
{
First,
Second,
Third,
Fourth
}
public class LowHigh : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, String propertyName = null)
{
if (Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public double Low { get; set; }
public double High { get; set; }
#region Tags
internal const string LowHighTag = "LowHigh";
internal const string LowTag = "Low";
internal const string HighTag = "High";
#endregion
private readonly string TableName;
internal LowHigh(XElement elem, string prefix, string tblName, string id)
{
TableName = tblName;
XElement inner = null;
try
{
inner = elem.Element(mkTag(prefix));
}
catch (ArgumentNullException)
{
if (!string.IsNullOrEmpty(id))
throw new Exception(string.Format("{0}: Can't find tag {1} for entry {2}", TableName, prefix + "-" + LowHighTag, id));
else
throw new Exception(string.Format("{0}: Can't find tag {1} in file", TableName, prefix + "-" + LowHighTag));
}
Low = double.Parse(inner.Attribute(LowTag).Value, System.Globalization.CultureInfo.InvariantCulture);
High = double.Parse(inner.Attribute(HighTag).Value, System.Globalization.CultureInfo.InvariantCulture);
}
public LowHigh(double _low, double _high)
{
Low = _low;
High = _high;
}
internal XElement ToXElement(string prefix)
{
var element = new XElement(mkTag(prefix));
element.SetAttributeValue(LowTag, Low);
element.SetAttributeValue(HighTag, High);
return element;
}
internal void Update(XElement elem, string prefix)
{
var element = elem.Element(mkTag(prefix));
element.SetAttributeValue(LowTag, Low);
element.SetAttributeValue(HighTag, High);
}
static internal string mkTag(string prefix)
{
return prefix + "-" + LowHighTag;
}
public string ToSerializeString()
{
return string.Format("{0},{1}", Low.ToString(System.Globalization.CultureInfo.InvariantCulture),
High.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
public LowHigh(string value)
{
string[] values = value.Split(new char[] { ',' });
if (values.Length < 2) { throw new InvalidDataException("invalid low-high: " + value); }
Low = double.Parse(values[0], System.Globalization.CultureInfo.InvariantCulture);
High = double.Parse(values[1], System.Globalization.CultureInfo.InvariantCulture);
}
}
#endregion
public class SensorDBTables
{
private const string CalibrationTag = "Calibration";
private const string CalibrationDateTag = "Date";
public SensorCalibration GetLatestCalibrationBySerialNumberSafe(string sensorSerNo)
{
var cals = from cal in Calibrations.Elements(SensorDBTables.CalibrationTag)
where ((string)cal.Element(SensorDBTables.SerialNumberTag)).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
orderby (DateTime)cal.Element(SensorDBTables.CalibrationDateTag) descending
select new SensorCalibration(cal);
if (null == cals || cals.Count() == 0) { return null; }
return cals.First();
}
public OutputTOMDigitalChannel[] GetTomsByDescription(string description)
{
var toms = from sensor in DigitalOutputChannels
where sensor.DigitalChannelDescription == description
select sensor;
return toms.ToArray();
}
protected System.Globalization.CultureInfo InvariantCulture = new System.Globalization.CultureInfo("");
public class EntryNotFoundException : System.Exception
{
public EntryNotFoundException(string msg)
: base(msg)
{
}
}
#region Filenames
internal const string ModelTableFilename = "Model.SensorDB.xml";
public const string DataTableFilename = "Data.SensorDB.xml";
public const string SensorTag = "Sensor";
public const string SerialNumberTag = "SerialNumber";
public const string IDTag = "ID";
internal const string CalibrationTableFilename = "Calibration.SensorDB.xml";
internal const string SquibTableFilename = "Data.SquibDB.xml";
internal const string DigitalOutputTableFilename = "Data.DigitalOut.xml";
#endregion
#region Our data storage
[Serializable()]
public class DigitalChannelList
{
public List<OutputTOMDigitalChannel> DigitalChannels { get; set; }
public DigitalChannelList(OutputTOMDigitalChannel[] channels)
{
DigitalChannels = new List<OutputTOMDigitalChannel>(channels);
}
public DigitalChannelList() { DigitalChannels = new List<OutputTOMDigitalChannel>(); }
}
[Serializable()]
public class SquibChannelList
{
public List<OutputSquibChannel> SquibChannels { get; set; }
public SquibChannelList(OutputSquibChannel[] channels)
{
SquibChannels = new List<OutputSquibChannel>(channels);
}
public SquibChannelList() { SquibChannels = new List<OutputSquibChannel>(); }
}
private List<OutputSquibChannel> _squibChannels = new List<OutputSquibChannel>();
public OutputSquibChannel[] SquibChannels
{
get { return _squibChannels.ToArray(); }
set { _squibChannels.Clear(); _squibChannels.AddRange(value); }
}
private List<OutputTOMDigitalChannel> _digitalChannels = new List<OutputTOMDigitalChannel>();
public OutputTOMDigitalChannel[] DigitalOutputChannels
{
get { return _digitalChannels.ToArray(); }
set { _digitalChannels.Clear(); _digitalChannels.AddRange(value); }
}
protected XElement Models { get; set; }
protected XElement Sensors { get; set; }
public XElement GetSensorsElement() { return Sensors; }
public SensorData[] GetSensorsBySerialNumber(string sensorSerNo)
{
var sensors = from sensor in Sensors.Elements(SensorTag)
where SensorData.IsValid(sensor) &&
((string)sensor.Element(SerialNumberTag)).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
orderby (string)sensor.Element(SerialNumberTag)
select new SensorData(sensor);
return sensors.ToArray();
}
protected XElement Calibrations { get; set; }
protected bool ModelsDirty { get; set; }
protected bool SensorsDirty { get; set; }
protected bool CalibrationsDirty { get; set; }
/// <summary>
/// Event generated whenever the tables are modified.
/// </summary>
public event EventHandler OnSensorDBModified;
#endregion
public string CurrentFolder { get; set; }
public SensorDBTables()
{
SetAllClean();
}
protected void SetAllClean()
{
ModelsDirty = false;
SensorsDirty = false;
CalibrationsDirty = false;
}
protected void TriggerSensorDBModified()
{
OnSensorDBModified?.Invoke(this, null);
}
/// <summary>
/// this function is designed to allow the Load function below to
/// load XML files without throwing exceptions when the files don't exist,
/// but create if Empty is true
/// 6/8/2010 - dtm
/// </summary>
/// <param name="fileLocation"></param>
/// <param name="createIfEmpty"></param>
/// <param name="defaultElement"></param>
/// <returns></returns>
private XElement LoadFile(string fileLocation, bool createIfEmpty, string defaultElement)
{
if (System.IO.File.Exists(fileLocation)) { return XElement.Load(fileLocation); }
else if (createIfEmpty) { return new XElement(defaultElement); }
throw new System.IO.FileNotFoundException(fileLocation);
}
private double _defaultAveZeroStart = SensorConstants.DefaultZeroMethodStart; // FB12764: Default in SensorConstants
public double DefaultAveZeroStart { get { return _defaultAveZeroStart; } set { _defaultAveZeroStart = value; } }
private double _defaultAveZeroStop = SensorConstants.DefaultZeroMethodEnd; // FB12764: Default in SensorConstants
public double DefaultAveZeroStop { get { return _defaultAveZeroStop; } set { _defaultAveZeroStop = value; } }
public void Load(string folder, bool createIfEmpty, string sifFolder,
double defaultPrepareAveZeroStart, double defaultPrepareAveZeroStop)
{
Load(folder, createIfEmpty, sifFolder, defaultPrepareAveZeroStart, defaultPrepareAveZeroStop, DataTableFilename);
}
public void Load(string folder, bool createIfEmpty, string sifFolder,
double defaultPrepareAveZeroStart, double defaultPrepareAveZeroStop, string datatableFileName)
{
_defaultAveZeroStart = defaultPrepareAveZeroStart;
_defaultAveZeroStop = defaultPrepareAveZeroStop;
CurrentFolder = folder;
//APILogger.Log(SensorModelCollection.GetSensorModels().GetNumberOfModels(), " sensor models loaded");
try
{
Sensors = LoadFile(string.Format("{0}\\{1}", folder, datatableFileName), createIfEmpty, SensorData.TOP_LEVEL_TAG);
}
catch (System.Exception ex)
{
if (!createIfEmpty) { throw ex; }
Sensors = new XElement(SensorData.TOP_LEVEL_TAG);
}
try
{
Calibrations = LoadFile(string.Format("{0}\\{1}", folder, CalibrationTableFilename), createIfEmpty, SensorCalibration.TOP_LEVEL_TAG);
}
catch (System.Exception ex)
{
if (!createIfEmpty) { throw ex; }
Calibrations = new XElement(SensorCalibration.TOP_LEVEL_TAG);
}
try
{
_digitalChannels.Clear();
string file = Path.Combine(folder, DigitalOutputTableFilename);
if (File.Exists(file))
{
using (FileStream fs = new FileStream(file, FileMode.Open))
{
System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(fs, settings);
reader.Read();
reader.ReadStartElement("DigitalChannelList");
reader.ReadStartElement("DigitalChannels");
while (reader.NodeType == System.Xml.XmlNodeType.Element)
{
OutputTOMDigitalChannel osc = new OutputTOMDigitalChannel(reader);
_digitalChannels.Add(osc);
}
reader.ReadEndElement();
reader.ReadEndElement();
}
}
}
catch (System.Exception)
{
_digitalChannels.Clear();
}
try
{
_squibChannels.Clear();
string file = Path.Combine(folder, SquibTableFilename);
if (File.Exists(file))
{
using (FileStream fs = new FileStream(file, FileMode.Open))
{
System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment;
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(fs, settings);
reader.Read();
reader.ReadStartElement("SquibChannelList");
reader.ReadStartElement("SquibChannels");
while (reader.NodeType == System.Xml.XmlNodeType.Element)
{
OutputSquibChannel osc = new OutputSquibChannel(reader);
_squibChannels.Add(osc);
}
reader.ReadEndElement();
reader.ReadEndElement();
}
}
}
catch (Exception)
{
//_squibChannels.Clear();
}
SetAllClean();
TriggerSensorDBModified();
}
private const string INVERT_DATA_TAG = "---- Invert Data - 0=no invert, 1=yes invert ----";
private const string ZERO_REFERENCE_TAG = "---- Zero Reference - 0=use 30 msec avg, 1=use prezero, 2=equals zero mV ----";
private const string CHANNEL_DESCRIPTION_TAG = "---- Channel Description ----";
private const string SERIAL_NUMBER_TAG = "---- Serial Number ----";
private const string OFFSET_LOW_TOLERANCE_TAG = "---- Offset Low Tol (mV) ----";
private const string OFFSET_HIGH_TOLERANCE_TAG = "---- Offset High Tol (mV) ----";
private const string CAL_MODE_TAG = "---- Cal Mode - I=Voltage Insertion, S=Shunt ----";
private const string CAL_STEP_TAG = "---- Cal Step - shunt resistor (Ohms) ----";
private const string SHUNT_VALUE_TAG = "---- Shunt Value - corresponding value of shunt resistor in Eng Units ----";
private const string PROPORTIONAL_TO_EXCITATION_TAG = "---- Proportional to Excitation ----";
private const string SENSITIVITY_TAG = "---- Sensitivity (mV/V/eng unit) ----";
private const string GAIN_TAG = "---- Gain - must be a valid gain from list ----";
private const string EXCITATION_TAG = "---- Excitation Voltage must be a valid voltage from list ----";
private const string ENG_UNIT_TAG = "---- Eng Unit ----";
private const string SOFTWARE_FILTER_TAG = "---- Software Filter, -3dB point (Hz) ----";
private const string DESIRED_MAX_RANGE_TAG = "---- Desired Max Range in Eng Units ----";
private const string CALIBRATION_DATE_TAG = "---- Calibration Date M_D_Y ----";
private const string REMOVE_NATURAL_OFFSET_TAG = "---- Remove Natural Sensor Offset? ----";
private const string INITIAL_EU_VALUE_TAG = "---- Initial EU Value ----";
private const string SENSOR_ID_TYPE_TAG = "---- Sensor ID Type ----";
private const string SENSOR_ID_NUMBER_TAG = "---- Sensor ID No ----";
private const string ISO_CODE_TAG = "---- ISO Code ----";
private const string EMPTY_ISO_CODE = "0000000000000000";
private const string EMPTY_SENSORID_TAG = "NONE";
private const string SENSOR_CATEGORY_TAG = "---- Sensor Category (Use 0 for most sensors) ----";
private const string SOFTWARE_VERSION_TAG = "Software Version: ";
public static void ProcessSif(string file, ref SensorData sd, ref SensorCalibration cal, double defaultAveWindowStart, double defaultAveWindowStop)
{
if (!File.Exists(file)) { throw new FileNotFoundException(file); }
using (StreamReader sr = new StreamReader(file, Encoding.Default))
{
sd = CreateDefaultSensor(0D, 0D);
sd.CheckOffset = true;
string line1 = sr.ReadLine();
string line2 = sr.ReadLine();
double sensitivity = 0D;
DateTime calibrationDate = DateTime.MinValue;
while (null != line1 && null != line2)
{
switch (line1)
{
case CHANNEL_DESCRIPTION_TAG:
sd.Comment = line2;
break;
case SERIAL_NUMBER_TAG:
sd.SerialNumber = line2;
break;
case OFFSET_LOW_TOLERANCE_TAG:
sd.OffsetToleranceLow = Convert.ToDouble(line2);
break;
case OFFSET_HIGH_TOLERANCE_TAG:
sd.OffsetToleranceHigh = Convert.ToDouble(line2);
break;
case CAL_MODE_TAG:
switch (line2[0])
{
case 'S'://this appears to just tell us Shunt or not, not what type?
//sd.Shunt = ShuntMode.Internal;
sd.Shunt = ShuntMode.Emulation;
break;
case 'I'://voltage insertion - apparently this is what you get
//if you click no shunt or have bridge resistance of 0?
sd.Shunt = ShuntMode.None;
break;
default:
throw new InvalidDataException("bad format cal mode position 0 " + line2);
}
switch (line2[1])
{
case 'D':
sd.Bridge = SensorConstants.BridgeType.FullBridge;
break;
case 'S':
sd.Bridge = SensorConstants.BridgeType.HalfBridge;
break;
default:
throw new InvalidDataException("bad format cal mode position 1 " + line2);
}
switch (line2[2])
{
case 'F':
sd.ByPassFilter = false;
break;
case 'B':
sd.ByPassFilter = true;
break;
default:
throw new InvalidDataException("bad format cal mode position 2" + line2);
}
break;
case CAL_STEP_TAG:
{
double value = Convert.ToDouble(line2);
if (value == 0D)
{
if (sd.Shunt != ShuntMode.None) { }
sd.ExternalShuntResistance = value;
}
else if (value == -1D)
{
if (sd.Shunt != ShuntMode.None) { }
sd.InternalShuntResistance = value;
}
else
{
if (sd.Shunt != ShuntMode.None) { }
sd.InternalShuntResistance = value;
}
}
break;
case SHUNT_VALUE_TAG:
sd.BridgeResistance = Convert.ToDouble(line2);
break;
case PROPORTIONAL_TO_EXCITATION_TAG:
cal.IsProportional = line2 == "Y";
break;
case SENSITIVITY_TAG:
{
string[] tokens = line2.Split(',');
sensitivity = Convert.ToDouble(tokens[0]);
if (tokens.Length > 1)
{
cal.Records.Records[0].Poly.LinearizationExponent = Convert.ToDouble(tokens[1]);
}
}
break;
case GAIN_TAG:
//not stored at all?
break;
case EXCITATION_TAG:
switch (line2)
{
case "5.0":
sd.SupportedExcitation = new ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Volt5 };
cal.Records.Records[0].Excitation = ExcitationVoltageOptions.ExcitationVoltageOption.Volt5;
break;
case "10.0":
sd.SupportedExcitation = new ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Volt10 };
cal.Records.Records[0].Excitation = ExcitationVoltageOptions.ExcitationVoltageOption.Volt10;
break;
case "0":
sd.SupportedExcitation = new ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Undefined };
cal.Records.Records[0].Excitation = ExcitationVoltageOptions.ExcitationVoltageOption.Undefined;
break;
case "2.5":
sd.SupportedExcitation = new ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Volt2_5 };
cal.Records.Records[0].Excitation = ExcitationVoltageOptions.ExcitationVoltageOption.Volt2_5;
break;
case "2.0":
sd.SupportedExcitation = new ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Volt2 };
cal.Records.Records[0].Excitation = ExcitationVoltageOptions.ExcitationVoltageOption.Volt2;
break;
case "3.0":
sd.SupportedExcitation = new ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Volt3 };
cal.Records.Records[0].Excitation = ExcitationVoltageOptions.ExcitationVoltageOption.Volt3;
break;
}
break;
case ENG_UNIT_TAG:
sd.DisplayUnit = line2;
break;
case SOFTWARE_FILTER_TAG:
sd.Filter = new FilterClass(Convert.ToDouble(line2));
break;
case INVERT_DATA_TAG:
switch (line2)
{
case "1":
sd.Invert = true;
break;
case "0":
sd.Invert = false;
break;
default:
throw new InvalidDataException(INVERT_DATA_TAG + " " + line2);
}
break;
case ZERO_REFERENCE_TAG:
switch (line2)
{
case "0":
//sd.OriginalZeroMethod = ZeroMethodType.AverageOverTime;
cal.ZeroMethods = new ZeroMethods(new ZeroMethod(ZeroMethodType.AverageOverTime, defaultAveWindowStart, defaultAveWindowStop));
break;
case "1":
//sd.OriginalZeroMethod = ZeroMethodType.UsePreEventDiagnosticsZero;
cal.ZeroMethods = new ZeroMethods(new ZeroMethod(ZeroMethodType.UsePreEventDiagnosticsZero, defaultAveWindowStart, defaultAveWindowStop));
break;
case "2":
//sd.OriginalZeroMethod = ZeroMethodType.None;
cal.ZeroMethods = new ZeroMethods(new ZeroMethod(ZeroMethodType.None, defaultAveWindowStart, defaultAveWindowStop));
//sd.Zero = new ZeroMethod( ZeroMethodType.UseZeroMv, _defaultAveZeroStart, _defaultAveZeroStop);
break;
default:
throw new InvalidDataException(ZERO_REFERENCE_TAG + " " + line2);
}
break;
case DESIRED_MAX_RANGE_TAG:
sd.Capacity = Convert.ToDouble(line2);
break;
case CALIBRATION_DATE_TAG:
{
string[] tokens = line2.Split('_');
if (tokens.Length == 3)
{
cal.CalibrationDate = new DateTime(Convert.ToInt32(tokens[2]), Convert.ToInt32(tokens[0]), Convert.ToInt32(tokens[1]));
cal.ModifyDate = DateTime.Now;
}
}
break;
case REMOVE_NATURAL_OFFSET_TAG:
cal.RemoveOffset = line2 == "Y";
break;
case INITIAL_EU_VALUE_TAG:
cal.InitialOffsets = new InitialOffsets(new InitialOffset(Convert.ToDouble(line2)));
//sd.InitialEU = Convert.ToDouble(line2);
break;
case SENSOR_ID_TYPE_TAG:
//always DALLAS
break;
case SENSOR_ID_NUMBER_TAG:
sd.EID = line2;
if (line2 == EMPTY_SENSORID_TAG) { sd.EID = ""; }
break;
case ISO_CODE_TAG:
sd.ISOCode = line2;
if (line2 == EMPTY_ISO_CODE) { sd.ISOCode = ""; }
break;
case SENSOR_CATEGORY_TAG:
sd.SensorCategory = Convert.ToInt32(line2);
break;
default:
if (line1.Contains(SOFTWARE_VERSION_TAG))
{
//ignored for now
}
else
{
throw new InvalidDataException("bad sif data: " + line1 + "-" + line2);
}
break;
}
line1 = sr.ReadLine();
line2 = sr.ReadLine();
}
sr.Close();
}
}
private void CreateDirectoryIfMissing(DirectoryInfo di)
{
if (!di.Parent.Exists)
{
CreateDirectoryIfMissing(di.Parent);
}
if (!di.Exists) { di.Create(); }
}
#region Model functions
/*public void Add(SensorModel newModel)
{
ModelsDirty = true;
SensorModelCollection.GetSensorModels().AddSensorModel(newModel);
}
*/
/*public void Delete(SensorModel model)
{
if(model == null)
{
// "SensorDBTables.Delete(SensorModel): model is null"
throw new ArgumentException(Strings.SensorDBTables_Delete_SensorModel_Err1);
}
if(string.IsNullOrEmpty(model.Model))
{
// "SensorDBTables.Delete(SensorModel): model.Model is null"
throw new ArgumentException(Strings.SensorDBTables_Delete_SensorModel_Err2);
}
ModelsDirty = true;
SensorModelCollection.GetSensorModels().DeleteSensorModel(model);
}
*/
/// <summary>
/// Update the data for this sensor model. If it doesn't exist, we'll add it
/// </summary>
/// <param name="sensor">The new sensor model data</param>
/*public void Update(SensorModel model)
{
SensorModelCollection.GetSensorModels().UpdateSensorModel(model);
ModelsDirty = true;
}*/
/*
public SensorModel[] GetModelsByManufacturer(string manufacturer)
{
return SensorModelCollection.GetSensorModels().GetSensorModelsForManufacturer(manufacturer);
}
*/
/*
public string[] GetUniqueManufacturers()
{
return SensorModelCollection.GetSensorModels().GetUniqueManufacturers();
}
*/
#endregion
#region Data functions
public static SensorData CreateDefaultSensor(double defaultAveStart, double defaultAveEnd)
{
SensorData sensor = new SensorData();
sensor.Bridge = SensorConstants.BridgeType.FullBridge;
sensor.BridgeLegMode = BridgeLeg.First;
sensor.BridgeResistance = 100;
sensor.Capacity = 0;
sensor.CheckOffset = false;
sensor.Comment = "";
sensor.Created = DateTime.Now;
sensor.ExternalShuntResistance = 0;
sensor.Filter = new FilterClass(FilterClassType.CFC1000);
sensor.EID = "";
//sensor.InitialEU = 0;
sensor.InternalShuntResistance = 0;
sensor.Invert = false;
sensor.ISOCode = "";
sensor.DisplayUnit = "";
sensor.Model = "";
sensor.OffsetToleranceLow = SensorConstants.DefaultBridgeOffsetMVTolLow;
sensor.OffsetToleranceHigh = SensorConstants.DefaultBridgeOffsetMVTolHigh;
//sensor.OffsetTolerance = new LowHigh(-100, 100);
sensor.SerialNumber = "";
sensor.Shunt = ShuntMode.None;
sensor.CalSignal = false;
sensor.Status = SensorStatus.Available;
sensor.TimesUsed = 0;
sensor.UserSerialNumber = "";
sensor.DiagnosticsMode = false;
sensor.UserValue1 = "";
sensor.UserValue2 = "";
sensor.UserValue3 = "";
sensor.CouplingMode = SensorConstants.CouplingModes.DC;
sensor.CheckCalibrationSignal = false;
return sensor;
}
public SensorData[] GetAllSensors()
{
if (null == Sensors) { return new SensorData[0]; }
var sensors = from sensor in Sensors.Elements(SensorData.SENSOR_TAG)
where SensorData.IsValid(sensor)
//orderby (string)sensor.Element(SensorData.SensorXMLFields.SerialNumber.ToString())
select new SensorData(sensor);
List<SensorData> list = new List<SensorData>(sensors.ToArray());
list.Sort();
return list.ToArray();
}
#endregion
#region Calibration functions
/*
public void Add(SensorCalibration newCal)
{
if(newCal == null)
{
// "SensorDBTables.Add(SensorCalibration): newCal is null"
throw new ArgumentException(Strings.SensorDBTables_Add_SensorCalibration_Err1);
}
if(string.IsNullOrEmpty(newCal.SerialNumber))
{
// "SensorDBTables.Add(SensorCalibration): newCal.SerialNumber is null"
throw new ArgumentException(Strings.SensorDBTables_Add_SensorCalibration_Err2);
}
// make sure the sensor serial number exist
var sensors = GetRawSensorsBySerialNumber(newCal.SerialNumber);
if(sensors == null || sensors.Count() == 0)
{
// "SensorDBTables.Add(SensorCalibration): newCal.SerialNumber({0}) doesn't exist"
throw new ArgumentException(string.Format(Strings.SensorDBTables_Add_SensorCalibration_Err3, newCal.SerialNumber));
}
// looks good, add it
Calibrations.Add(newCal.ToXElement());
CalibrationsDirty = true;
}*/
/*
public void Delete(String serialNumber)
{
if (null == serialNumber) { throw new ArgumentException(Strings.SensorDBTables_Delete_SensorCalibration_Err2); }
XElement [] xes = GetRawCalibrationsBySerialNumber(serialNumber);
if (null != xes && xes.Length > 0)
{
foreach (XElement xe in xes)
{
xe.Remove();
}
}
CalibrationsDirty = true;
}
*/
/*
public void Delete(SensorCalibration calib)
{
if(calib == null)
{
// "SensorDBTables.Delete(SensorCalibration): calib is null"
throw new ArgumentException(Strings.SensorDBTables_Delete_SensorCalibration_Err1);
}
if(string.IsNullOrEmpty(calib.SerialNumber))
{
// "SensorDBTables.Delete(SensorCalibration): calib.SerialNumber is null"
throw new ArgumentException(Strings.SensorDBTables_Delete_SensorCalibration_Err2);
}
var foundCals = GetRawCalibrationsBySerialNumberAndDate(calib.SerialNumber, calib.CalibrationDate);
// first check if we found something
if(foundCals == null || foundCals.Count() == 0)
{
// no, consider it deleted
return;
}
// OK, delete this one
foreach(var xe in foundCals)
{
xe.Remove();
}
CalibrationsDirty = true;
}
*/
/*
/// <summary>
/// Update the data for this sensor. If it doesn't exist, we'll add it
/// </summary>
/// <param name="sensor">The new sensor calibration data</param>
public void Update(SensorCalibration calib)
{
if(calib == null)
{
// "SensorDBTables.Update(SensorCalibration): calib is null"
throw new ArgumentException(Strings.SensorDBTables_Update_SensorCalibration_Err1);
}
if(string.IsNullOrEmpty(calib.SerialNumber))
{
// "SensorDBTables.Update(SensorCalibration): calib.SerialNumber is null"
throw new ArgumentException(Strings.SensorDBTables_Update_SensorCalibration_Err2);
}
var foundCals = GetRawCalibrationsBySerialNumberAndDate(calib.SerialNumber, calib.CalibrationDate);
// first check if we found something
if(foundCals == null || foundCals.Count() == 0)
{
// no, we'll add it
Add(calib);
return;
}
// if we got more than 1 it's trouble
if(foundCals.Count() > 1)
{
// SensorDBTables.Update(SensorCalibration): Calibrations table is corrupt, there's more than one entry with same SerialNumber and date
throw new System.Exception(Strings.SensorDBTables_Update_SensorCalibration_Err3);
}
// OK, update this one
foreach(var xe in foundCals)
{
// replace all except serial number and date (our keys)
xe.SetElementValue(SensorCalibration.DocumentIDTag, calib.DocumentID);
xe.SetElementValue(SensorCalibration.ExcitationTag, calib.Excitation.ToString());
xe.SetElementValue(SensorCalibration.MeasurementUnitTag, calib.MeasurementUnit);
xe.SetElementValue(SensorCalibration.SensitivityTag, calib.Sensitivity);
xe.SetElementValue(SensorCalibration.UsernameTag, calib.Username);
xe.SetElementValue(SensorCalibration.ZmoTag, calib.Zmo);
xe.SetElementValue(SensorCalibration.PolyTag, calib.Poly.ToSerializeString());
}
CalibrationsDirty = true;
}
*/
/*
protected XElement[] GetRawCalibrationsBySerialNumber(string sensorSerNo)
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.SerialNumberTag)).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
select cal;
return cals.ToArray();
}
*/
/*
protected IEnumerable<XElement> GetRawCalibrationsBySerialNumberAndDate(string sensorSerNo, DateTime ts)
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.SerialNumberTag)).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase) &&
(DateTime)cal.Element(SensorCalibration.CalibrationDateTag) == ts
select cal;
return cals;
}
*/
public SensorCalibration[] GetAllCalibrations()
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CALIBRATION_TAG) select new SensorCalibration(cal);
return cals.ToArray();
}
/*
public SensorCalibration[] GetCalibrationsBySerialNumber(string sensorSerNo)
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.XMLFields.SerialNumber.ToString())).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
orderby (DateTime)cal.Element(SensorCalibration.XMLFields.Date.ToString())
select new SensorCalibration(cal);
return cals.ToArray();
}
public SensorCalibration GetLatestCalibrationBySerialNumberSafe(string sensorSerNo)
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.XMLFields.SerialNumber.ToString())).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
orderby (DateTime)cal.Element(SensorCalibration.XMLFields.Date.ToString()) descending
select new SensorCalibration(cal);
if (null == cals || cals.Count() == 0) { return null; }
return cals.First();
}
public SensorCalibration GetLatestCalibrationBySerialNumber(string sensorSerNo)
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.XMLFields.SerialNumber.ToString())).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
orderby (DateTime)cal.Element(SensorCalibration.XMLFields.Date.ToString()) descending
select new SensorCalibration(cal);
if (null == cals || cals.Count() == 0)
{
throw new EntryNotFoundException("no calibrations for " + sensorSerNo);
}
return cals.First();
}
*/
/*
public double GetLatestSensitivityBySerialNumber(string sensorSerNo)
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.SerialNumberTag)).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
orderby (DateTime)cal.Element(SensorCalibration.CalibrationDateTag) descending
select double.Parse((string)cal.Element(SensorCalibration.SensitivityTag), InvariantCulture);
if (cals == null || cals.Count() == 0)
{
throw new EntryNotFoundException(string.Format(Strings.SensorDBTables_GetLatestSensitivityBySerialNumber_Err1, sensorSerNo));
}
return cals.First();
}
*/
/*
public double? GetLatestSensitivityBySerialNumberSafe(string sensorSerNo)
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.SerialNumberTag)).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
orderby (DateTime)cal.Element(SensorCalibration.CalibrationDateTag) descending
select double.Parse((string)cal.Element(SensorCalibration.SensitivityTag), InvariantCulture);
if (cals == null || cals.Count() == 0)
{
return null;
}
return cals.First();
}
*/
/*
public string GetLatestPolyBySerialNumberSafe(string sensorSerNo)
{
try
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.SerialNumberTag)).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase)
orderby (DateTime)cal.Element(SensorCalibration.CalibrationDateTag) descending
select cal.Element(SensorCalibration.PolyTag);
if (cals == null || cals.Count() == 0)
{
return null;
}
return (string)(cals.First());
}
catch (System.Exception)
{
return null;
}
}
*/
/*
public SensorCalibration GetCalibrationBySerialNumberAndDate(string sensorSerNo, DateTime ts)
{
var cals = from cal in Calibrations.Elements(SensorCalibration.CalibrationTag)
where ((string)cal.Element(SensorCalibration.SerialNumberTag)).Equals(sensorSerNo, StringComparison.OrdinalIgnoreCase) &&
(DateTime)cal.Element(SensorCalibration.CalibrationDateTag) == ts
select new SensorCalibration(cal);
// make sure we only got one
if(cals != null && cals.Count() > 1)
{
// "SensorDBTables.GetCalibrationBySerialNumberAndDate: Duplicate entries for {0} and {1}"
throw new System.Exception(string.Format(Strings.SensorDBTables_GetCalibrationBySerialNumberAndDate_Err1, sensorSerNo, ts.ToString("o")));
}
if(cals.Count() == 0)
return null;
return cals.ToArray()[0];
}
*/
#endregion
}
}

View File

@@ -0,0 +1,239 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{444EF10C-046E-47AD-A9A5-17318D488723}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DTS.SensorDB</RootNamespace>
<AssemblyName>SensorDB</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkProfile />
<SccProjectName>
</SccProjectName>
<SccLocalPath>
</SccLocalPath>
<SccAuxPath>
</SccAuxPath>
<SccProvider>
</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Xaml.Behaviors">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Microsoft.Xaml.Behaviors.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="Prism">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Prism.dll</HintPath>
</Reference>
<Reference Include="Prism.Unity.Wpf">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Prism.Unity.Wpf.dll</HintPath>
</Reference>
<Reference Include="Prism.Wpf">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Prism.Wpf.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Windows" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Unity.Abstractions">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Unity.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Unity.Container">
<HintPath>..\..\Common\DTS.Common\lib\PrismLibrary\Unity.Container.dll</HintPath>
</Reference>
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="AnalogSettingDefaults.cs" />
<Compile Include="CalibrationPolicy.cs" />
<Compile Include="CANSetting.cs" />
<Compile Include="CanSettingDefaults.cs" />
<Compile Include="DigitalInputSensorDefault.cs" />
<Compile Include="DigitalInputSetting.cs" />
<Compile Include="DigitalOutputDefaults.cs" />
<Compile Include="FactorySensorModel.cs" />
<Compile Include="IEPESensorDefault.cs" />
<Compile Include="OffsetToleranceChange.cs" />
<Compile Include="SensorCalibrationList.cs" />
<Compile Include="SensorInformationFile.cs" />
<Compile Include="SensorMerge.cs" />
<Compile Include="SoftwareFilter.cs" />
<Compile Include="SquibSettingDefaults.cs" />
<Compile Include="StreamInputSetting.cs" />
<Compile Include="StreamInputSettingDefaults.cs" />
<Compile Include="StreamOutputSetting.cs" />
<Compile Include="StreamOutputSettingDefaults.cs" />
<Compile Include="StringResources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>StringResources.resx</DependentUpon>
</Compile>
<Compile Include="TDCINI\INIDataZeroTimeWindowSeconds.cs" />
<Compile Include="TDCINI\INIIIHSExport.cs" />
<Compile Include="TDCINI\INIISOExportParameters.cs" />
<Compile Include="TDCINI\INIRackInventory.cs" />
<Compile Include="TDCINI\INISmartBatteryThresholds.cs" />
<Compile Include="TDCINI\INIViewerROI.cs" />
<Compile Include="TDCINI\TDCINIError.cs" />
<Compile Include="TDCINI\TDCINIRS232Info.cs" />
<Compile Include="TDCINI\TSFINIRegionOfInterest.cs" />
<Compile Include="TDM\TDMCSVImport.cs" />
<Compile Include="ThermocouplerSetting.cs" />
<Compile Include="TSF\G5DigitalInputChannelTSFEntry.cs" />
<Compile Include="TSF\ReadTSFError.cs" />
<Compile Include="TSF\TOMChannelInformationSection.cs" />
<Compile Include="TSF\TSFCalculatedChannelEntry.cs" />
<Compile Include="TSF\TSFCalculatedChannelInformationSection.cs" />
<Compile Include="TSF\TSFChannel.cs" />
<Compile Include="TSF\TSFDigitalChannel.cs" />
<Compile Include="TSF\TSFDIMEntry.cs" />
<Compile Include="TSF\TSFDIMSection.cs" />
<Compile Include="TSF\TSFFile.cs" />
<Compile Include="TSF\TSFG5DigitalInputSection.cs" />
<Compile Include="TDCINI\TDCINIFile.cs" />
<Compile Include="TSF\TSFInputChannelDescription.cs" />
<Compile Include="IsoCode.cs" />
<Compile Include="MeasurementUnit.cs" />
<Compile Include="SensorCalibration.cs" />
<Compile Include="SensorData.cs" />
<Compile Include="SensorDB.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SensorDBBase.cs" />
<Compile Include="SensorModel.cs" />
<Compile Include="SensorRange.cs" />
<Compile Include="SensorsCollection.cs" />
<Compile Include="SquibSetting.cs" />
<Compile Include="Strings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Strings.resx</DependentUpon>
</Compile>
<Compile Include="DigitalOutputSetting.cs" />
<Compile Include="TSF\TSFCalibrationInformation.cs" />
<Compile Include="TSF\TSFChannelDescription.cs" />
<Compile Include="TSF\TSFModuleDescription.cs" />
<Compile Include="TSF\TSFModuleInformationSection.cs" />
<Compile Include="TSF\TSFOutputChannelDescription.cs" />
<Compile Include="TSF\TSFRackDescription.cs" />
<Compile Include="TSF\TSFRackInformationSection.cs" />
<Compile Include="TSF\TSFSamplingInformationSection.cs" />
<Compile Include="TSF\TSFSensorChannelInformationSection.cs" />
<Compile Include="TSF\TSFSensorEntry.cs" />
<Compile Include="TSF\TSFSquibFireEntry.cs" />
<Compile Include="TSF\TSFSystemDescription.cs" />
<Compile Include="TSF\TSFTCFSection.cs" />
<Compile Include="UartSetting.cs" />
<Compile Include="UartSettingDefaults.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="StringResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>StringResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Include="Strings.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Strings.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Common\DTS.Common.DAS.Concepts\DTS.Common.DAS.Concepts.csproj">
<Project>{ae3987f7-c4c6-40fb-a353-1a2dadef7a9a}</Project>
<Name>DTS.Common.DAS.Concepts</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\DTS.Common.SettingsDB\DTS.Common.Settings.csproj">
<Project>{61017104-d8ee-41d1-b9ca-dad863ff78b2}</Project>
<Name>DTS.Common.Settings</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\DTS.Common.Storage\DTS.Common.Storage.csproj">
<Project>{e3be457c-0ac7-4a9c-bc81-eafeb3217878}</Project>
<Name>DTS.Common.Storage</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\DTS.Common.Utilities\DTS.Common.Utilities.csproj">
<Project>{d6da1b74-c711-43c2-91b1-1908a8d04dbf}</Project>
<Name>DTS.Common.Utilities</Name>
</ProjectReference>
<ProjectReference Include="..\..\Common\DTS.Common\DTS.Common.csproj">
<Project>{f7a0804f-61a4-40ae-83d0-f1137622b592}</Project>
<Name>DTS.Common</Name>
</ProjectReference>
<ProjectReference Include="..\IService\IService.csproj">
<Project>{C9C45B72-05A3-4962-BC13-A78B1F4B1925}</Project>
<Name>IService</Name>
<Private>False</Private>
</ProjectReference>
<ProjectReference Include="..\Users\Users.csproj">
<Project>{be8d217d-6da9-4bca-b62a-a82325b33979}</Project>
<Name>Users</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="Design\SensorDBClassDiagram.cd" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// helper class for ViewerROI section of ROI
/// </summary>
public class INIViewerROI
{
/// <summary>
/// x Min value
/// </summary>
public double XMin { get; set; }
/// <summary>
/// x Max value
/// </summary>
public double XMax { get; set; }
/// <summary>
/// reads section from a line
/// returns false if failed to read section, true if section was read.
/// </summary>
/// <param name="line"></param>
/// <param name="curLine"></param>
/// <param name="errors"></param>
/// <returns></returns>
public bool ReadFrom(string line, int curLine, ref List<TDCINIError> errors)
{
string[] tokens = line.Split(new char[] { ',' });
if (2 != tokens.Length)
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ViewerROI_INVALID, line, curLine));
return false;
}
double d;
if (!double.TryParse(tokens[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ViewerROI_INVALID, tokens[0], curLine));
return false;
}
else { XMin = d; }
if (!double.TryParse(tokens[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out d))
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ViewerROI_INVALID, tokens[1], curLine));
return false;
}
else { XMax = d; }
return true;
}
}
}

View File

@@ -0,0 +1,100 @@
using System;
using System.Xml.Linq;
using System.ComponentModel;
namespace DTS.SensorDB
{
public class SensorRange : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, String propertyName = null)
{
if (Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public double Low { get; set; }
public double Medium { get; set; }
public double High { get; set; }
#region Tags
internal const string SensorRangeTag = "SensorRange";
internal const string LowTag = "Low";
internal const string MediumTag = "Medium";
internal const string HighTag = "High";
#endregion
public SensorRange(string value)
{
var values = value.Split(',');
if (3 != values.Length) { throw new System.IO.InvalidDataException("bad SensorRange, " + value); }
Low = double.Parse(values[0]);
Medium = double.Parse(values[1]);
High = double.Parse(values[2]);
}
public string ToSerializeString()
{
return $"{Low.ToString(System.Globalization.CultureInfo.InvariantCulture)},{Medium.ToString(System.Globalization.CultureInfo.InvariantCulture)},{High.ToString(System.Globalization.CultureInfo.InvariantCulture)}";
}
private string TableName;
internal SensorRange(XElement elem, string prefix, string tblName, string id)
{
TableName = tblName;
XElement inner = null;
try
{
inner = elem.Element(mkTag(prefix));
}
catch (ArgumentNullException)
{
if (!string.IsNullOrEmpty(id))
throw new Exception($"{TableName}: Can't find tag {prefix + "-" + SensorRangeTag} for entry {id}");
throw new Exception($"{TableName}: Can't find tag {prefix + "-" + SensorRangeTag} in file");
}
Low = Double.Parse(inner.Attribute(LowTag).Value, System.Globalization.CultureInfo.InvariantCulture);
Medium = Double.Parse(inner.Attribute(MediumTag).Value, System.Globalization.CultureInfo.InvariantCulture);
High = Double.Parse(inner.Attribute(HighTag).Value, System.Globalization.CultureInfo.InvariantCulture);
}
public SensorRange(double low, double medium, double high)
{
Low = low;
Medium = medium;
High = high;
}
internal XElement ToXElement(string prefix)
{
var element = new XElement(mkTag(prefix));
element.SetAttributeValue(LowTag, Low);
element.SetAttributeValue(MediumTag, Medium);
element.SetAttributeValue(HighTag, High);
return element;
}
internal void Update(XElement elem, string prefix)
{
var element = elem.Element(mkTag(prefix));
if (element == null) return;
element.SetAttributeValue(LowTag, Low);
element.SetAttributeValue(MediumTag, Medium);
element.SetAttributeValue(HighTag, High);
}
internal static string mkTag(string prefix)
{
return prefix + "-" + SensorRangeTag;
}
}
}

View File

@@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// the G5 Digital Input Channels section of the TSF
/// </summary>
public class TSFG5DigitalInputSection
{
private const string SECTION_START_HEADER = "---- G5 Digital Input Channels Begin ----";
private const string COLUMN_HEADER = "datachan,rack,mod,chan,descrip,ISOCode,scale,invert";
private const string SECTION_END_HEADER = "---- G5 Digital Input Channels End ----";
private List<G5DigtalInputChannelTSFEntry> _digitalInputChannels = new List<G5DigtalInputChannelTSFEntry>();
public G5DigtalInputChannelTSFEntry[] DigitalInputChannels
{
get { return _digitalInputChannels.ToArray(); }
set { _digitalInputChannels = new List<G5DigtalInputChannelTSFEntry>(value); }
}
public void ReadFrom(List<string> lines, ref int currentLine, ref List<ReadTSFError> errors)
{
if (currentLine == lines.Count)
{
//errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string sectionStart = lines[currentLine++];
if (sectionStart != SECTION_START_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.G5DIGITALINPUTSECTION_START_INVALID_HEADER, currentLine, sectionStart));
return;
}
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string columnHeader = lines[currentLine++];
if (columnHeader != COLUMN_HEADER)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.G5DIGITALINPUTSECTION_COLUMN_INVALID_HEADER, currentLine, columnHeader));
return;
}
List<G5DigtalInputChannelTSFEntry> g5DigitalInputChannels = new List<G5DigtalInputChannelTSFEntry>();
bool done = false;
while (!done)
{
if (currentLine == lines.Count)
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_UNEXPECTED_EOF, currentLine));
return;
}
string line = lines[currentLine++];
if (!line.Contains("G5 Digital Input Channels End"))
{
G5DigtalInputChannelTSFEntry ichan = new G5DigtalInputChannelTSFEntry();
string[] tokens = line.Split(new char[] { ',' });
for (int iCurField = 0; iCurField < tokens.Length; iCurField++)
{
string s = tokens[iCurField];
G5DigtalInputChannelTSFEntry.Fields field = (G5DigtalInputChannelTSFEntry.Fields)iCurField;
switch (field)
{
case G5DigtalInputChannelTSFEntry.Fields.chan:
try { ichan.Chan = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_G5DIGITALCHANNEL_INVALID_CHAN, currentLine, s)); }
break;
case G5DigtalInputChannelTSFEntry.Fields.datachan:
try { ichan.DataChan = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_G5DIGITALCHANNEL_INVALID_DATACHAN, currentLine, s)); }
break;
case G5DigtalInputChannelTSFEntry.Fields.descrip: ichan.Descripton = s; break;
case G5DigtalInputChannelTSFEntry.Fields.invert:
try
{
switch (s)
{
case "0":
case "F":
case "N":
ichan.Invert = false; break;
case "1":
case "T":
case "Y":
ichan.Invert = true; break;
default:
{
errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_G5DIGITALCHANNEL_INVALID_INVERT, currentLine, s));
}
break;
}
}
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_G5DIGITALCHANNEL_INVALID_INVERT, currentLine, s)); }
break;
case G5DigtalInputChannelTSFEntry.Fields.ISOCode: ichan.ISOCode = s; break;
case G5DigtalInputChannelTSFEntry.Fields.mod:
try { ichan.Module = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_G5DIGITALCHANNEL_INVALID_MODULE, currentLine, s)); }
break;
case G5DigtalInputChannelTSFEntry.Fields.rack:
try { ichan.Rack = Convert.ToInt32(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_G5DIGITALCHANNEL_INVALID_RACK, currentLine, s)); }
break;
case G5DigtalInputChannelTSFEntry.Fields.scale:
try { ichan.Scale = Convert.ToDouble(s); }
catch (System.Exception) { errors.Add(new ReadTSFError(ReadTSFError.TSF_ERRORS.TSF_G5DIGITALCHANNEL_INVALID_SCALE, currentLine, s)); }
break;
default: throw new NotSupportedException("TSFFile::ReadTSF invalid G5DigitalInput field: " + field.ToString());
}
}
g5DigitalInputChannels.Add(ichan);
}
else { done = true; }
}
DigitalInputChannels = g5DigitalInputChannels.ToArray();
}
}
}

View File

@@ -0,0 +1,183 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TDCINI
{
/// <summary>
/// helper class for ISO Export section of INI
/// </summary>
public class INIISOExportParameters
{
/// <summary>
/// whether to automatically export ISO on download
/// </summary>
public bool AutomaticISOExportOnDownload { get; set; }
/// <summary>
/// the MME header template (empty if none)
/// </summary>
public string MMEHeaderTemplateFilename { get; set; }
/// <summary>
/// whether to prompt the user for MME header template file or not
/// </summary>
public bool PromptUserForMMETemplateFilename { get; set; }
/// <summary>
/// channel header template (empty if none)
/// </summary>
public string ChannelHeaderTemplateFilename { get; set; }
/// <summary>
/// whether to prompt the user for a channel header template file
/// </summary>
public bool PromptUserForChannelHeaderFilename { get; set; }
public enum FilterOutputOptions
{
UnFiltered = 0,
Filtered = 1,
PromptUser = 2
}
/// <summary>
/// what type of output is desired
/// </summary>
public FilterOutputOptions FilterOutput { get; set; }
/// <summary>
/// whether to supress the export completion dialog
/// </summary>
public bool SuppressExportCompletionDialog { get; set; }
/// <summary>
/// dummy template file (empty if none)
/// </summary>
public string DummyTemplateFilename { get; set; }
/// <summary>
/// whether to prompt the user for dummy template file or not
/// </summary>
public bool PromptUserForDummyTemplateFilename { get; set; }
/// <summary>
/// reads settings from a line
/// returns true if successful or false if not
/// </summary>
/// <param name="line"></param>
/// <param name="curLine"></param>
/// <param name="errors"></param>
/// <returns></returns>
public bool ReadFrom(string line, int curLine, ref List<TDCINIError> errors)
{
string[] tokens = line.Split(new char[] { ',' });
if (tokens.Length != 9)
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ISOEXPORTPARAMETERS_INVALID, line, curLine));
return false;
}
switch (tokens[0])
{
case "0":
case "F":
case "N":
AutomaticISOExportOnDownload = false;
break;
case "1":
case "T":
case "Y":
AutomaticISOExportOnDownload = true;
break;
default:
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ISOEXPORTPARAMETERS_INVALID, tokens[0], curLine));
return false;
}
}
MMEHeaderTemplateFilename = tokens[1];
switch (tokens[2])
{
case "0":
case "F":
case "N":
PromptUserForMMETemplateFilename = false;
break;
case "1":
case "T":
case "Y":
PromptUserForMMETemplateFilename = true;
break;
default:
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ISOEXPORTPARAMETERS_INVALID, tokens[2], curLine));
return false;
}
}
ChannelHeaderTemplateFilename = tokens[3];
switch (tokens[4])
{
case "0":
case "F":
case "N":
PromptUserForChannelHeaderFilename = false;
break;
case "1":
case "T":
case "Y":
PromptUserForChannelHeaderFilename = true;
break;
default:
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ISOEXPORTPARAMETERS_INVALID, tokens[4], curLine));
return false;
}
}
switch (tokens[5])
{
case "0": FilterOutput = FilterOutputOptions.UnFiltered; break;
case "1": FilterOutput = FilterOutputOptions.Filtered; break;
case "2": FilterOutput = FilterOutputOptions.PromptUser; break;
default:
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ISOEXPORTPARAMETERS_INVALID, tokens[5], curLine));
return false;
}
}
switch (tokens[6])
{
case "0":
case "F":
case "N":
SuppressExportCompletionDialog = false; break;
case "1":
case "T":
case "Y":
SuppressExportCompletionDialog = true; break;
default:
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ISOEXPORTPARAMETERS_INVALID, tokens[6], curLine));
return false;
}
}
DummyTemplateFilename = tokens[7];
switch (tokens[8])
{
case "0":
case "F":
case "N":
PromptUserForDummyTemplateFilename = false; break;
case "1":
case "T":
case "Y":
PromptUserForDummyTemplateFilename = true; break;
default:
{
errors.Add(new TDCINIError(TDCINIError.INIErrors.INI_ISOEXPORTPARAMETERS_INVALID, tokens[8], curLine));
return false;
}
}
return true;
}
}
}

View File

@@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// helper class to help returning errors while reading Test Setup Files (TSF)
/// this is to make it easier to handle translations.
/// </summary>
public class ReadTSFError
{
/// <summary>
/// these are all the possible errors returned by ReadTSF
/// </summary>
public enum TSF_ERRORS
{
TSF_FILE_NOT_FOUND,
TSF_FILE_IO_ERROR,
TSFFILE_INCOMPLETE,
TSF_INVALID_VERSION,
TSF_OLD_FILE_VERSION,
TSF_UNEXPECTED_EOF,
TSF_INCOMPLETE_SAMPLING_SECTION,
TSF_INVALID_SAMPLERATE,
TSF_INVALID_PRETRIGGER_TIME,
TSF_INAVLID_POSTTRIGGER_TIME,
TSF_INVALID_AAF,
TSF_SKIPPED_RACK_ENTRY_INCOMPLETE,
TSF_RACK_ENTRY_INVALID_RACK_VALUE,
TSF_RACK_ENTRY_INVALID_ISO_POSITION,
RACK_ENTRY_IWALLTEST_ITROLLEY_FUNCTIONALITY,
RACK_ENTRY_ITROLLEYTEST_IWALL_FUNCTIONALITY,
RACK_ENTRY_INVALID_RACK_INDEX,
RACK_ENTRY_INVALID_EMPTYRACK,
TSF_SKIPPING_MODULE_TOO_FEW_TOKENS,
TSF_MODULE_INVALID_RACK_FIELD,
TSF_MODULE_INVALID_MODULE_FIELD,
TSF_MODULE_INVALID_TRIGGERMODE_FIELD,
TSF_MODULE_INVALID_TRIGGERCHAN_FIELD,
TSF_MODULE_INVALID_TRIGGERDIR_FIELD,
TSF_MODULE_INVALID_TRIGGERLEVEL_FIELD,
TSF_MODULE_INVALID_MODULETYPE_FIELD,
TSF_MODULE_SKIPPED_RACKNOTFOUND,
TSF_SENSORCHANNEL_INVALID_C0,
TSF_SENSORCHANNEL_INVALID_C1,
TSF_SENSORCHANNEL_INVALID_C2,
TSF_SENSORCHANNEL_INVALID_C3,
TSF_SENSORCHANNEL_INVALID_C4,
TSF_SENSORCHANNEL_INVALID_C5,
TSF_SENSORCHANNEL_INVALID_CALDATE,
TSF_SENSORCHANNEL_INVALID_CALSTEP,
TSF_SENSORCHANNEL_INVALID_CHAN,
TSF_SENSOR_CHANNEL_INVALID_DATACHAN,
TSF_SENSOR_CHANNEL_INVALID_DESIREDMAXRANGE,
TSF_SENSOR_CHANNEL_INVALID_DESIREDMAXRANGESCALING,
TSF_SENSOR_CHANNEL_INVALID_DUPLICATESERIALNUMBER,
TSF_SENSOR_CHANNEL_INVALID_EXTVOLT,
TSF_SENSOR_CHANNEL_INVALID_GAIN,
TSF_SENSOR_CHANNEL_INVALID_INITIALEU,
TSF_SENSOR_CHANNEL_INVALID_IRTRACCEXPONENT,
TSF_SENSOR_CHANNEL_INVALID_MODULE,
TSF_SENSOR_CHANNEL_INVALID_OFFSETHIGH,
TSF_SENSOR_CHANNEL_INVALID_OFFSETLOW,
TSF_SENSOR_CHANNEL_INVALID_RACK,
TSF_SENSOR_CHANNEL_INVALID_SENSITIVITY,
TSF_SENSOR_CHANNEL_INVALID_SENSORCATEGORY,
TSF_SENSOR_CHANNEL_INVALID_SHUNTVALUE,
TSF_SENSOR_CHANNEL_INVALID_ZEROREF,
TSF_SENSOR_CHANNEL_INVALIDFIELD,
TSF_READPROTOCOL_AND_NO_SIF,
TSF_ERROR_IN_TSF,
TSF_ERROR_INVALID_BRIDGERESISTANCE,
TSF_CALCULATED_CHANNEL_INVALID_CHAN_FIELD,
TSF_CALCULATED_CHANNEL_INVALID_EXPMAXRANGE,
TSF_CALCULATED_CHANNEL_INVALID_FIRSTCHAN,
TSF_CALCULATED_CHANNEL_INVALID_PROCESSTYPE,
TSF_CALCULATED_CHANNEL_INVALID_PROGRESS2,
TSF_CALCULATED_CHANNEL_INVALID_PROGRESS3,
TSF_CALCULATED_CHANNEL_INVALID_SECONDCHAN,
TSF_CALCULATED_CHANNEL_INVALID_THIRDCHAN,
TSF_CALCULATED_CHANNEL_INVALID_VALUE,
TSF_DIGITALCHANNEL_INVALID_CHAN,
TSF_DIGITALCHANNEL_INVALID_DELAY,
TSF_DIGITALCHANNEL_INVALID_DURATION,
TSF_DIGITALCHANNEL_INVALID_DURATIONON,
TSF_DIGITALCHANNEL_INVALID_MODULE,
TSF_DIGITALCHANNEL_INVALID_RACK,
TSF_DIGITALCHANNEL_INVALID_TYPE,
TSF_SQUIBFIREENTRY_INVALID_CHAN,
TSF_SQUIBFIREENTRY_INVALID_CURRENT,
TSF_SQUIBFIREENTRY_INVALID_DELAY,
TSF_SQUIBFIREENTRY_INVALID_DURATION,
TSF_SQUIBFIREENTRY_INVALID_DURATIONON,
TSF_SQUIBFIREENTRY_INVALID_MODULE,
TSF_SQUIBFIREENTRY_INVALID_OHMHIGH,
TSF_SQUIBFIREENTRY_INVALID_OHMLOW,
TSF_SQUIBFIREENTRY_RACK,
TSF_SQUIBFIREENTRY_TYPE,
TSF_DIM_INVALID_CABLETEST,
TSF_DIM_INVALID_CHAN,
TSF_DIM_INVALID_DATACHAN,
TSF_DIM_INVALID_FILTERMODE,
TSF_DIM_INVALID_FILTERTHRESHOLD,
TSF_DIM_INVALID_INVERTED,
TSF_DIM_INVALID_MODULE,
TSF_DIM_INVALID_RACK,
TSF_DIM_INVALID_SCALE,
TSF_G5DIGITALCHANNEL_INVALID_CHAN,
TSF_G5DIGITALCHANNEL_INVALID_DATACHAN,
TSF_G5DIGITALCHANNEL_INVALID_INVERT,
TSF_G5DIGITALCHANNEL_INVALID_MODULE,
TSF_G5DIGITALCHANNEL_INVALID_RACK,
TSF_G5DIGITALCHANNEL_INVALID_SCALE,
RACKINFORMATIONSECTION_INVALIDHEADER,
RACKINFORMATIONSECTION_INVALIDCOLUMNHEADER,
MODULEINFORMATIONSECTION_BADHEADER,
MODULEINFORMATIONSECTION_BADCOLUMHEADER,
SENSORCHANNELSECTION_INVALIDHEADER,
SENSORCHANNELSECTION_INVALIDCOLUMNHEADER,
CALCULATEDCHANNELSSECTION_INVALIDSECTIONHEADER,
CALCULATEDCHANNELSECTION_INVALIDCOLUMNHEADER,
G5DIGITALINPUTSECTION_START_INVALID_HEADER,
G5DIGITALINPUTSECTION_COLUMN_INVALID_HEADER,
TSF_DIM_INVALID_SECTIONSTARTHEADER,
TSF_DIM_INVALID_COLUMNSECTIONHEADER,
TCF_INVALID_STARTSECTIONHEADER,
TSF_TCF_INVALID_SECTIONENDHEADER,
TSF_TOMCHANNEL_INVALID_SECTIONSTART,
TSF_TOMCHANNEL_INVALID_SQUIBFIREHEADER,
TSF_SQUIBFIRECHANNELS_INVALID_COLUMNSHEADER,
TSF_TOMCHANNEL_INVALID_DIGITALCOLUMNSHEADER,
TSF_SENSOR_CHANNEL_INVALID_FILTER,
TSF_SENSOR_CHANNEL_INVALID_OFFSET
}
private TSF_ERRORS _error;
/// <summary>
/// error in question
/// </summary>
public TSF_ERRORS Error { get { return _error; } }
private int _line = 0;
/// <summary>
/// the line number where error occurred
/// </summary>
public int LineNumber { get { return _line; } }
/// <summary>
/// any additional information for the error
/// </summary>
private string _extraInfo = "";
public string ExtraInfo { get { return _extraInfo; } }
public ReadTSFError(TSF_ERRORS error) { _error = error; }
public ReadTSFError(TSF_ERRORS error, int line) { _error = error; _line = line; }
public ReadTSFError(TSF_ERRORS error, int line, string extraInfo) { _error = error; _line = line; _extraInfo = extraInfo; }
}
}

View File

@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB.TSF
{
/// <summary>
/// a calculated channel section entry in a TSF
/// each entry can contain
/// chan,descrip,processtype,1stchan,2ndchan,3rdchan,value,EU,expmaxrange
/// we currently do nothing with the entries in DataPRO
/// </summary>
public class TSFCalculatedChannelEntry : TSFChannel
{
private int _chan;
public int Chan { get { return _chan; } set { _chan = value; } }
private string _description;
public string Description { get { return _description; } set { _description = value; } }
private int _processType;
public int ProcessType { get { return _processType; } set { _processType = value; } }
private int _firstChan;
public int FirstChan { get { return _firstChan; } set { _firstChan = value; } }
private int _secondChan;
public int SecondChan { get { return _secondChan; } set { _secondChan = value; } }
private int _thirdChan;
public int ThirdChan { get { return _thirdChan; } set { _thirdChan = value; } }
private double _value;
public double Value { get { return _value; } set { _value = value; } }
private string _eu;
public string EU { get { return _eu; } set { _eu = value; } }
private double _expMaxRange;
public double ExpMaxRange { get { return _expMaxRange; } set { _expMaxRange = value; } }
private double _progress2;
public double Progress2 { get { return _progress2; } set { _progress2 = value; } }
private double _progress3;
public double Progress3 { get { return _progress3; } set { _progress3 = value; } }
public enum Fields
{
chan,
descrip,
processtype,
firstchan,//%i
secondchan,//%i
thirdchan,//%i
value,//%f
EU,//%s
expmaxrange,//%f
progress2,//%f
progress3 //%f
}
}
}

View File

@@ -0,0 +1,813 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Data;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Globalization;
using DTS.Common.Enums;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
using DTS.Common.Enums.Sensors;
using DTS.Common.Classes.Sensors;
using DTS.Common.Interface.Sensors;
using LinearizationFormula = DTS.Common.Classes.Sensors.LinearizationFormula;
namespace DTS.SensorDB
{
public class SensorCalibration : SensorCalDbRecord, IComparable<SensorCalibration>, ISensorCalibration
{
public long CalVersion { get; set; } = long.MinValue;
public string EngineeringUnits
{
get => Records.Records[0].EngineeringUnits;
}
internal const string TOP_LEVEL_TAG = "Calibrations";
internal const string CALIBRATION_TAG = "Calibration";
public enum XMLFields
{
Version,
SerialNumber,
Date,
Sensitivity,
Username,
DocumentID,
MeasurementUnit,
Excitation,
Zmo,
Poly
}
public bool SimpleEquals(SensorCalibration sc)
{
if (null == sc) { return false; }
var fields = Enum.GetValues(typeof(Fields)).Cast<Fields>().ToArray();
foreach (var field in fields)
{
switch (field)
{
case Fields.CalibrationDate: if (sc.CalibrationDate.Date != CalibrationDate.Date) { return false; } break;
case Fields.CalibrationRecords: if (!sc.Records.Records[0].IsEqual(Records.Records[0], this)) { return false; } break;
case Fields.IRTraccCalculationType: if (sc.IRTraccCalculationType != IRTraccCalculationType) { return false; } break;
case Fields.IsProportional: if (sc.IsProportional != IsProportional) { return false; } break;
case Fields.InitialOffsets: if (!sc.InitialOffsets.Equals(InitialOffsets)) { return false; } break; // FB5429
case Fields.LocalOnly: if (sc.LocalOnly != LocalOnly) { return false; } break;
case Fields.NonLinear: if (sc.NonLinear != NonLinear) { return false; } break;
case Fields.RemoveOffset: if (sc.RemoveOffset != RemoveOffset) { return false; } break;
case Fields.SerialNumber: if (sc.SerialNumber != SerialNumber) { return false; } break;
case Fields.ModifyDate: break;
case Fields.Username: break;
case Fields.SensitivityInspection: break;
case Fields.ZeroMethods: if (!sc.ZeroMethods.Equals(ZeroMethods)) { return false; } break;
case Fields.CertificationDocuments: /*if (!sc.CertificationDocuments.SequenceEqual(CertificationDocuments)) { return false; }*/
break;
default:
throw new NotSupportedException("SensorCalibration::Equals Unknown field " + field.ToString());
}
}
return true;
}
public override bool Equals(object obj)
{
if (obj is SensorCalibration sc)
{
var fields = Enum.GetValues(typeof(Fields)).Cast<Fields>().ToArray();
foreach (var field in fields)
{
switch (field)
{
case Fields.CalibrationDate: if (sc.CalibrationDate.Date != CalibrationDate.Date) { return false; } break;
case Fields.CalibrationRecords: if (!sc.Records.IsEqual(Records, this)) { return false; } break;
case Fields.IRTraccCalculationType: if (sc.IRTraccCalculationType != IRTraccCalculationType) { return false; } break;
case Fields.IsProportional: if (sc.IsProportional != IsProportional) { return false; } break;
case Fields.InitialOffsets: if (!sc.InitialOffsets.Equals(InitialOffsets)) { return false; } break; // FB5429
case Fields.LocalOnly: if (sc.LocalOnly != LocalOnly) { return false; } break;
case Fields.ModifyDate: if (sc.ModifyDate != ModifyDate) { return false; } break;
case Fields.NonLinear: if (sc.NonLinear != NonLinear) { return false; } break;
case Fields.RemoveOffset: if (sc.RemoveOffset != RemoveOffset) { return false; } break;
case Fields.SerialNumber: if (sc.SerialNumber != SerialNumber) { return false; } break;
case Fields.Username: break;
case Fields.SensitivityInspection: break;
case Fields.ZeroMethods: if (!sc.ZeroMethods.Equals(ZeroMethods)) { return false; } break;
case Fields.CertificationDocuments:
if (!sc.CertificationDocuments.SequenceEqual(CertificationDocuments)) { return false; }
break;
case Fields.UsageCount: break; //Don't consider Usage Count when comparing, so it gets set to 0
default:
throw new NotSupportedException("SensorCalibration::Equals Unknown field " + field);
}
}
return true;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public string UUID { get; set; } = "";
public string LinearAddedValues
{
get
{
if (LinearAdded)
{
var records = new CalibrationRecords(Records);
var methods = new ZeroMethods(ZeroMethods);
var offsets = new InitialOffsets(InitialOffsets);
records.Records = records.Records.Where(record => record != records.Records[0]).ToArray();
methods.Methods = new ZeroMethod[] { methods.Methods[1] };
return records.ToSerializedString(this) + SensorConstants.LinearValuesSeparator + methods.ToSerializedString() + SensorConstants.LinearValuesSeparator + offsets.ToSerializedString();
}
return string.Empty;
}
}
public double LinearAddedSensitivity
{
get
{
if (LinearAdded)
{
var records = new CalibrationRecords(Records);
records.Records = records.Records.Where(record => record != records.Records[0]).ToArray();
return records.Records[0].Sensitivity;
}
return 0D;
}
}
public ICalibrationRecord[] LinearAddedRecords
{
get
{
var records = new CalibrationRecords(Records);
if (LinearAdded)
{
records.Records = records.Records.Where(record => record != records.Records[0]).ToArray();
return records.Records;
}
return records.Records;
}
}
public ZeroMethodType LinearAddedZeroMethodType
{
get
{
var methods = new ZeroMethods(ZeroMethods);
var zeroMethods = new ZeroMethod[] { methods.Methods[1] };
return zeroMethods[0].Method;
}
}
public double LinearAddedZeroMethodEnd
{
get
{
var methods = new ZeroMethods(ZeroMethods);
var zeroMethods = new ZeroMethod[] { methods.Methods[1] };
return zeroMethods[0].End;
}
}
public double LinearAddedZeroMethodStart
{
get
{
var methods = new ZeroMethods(ZeroMethods);
var zeroMethods = new ZeroMethod[] { methods.Methods[1] };
return zeroMethods[0].Start;
}
}
public double GetPolynomialEU(double inputmV, double excitation)
{
return Records.Records[0].Poly.GetLinearizedValue(inputmV, excitation);
}
/// <summary>
/// inserts a sensor calibration into the db
/// </summary>
/// <param name="bChangeModifyDate"></param>
/// <param name="sensor"></param>
/// <param name="bSetLatestCalibrationId">whether to set the given sensor's latest calibration
/// id to the calibration when committing</param>
internal void Insert(bool bChangeModifyDate, SensorData sensor, bool bSetLatestCalibrationId = false)
{
if (bChangeModifyDate)
{
ModifyDate = DateTime.Now;
}
_ = DbOperations.SensorCalibrationsInsert(this, sensor.GetSensorType(), bSetLatestCalibrationId);
}
public void CopyValues(ISensorCalibration icopy)
{
var copy = (SensorCalibration)icopy;
CalibrationDate = copy.CalibrationDate;
Records = new CalibrationRecords(copy.Records);
IsProportional = copy.IsProportional;
LocalOnly = copy.LocalOnly;
ModifyDate = copy.ModifyDate;
NonLinear = copy.NonLinear;
RemoveOffset = copy.RemoveOffset;
SerialNumber = copy.SerialNumber;
Username = copy.Username;
ZeroMethods = new ZeroMethods(copy.ZeroMethods);
InitialOffsets = new InitialOffsets(copy.InitialOffsets);
CertificationDocuments = new string[copy.CertificationDocuments.Length];
CalibrationNote = copy.CalibrationNote;
UsageCount = copy.UsageCount;
copy.CertificationDocuments.CopyTo(CertificationDocuments, 0);
OnPropertyChanged(ALL_FIELDS);
}
public const string ALL_FIELDS = "AllFields";
public static SensorCalibration GetLatestCalibrationBySerialNumber(SensorData sd)
{
return SensorCalibrationList.GetLatestCalibrationBySerialNumber(sd);
}
public static SensorCalibration NewDigitalSC(string units)
{
var sc = new SensorCalibration
{
RemoveOffset = false,
CalibrationDate = DateTime.Now.Date,
IsProportional = false,
LocalOnly = false,
NonLinear = false
};
sc.Records.Records[0].Sensitivity = 1;
sc.Records.Records[0].EngineeringUnits = units;
sc.Records.Records[0].Excitation = ExcitationVoltageOptions.ExcitationVoltageOption.Volt5;
sc.ZeroMethods = new ZeroMethods(new[] { new ZeroMethod(ZeroMethodType.None, 0, 0) });
return sc;
}
public static SensorCalibration NewEmbeddedSC(string units)
{
//TODO: REMOVE THIS HACK
//and put in proper variables / gets from device
var sc = new SensorCalibration
{
RemoveOffset = true,
CalibrationDate = DateTime.Now.Date,
IsProportional = false,
LocalOnly = false,
NonLinear = false
};
sc.Records.Records[0].Sensitivity = 1;
sc.Records.Records[0].EngineeringUnits = units;
sc.Records.Records[0].Excitation = ExcitationVoltageOptions.ExcitationVoltageOption.Volt5;
sc.ZeroMethods = new ZeroMethods(new[] { new ZeroMethod(ZeroMethodType.None, 0, 0) });
return sc;
}
public static SensorCalibration GetLatestCalibrationBySerialNumberAndExcitation(SensorData sd, ExcitationVoltageOptions.ExcitationVoltageOption exc)
{
return SensorCalibrationList.GetLatestCalibrationBySerialNumberAndExcitation(sd, exc);
}
public static SensorCalibration GetLatestCalibrationsBySerialNumberAndCalDate(string ser, DateTime calDate)
{
return SensorCalibrationList.GetLatestCalibrationsBySerialNumberAndCalDate(ser, calDate);
}
public static SensorCalibration GetLatestCalibrationsBySerialNumberCalDateAndModifyDate(string ser, DateTime calDate, DateTime modifyDate)
{
return SensorCalibrationList.GetLatestCalibrationsBySerialNumberCalDateAndModifyDate(ser, calDate, modifyDate);
}
public static SensorCalibration[] GetCalibrationsBySerialNumber(SensorData sd)
{
return SensorCalibrationList.GetCalibrationsBySerialNumber(sd);
}
#region Data Fields
private string _documentId = "";
public string DocumentID
{
get => _documentId;
set => SetProperty(ref _documentId, value, "DocumentID");
}
public NonLinearStyles IRTraccCalculationType
{
get => Records.Records[0].Poly.NonLinearStyle;
set => Records.Records[0].Poly.NonLinearStyle = value;
}
//private ZeroMethods _zeroMethods;
public new ZeroMethods ZeroMethods
{
get
{
if (null == base.ZeroMethods || !base.ZeroMethods.Methods.Any())
{
// FB12764: Defaults in SensorConstants
base.ZeroMethods = new ZeroMethods() { Methods = new ZeroMethod[] { new ZeroMethod(SensorConstants.DefaultZeroMethodType, SensorConstants.DefaultZeroMethodStart, SensorConstants.DefaultZeroMethodEnd) } };
}
try
{
if (NonLinear)
{
switch (Records.Records[0].Poly.NonLinearStyle)
{
case NonLinearStyles.IRTraccAverageOverTime: base.ZeroMethods.Methods[0].Method = ZeroMethodType.AverageOverTime; break;
case NonLinearStyles.IRTraccDiagnosticsZero: base.ZeroMethods.Methods[0].Method = ZeroMethodType.UsePreEventDiagnosticsZero; break;
case NonLinearStyles.IRTraccZeroMMmV: base.ZeroMethods.Methods[0].Method = ZeroMethodType.None; break;
case NonLinearStyles.IRTraccCalFactor: base.ZeroMethods.Methods[0].Method = ZeroMethodType.None; break;
}
}
}
catch (Exception ex) { APILogger.Log(ex); }
return base.ZeroMethods;
}
set => base.ZeroMethods = value;
}
#endregion
protected const int CURRENT_VERSION = 1;
public SensorCalibration()
{
if (!NonLinear || LinearAdded) return;
Records.Records[0].Sensitivity = 1D;
//FB 29728 Don't set it to false, user can make the selection
// IsProportional = false;
RemoveOffset = false;
}
public enum Fields
{
CalibrationDate,
CalibrationRecords,
IsProportional,
LocalOnly,
ModifyDate,
NonLinear,
RemoveOffset,
SerialNumber,
Username,
ZeroMethods,
InitialOffsets,
CertificationDocuments,
IRTraccCalculationType,
SensitivityInspection,
UsageCount
}
private void CommonInit()
{
if (!NonLinear || LinearAdded) return;
Records.Records[0].Sensitivity = 1D;
//FB 29728 Don't set it to false, user can make the selection
// IsProportional = false;
RemoveOffset = false;
}
public SensorCalibration(string s)
{
FromSerializedString(s);
CommonInit();
}
public SensorCalibration(ISensorCalDbRecord record) : base(record)
{
CommonInit();
}
public SensorCalibration(IDataReader dr, int actualDbVersion) : base(dr, actualDbVersion)
{
CommonInit();
}
public SensorCalibration(DataRow dr)
{
try
{
CalibrationDate = Convert.ToDateTime(dr[DbOperations.SensorDB.SensorCalibrationFields.CalibrationDate.ToString()]);
CalibrationId = Convert.ToInt32(dr[DbOperations.SensorDB.SensorCalibrationFields.SensorCalibrationId.ToString()]);
LocalOnly = Convert.ToBoolean(dr[DbOperations.SensorDB.SensorCalibrationFields.LocalOnly.ToString()]);
SerialNumber = (string)dr[DbOperations.SensorDB.SensorCalibrationFields.SerialNumber.ToString()];
Username = (string)dr[DbOperations.SensorDB.SensorCalibrationFields.Username.ToString()];
Records = new CalibrationRecords((string)dr[DbOperations.SensorDB.SensorCalibrationFields.CalibrationRecords.ToString()]);
NonLinear = Convert.ToBoolean(dr[DbOperations.SensorDB.SensorCalibrationFields.NonLinear.ToString()]);
IsProportional = Convert.ToBoolean(dr[DbOperations.SensorDB.SensorCalibrationFields.IsProportional.ToString()]);
ModifyDate = Convert.ToDateTime(dr[DbOperations.SensorDB.SensorCalibrationFields.ModifyDate.ToString()]);
CertificationDocuments = ((string)dr[DbOperations.SensorDB.SensorCalibrationFields.CertificationDocuments.ToString()]).Split(new[] { CultureInfo.InvariantCulture.TextInfo.ListSeparator }, StringSplitOptions.None).ToArray();
RemoveOffset = Convert.ToBoolean(dr[DbOperations.SensorDB.SensorCalibrationFields.RemoveOffset.ToString()]);
ZeroMethods = new ZeroMethods((string)dr[DbOperations.SensorDB.SensorCalibrationFields.ZeroMethod.ToString()]);
InitialOffsets = new InitialOffsets((string)dr[DbOperations.SensorDB.SensorCalibrationFields.InitialOffset.ToString()]);
//this is downright silly, but because the linearization formula marks itself valid when it deserializes with data in it, we go and correct it here.
Records.Records[0].Poly.MarkValid(NonLinear);
if (!NonLinear || LinearAdded) return;
Records.Records[0].Sensitivity = 1D;
IsProportional = false;
RemoveOffset = false;
}
catch (Exception ex)
{
APILogger.Log("Failed to process Sensor Calibration record", ex);
}
}
/// <summary>
/// serializes to a string
/// primarily used by sensor models, which only have one calibration entry
/// sensors on the other hand have many and serialize to rows in a db table
/// </summary>
/// <returns></returns>
public string ToSerializedString()
{
var fields = Enum.GetValues(typeof(DbOperations.SensorDB.SensorCalibrationFields)).Cast<DbOperations.SensorDB.SensorCalibrationFields>().ToArray();
if (CalibrationDate.Year < 1960) { CalibrationDate = DateTime.Now.Date; }
var substrings = new List<string>();
foreach (var field in fields)
{
switch (field)
{
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationDate: substrings.Add(CalibrationDate.Date.ToFileTimeUtc().ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationRecords: substrings.Add(Records.ToSerializedString(this)); break;
//case DbOperations.SensorDB.SensorCalibrationFields.IRTraccCalculationType: substrings.Add(IRTraccCalculationType.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.IsProportional: substrings.Add(IsProportional.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.LocalOnly: substrings.Add(LocalOnly.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.ModifyDate: substrings.Add(DateTime.Now.ToFileTimeUtc().ToString(System.Globalization.CultureInfo.InvariantCulture)); break;
case DbOperations.SensorDB.SensorCalibrationFields.NonLinear: substrings.Add(NonLinear.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.RemoveOffset: substrings.Add(RemoveOffset.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.SerialNumber: substrings.Add(SerialNumber); break;
case DbOperations.SensorDB.SensorCalibrationFields.Username: substrings.Add(Username); break;
case DbOperations.SensorDB.SensorCalibrationFields.ZeroMethod: substrings.Add(ZeroMethods.ToSerializedString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.InitialOffset: substrings.Add(InitialOffsets.ToSerializedString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.CertificationDocuments:
{
List<string> docs = new List<string>();
foreach (var d in CertificationDocuments) { docs.Add(d); }
substrings.Add(string.Join(System.Globalization.CultureInfo.InvariantCulture.TextInfo.ListSeparator, docs.ToArray()));
}
break;
case DbOperations.SensorDB.SensorCalibrationFields.SensorCalibrationId: substrings.Add(CalibrationId?.ToString() ?? INVALID_CALIBRATION_ID.ToString()); break; //FB16002: follow the import/export pattern for strings as in XML
case DbOperations.SensorDB.SensorCalibrationFields.UsageCount: substrings.Add(UsageCount.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.SensitivityInspection:
try
{
substrings.Add(((int)SensitivityInspection).ToString());
}
catch (Exception ex)
{
APILogger.LogException(ex);
}
break;
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationNote: substrings.Add(CalibrationNote); break;
default: throw new NotSupportedException("SensorCalibration::ToSerializedString unknown field: " + field.ToString());
}
}
for (var i = 0; i < substrings.Count; i++)
{
substrings[i] = substrings[i]?.Replace(CultureInfo.InvariantCulture.TextInfo.ListSeparator, SEPARATOR_REPLACEMENT);
}
return string.Join(CultureInfo.InvariantCulture.TextInfo.ListSeparator, substrings.ToArray());
}
public void FromSerializedString(string s)
{
var fields = Enum.GetValues(typeof(DbOperations.SensorDB.SensorCalibrationFields)).Cast<DbOperations.SensorDB.SensorCalibrationFields>().ToArray();
var tokens = s.Split(new[] { CultureInfo.InvariantCulture.TextInfo.ListSeparator }, StringSplitOptions.None);
for (var i = 0; i < tokens.Length && i < fields.Length; i++)
{
var field = fields[i];
var token = tokens[i].Replace(SEPARATOR_REPLACEMENT, CultureInfo.InvariantCulture.TextInfo.ListSeparator);
switch (field)
{
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationDate: CalibrationDate = DateTime.FromFileTimeUtc(Convert.ToInt64(token)); break;
case DbOperations.SensorDB.SensorCalibrationFields.SensorCalibrationId:
//FB16002: follow the import/export pattern for strings as in XML
if (int.TryParse(token, NumberStyles.Any, CultureInfo.InvariantCulture, out int iTemp))
{
if (iTemp == INVALID_CALIBRATION_ID) { CalibrationId = null; }
else
{
CalibrationId = iTemp;
}
}
else
{
CalibrationId = null;
}
break;
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationRecords: Records = new CalibrationRecords(token); break;
//case DbOperations.SensorDB.SensorCalibrationFields.IRTraccCalculationType: IRTraccCalculationType = (SensorModel.IRTraccFormats)Enum.Parse(typeof(SensorModel.IRTraccFormats), token);break;
case DbOperations.SensorDB.SensorCalibrationFields.IsProportional: IsProportional = Convert.ToBoolean(token); break;
case DbOperations.SensorDB.SensorCalibrationFields.LocalOnly: LocalOnly = Convert.ToBoolean(token); break;
case DbOperations.SensorDB.SensorCalibrationFields.ModifyDate: ModifyDate = DateTime.FromFileTimeUtc(Convert.ToInt64(token)); break;
case DbOperations.SensorDB.SensorCalibrationFields.NonLinear: NonLinear = Convert.ToBoolean(token); break;
case DbOperations.SensorDB.SensorCalibrationFields.RemoveOffset: RemoveOffset = Convert.ToBoolean(token); break;
case DbOperations.SensorDB.SensorCalibrationFields.SerialNumber: SerialNumber = token; break;
case DbOperations.SensorDB.SensorCalibrationFields.Username: Username = token; break;
case DbOperations.SensorDB.SensorCalibrationFields.ZeroMethod: ZeroMethods = new ZeroMethods(token); break;
case DbOperations.SensorDB.SensorCalibrationFields.InitialOffset: InitialOffsets = new InitialOffsets(token); break;
case DbOperations.SensorDB.SensorCalibrationFields.CertificationDocuments: CertificationDocuments = token.Split(new[] { CultureInfo.InvariantCulture.TextInfo.ListSeparator }, StringSplitOptions.None); break;
case DbOperations.SensorDB.SensorCalibrationFields.UsageCount: UsageCount = Convert.ToInt32(token); break;
case DbOperations.SensorDB.SensorCalibrationFields.SensitivityInspection:
try
{
SensitivityInspection = (SensitivityInspectionType)Convert.ToInt32(token);
}
catch (Exception ex)
{
APILogger.LogException(ex);
}
break;
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationNote: CalibrationNote = token; break;
}
}
}
public const string SEPARATOR_REPLACEMENT = "__SC__";
public SensorCalibration(ISensorCalibration iSensorCalibration)
{
var sc = (SensorCalibration)iSensorCalibration;
_serialNumber = sc.SerialNumber;
_userName = sc.Username;
_calibrationDate = sc.CalibrationDate;
ModifyDate = sc.ModifyDate;
NonLinear = sc.NonLinear;
IsProportional = sc.IsProportional;
Records = new CalibrationRecords(sc.Records);
RemoveOffset = sc.RemoveOffset;
ZeroMethods = new ZeroMethods(sc.ZeroMethods);
InitialOffsets = new InitialOffsets(sc.InitialOffsets);
CertificationDocuments = sc.CertificationDocuments;
CalibrationId = sc.CalibrationId;
//43152
SensitivityInspection = sc.SensitivityInspection;
//43141 added note property
CalibrationNote = sc.CalibrationNote;
UsageCount = sc.UsageCount;
}
internal SensorCalibration(XElement elem)
{
var tableName = SensorDBTables.CalibrationTableFilename;
int ver;
try
{
ver = (int)elem.Element(XMLFields.Version.ToString());
}
catch (ArgumentNullException)
{
throw new Exception("SensorData: Can't find version tag in DB file");
}
if (ver != CURRENT_VERSION)
{
throw new Exception(string.Format(Strings.SensorData_Ctor_Err1, CURRENT_VERSION, ver));
}
SensorDBBase.GetValue(elem, XMLFields.SerialNumber.ToString(), out _serialNumber, null, tableName);
SensorDBBase.GetValue(elem, XMLFields.Date.ToString(), out _calibrationDate, SerialNumber, tableName);
SensorDBBase.GetValue(elem, XMLFields.Sensitivity.ToString(), out double sensitivity, SerialNumber, tableName);
Records.Records[0].Sensitivity = sensitivity;
var poly = "";
try { SensorDBBase.GetValueSafe(elem, XMLFields.Poly.ToString(), out poly, SerialNumber, tableName); }
catch (Exception ex) { APILogger.Log(ex); }
Records.Records[0].Poly = new LinearizationFormula();
if (!string.IsNullOrWhiteSpace(poly))
{
Records.Records[0].Poly.FromSerializeString(poly);
NonLinear = true;
}
SensorDBBase.GetValue(elem, XMLFields.MeasurementUnit.ToString(), out string mu, SerialNumber, tableName);
Array.ForEach(Records.Records, record => record.EngineeringUnits = mu); //FB16398: set units on all records, not just first
SensorDBBase.GetValue(elem, XMLFields.Username.ToString(), out _userName, SerialNumber, tableName);
SensorDBBase.GetValueSafe(elem, XMLFields.DocumentID.ToString(), out _documentId, SerialNumber, tableName);
if (null == _documentId) { _documentId = string.Empty; }
if (!NonLinear) return;
Records.Records[0].Sensitivity = 1D;
IsProportional = false;
}
public int CompareTo(SensorCalibration other)
{
if (null == other) { return 1; }
if (Equals(this, other)) { return 0; }
if (CalibrationDate.Date != other.CalibrationDate.Date)
return other.CalibrationDate.CompareTo(CalibrationDate);
var modifyCompare = other.ModifyDate.CompareTo(ModifyDate);
return 0 == modifyCompare ? other.CalVersion.CompareTo(CalVersion) : modifyCompare;
}
private string BuildLinearDisplayString(ICalibrationRecord[] records, ExcitationVoltageOptions.ExcitationVoltageOption excitation, string linearFormat, bool iepe = false)
{
var sb = new StringBuilder();
var dSensitivity = 0D;
if (ExcitationVoltageOptions.ExcitationVoltageOption.Undefined == excitation
|| !IsProportional)
{
dSensitivity = records[0].Sensitivity;
}
else
{
foreach (var r in records)
{
if (r.Excitation != excitation) continue;
dSensitivity = r.Sensitivity;
break;
}
}
var sensUnits = string.Empty;
switch (records[0].SensitivityUnits)
{
case SensorConstants.SensUnits.mV: sensUnits = " mV"; break;
case SensorConstants.SensUnits.mVperEU: sensUnits = " mV/EU"; break;
case SensorConstants.SensUnits.mVperV: sensUnits = " mV/V"; break;
case SensorConstants.SensUnits.mVperVperEU: sensUnits = " mV/V/EU"; break;
}
if (iepe)
{
sensUnits = " mV/EU";
}
sb.Append(string.Concat(dSensitivity.ToString(linearFormat), sensUnits));
if (IsProportional)
{
if (ExcitationVoltageOptions.ExcitationVoltageOption.Undefined != excitation)
{
var excitationString = string.Empty;
switch (excitation)
{
case ExcitationVoltageOptions.ExcitationVoltageOption.Volt1: excitationString = "1V"; break;
case ExcitationVoltageOptions.ExcitationVoltageOption.Volt10: excitationString = "10V"; break;
case ExcitationVoltageOptions.ExcitationVoltageOption.Volt2: excitationString = "2V"; break;
case ExcitationVoltageOptions.ExcitationVoltageOption.Volt2_5: excitationString = "2.5V"; break;
case ExcitationVoltageOptions.ExcitationVoltageOption.Volt3: excitationString = "3V"; break;
case ExcitationVoltageOptions.ExcitationVoltageOption.Volt5: excitationString = "5V"; break;
}
sb.Append($" ({excitationString})");
}
}
if (records[0].AtCapacity)
{
sb.Append($" @({records[0].CapacityOutputIsBasedOn}EU)");
}
return sb.ToString();
}
public string ToDisplayString(ExcitationVoltageOptions.ExcitationVoltageOption excitation,
string linearFormat,
string nonlinearFormat,
bool iepe)
{
if (NonLinear && !iepe)
{
return Records.Records[0].Poly.ToDisplayString(nonlinearFormat);
}
return BuildLinearDisplayString(Records.Records, excitation, linearFormat, iepe);
}
public string ToLinearDisplayString(ExcitationVoltageOptions.ExcitationVoltageOption excitation, string linearFormat, bool iepe)
{
if (NonLinear && !iepe)
{
if (LinearAdded)
{
//build linear string from remaining records after the poly record.
return BuildLinearDisplayString(Records.Records.Where(record => record != Records.Records[0]).ToArray(), excitation, linearFormat);
}
return string.Empty;
}
return ToDisplayString(excitation, linearFormat, null, iepe);
}
public string ToNonLinearDisplayString(string nonlinearFormat, bool iepe)
{
if (!NonLinear) return string.Empty;
return ToDisplayString(ExcitationVoltageOptions.ExcitationVoltageOption.Undefined, null, nonlinearFormat, iepe);
}
public void ReadXML(System.Xml.XmlElement root)
{
foreach (var node in root.ChildNodes)
{
if (node is System.Xml.XmlElement) { ProcessXmlElement(node as System.Xml.XmlElement); }
}
}
private void ProcessXmlElement(System.Xml.XmlElement node)
{
if (!Enum.TryParse(node.Name, out DbOperations.SensorDB.SensorCalibrationFields field)) return;
switch (field)
{
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationDate: CalibrationDate = DateTime.Parse(node.InnerText, CultureInfo.InvariantCulture); break;
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationRecords: Records = new CalibrationRecords(node.InnerText); break;
case DbOperations.SensorDB.SensorCalibrationFields.CertificationDocuments: CertificationDocuments = new string[0]; break;
case DbOperations.SensorDB.SensorCalibrationFields.IsProportional: IsProportional = Convert.ToBoolean(node.InnerText); break;
case DbOperations.SensorDB.SensorCalibrationFields.LocalOnly: LocalOnly = Convert.ToBoolean(node.InnerText); break;
case DbOperations.SensorDB.SensorCalibrationFields.ModifyDate: ModifyDate = DateTime.Parse(node.InnerText, CultureInfo.InvariantCulture); break;
case DbOperations.SensorDB.SensorCalibrationFields.NonLinear: NonLinear = Convert.ToBoolean(node.InnerText); break;
case DbOperations.SensorDB.SensorCalibrationFields.RemoveOffset: RemoveOffset = Convert.ToBoolean(node.InnerText); break;
case DbOperations.SensorDB.SensorCalibrationFields.SerialNumber: SerialNumber = node.InnerText; break;
case DbOperations.SensorDB.SensorCalibrationFields.Username: Username = node.InnerText; break;
case DbOperations.SensorDB.SensorCalibrationFields.ZeroMethod: ZeroMethods = new ZeroMethods(node.InnerText); break;
case DbOperations.SensorDB.SensorCalibrationFields.InitialOffset: InitialOffsets = new InitialOffsets(node.InnerText); break;
case DbOperations.SensorDB.SensorCalibrationFields.SensorCalibrationId:
if (int.TryParse(node.InnerText, NumberStyles.Any, CultureInfo.InvariantCulture, out int iTemp))
{
if (iTemp == INVALID_CALIBRATION_ID) { CalibrationId = null; }
else
{
CalibrationId = iTemp;
}
}
else
{
APILogger.Log($"possible error in sensor calibration id: {node.InnerText}");
CalibrationId = null;
}
break;
case DbOperations.SensorDB.SensorCalibrationFields.UsageCount: UsageCount = Convert.ToInt32(node.InnerText, CultureInfo.InvariantCulture); break;
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationNote: CalibrationNote = node.InnerText; break;
//FB 43267
case DbOperations.SensorDB.SensorCalibrationFields.SensitivityInspection:
try
{
SensitivityInspection = (SensitivityInspectionType)Convert.ToInt32(node.InnerText, CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
APILogger.LogException(ex);
}
break;
default: throw new NotSupportedException("SensorCalibration::ProcessXMLElement unsupported tag: " + field);
}
}
private const int INVALID_CALIBRATION_ID = -1;
public void WriteXML(ref System.Xml.XmlWriter writer)
{
writer.WriteStartElement("SensorCalibration");
var fields = Enum.GetValues(typeof(DbOperations.SensorDB.SensorCalibrationFields)).Cast<DbOperations.SensorDB.SensorCalibrationFields>().ToArray();
foreach (var f in fields)
{
writer.WriteStartElement(f.ToString());
switch (f)
{
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationDate: writer.WriteString(CalibrationDate.ToString(CultureInfo.InvariantCulture)); break;
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationRecords: writer.WriteString(Records.ToSerializedString(this)); break;
case DbOperations.SensorDB.SensorCalibrationFields.CertificationDocuments: writer.WriteString(""); break;
case DbOperations.SensorDB.SensorCalibrationFields.IsProportional: writer.WriteString(IsProportional.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.LocalOnly: writer.WriteString(LocalOnly.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.ModifyDate: writer.WriteString(ModifyDate.ToString(CultureInfo.InvariantCulture)); break;
case DbOperations.SensorDB.SensorCalibrationFields.NonLinear: writer.WriteString(NonLinear.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.RemoveOffset: writer.WriteString(RemoveOffset.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.SerialNumber: writer.WriteString(SerialNumber); break;
case DbOperations.SensorDB.SensorCalibrationFields.Username: writer.WriteString(Username); break;
case DbOperations.SensorDB.SensorCalibrationFields.ZeroMethod: writer.WriteString(ZeroMethods.ToSerializedString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.InitialOffset: writer.WriteString(InitialOffsets.ToSerializedString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.SensorCalibrationId:
if (null != CalibrationId)
{
writer.WriteString(((int)CalibrationId).ToString(CultureInfo.InvariantCulture));
}
else
{
writer.WriteString(INVALID_CALIBRATION_ID.ToString(CultureInfo.InvariantCulture));
}
break;
case DbOperations.SensorDB.SensorCalibrationFields.UsageCount: writer.WriteString(UsageCount.ToString()); break;
case DbOperations.SensorDB.SensorCalibrationFields.SensitivityInspection:
try
{
writer.WriteString(((int)SensitivityInspection).ToString());
}
catch(Exception ex)
{
APILogger.LogException(ex);
}
break;
case DbOperations.SensorDB.SensorCalibrationFields.CalibrationNote: writer.WriteString(CalibrationNote.ToString()); break;
default: throw new NotSupportedException("SensorCalibration::WriteXML unsupported field: " + f);
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
public bool IsCompatibleWithIEPE()
{
if (IsProportional) { return false; }
return !NonLinear;
}
}
}

View File

@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTS.SensorDB
{
/// <summary>
/// handles the calibration information section of the TSF
/// </summary>
public class TSFCalibrationInformation
{
private int _version;
public int Version { get { return _version; } set { _version = value; } }
private TSFChannelDescription _parent;
public TSFChannelDescription Parent { get { return _parent; } set { _parent = value; } }
private int _source;
public int Source { get { return _source; } set { _source = value; } }
private ulong _crc32;
public ulong CRC32 { get { return _crc32; } set { _crc32 = value; } }
private bool _calibrationValid;
public bool CalibrationValid { get { return _calibrationValid; } set { _calibrationValid = value; } }
private bool _calPas;
public bool CalPass { get { return _calPas; } set { _calPas = value; } }
private double _calGainErrorPercent;
public double CalGainErrorPercent { get { return _calGainErrorPercent; } set { _calGainErrorPercent = value; } }
private double _calShuntErrorPercent;
public double CalShuntErrorPercent { get { return _calShuntErrorPercent; } set { _calShuntErrorPercent = value; } }
private double _calMeasuredScaleFactorMV;
public double CalMeasuredScaleFactorMV { get { return _calMeasuredScaleFactorMV; } set { _calMeasuredScaleFactorMV = value; } }
private double _calExcitationVolts;
public double CalExcitationVolts { get { return _calExcitationVolts; } set { _calExcitationVolts = value; } }
private int _calChannelOffsetADC;
public int CalChannelOffsetADC { get { return _calChannelOffsetADC; } set { _calChannelOffsetADC = value; } }
private int _calChannelZeroADC;
public int CalChannelZeroADC { get { return _calChannelZeroADC; } set { _calChannelZeroADC = value; } }
private double _calNaturalSensorOffsetMV;
public double CalNaturalSensorOffsetMV { get { return _calNaturalSensorOffsetMV; } set { _calNaturalSensorOffsetMV = value; } }
private int _calNaturalFloorADC;
public int CalNaturalFloorADC { get { return _calNaturalFloorADC; } set { _calNaturalFloorADC = value; } }
private double _calInputRangeMV { get { return _calInputRangeMV; } set { _calInputRangeMV = value; } }
private double _calNoiseFloorADC;
public double CalNoiseFloorADC { get { return _calNoiseFloorADC; } set { _calNoiseFloorADC = value; } }
private double _calNoiseAtRangeADC;
public double CalNoiseAtRangeADC { get { return _calNoiseAtRangeADC; } set { _calNoiseAtRangeADC = value; } }
public TSFCalibrationInformation() { }
public TSFCalibrationInformation(TSFCalibrationInformation copy, TSFChannelDescription channel)
{
_calChannelOffsetADC = copy._calChannelOffsetADC;
_calChannelZeroADC = copy._calChannelZeroADC;
_calExcitationVolts = copy._calExcitationVolts;
_calGainErrorPercent = copy._calGainErrorPercent;
_calibrationValid = copy._calibrationValid;
_calInputRangeMV = copy._calInputRangeMV;
_calMeasuredScaleFactorMV = copy._calMeasuredScaleFactorMV;
_calNaturalFloorADC = copy._calNaturalFloorADC;
_calNaturalSensorOffsetMV = copy._calNaturalSensorOffsetMV;
_calNoiseAtRangeADC = copy._calNoiseAtRangeADC;
_calNoiseFloorADC = copy._calNoiseFloorADC;
_calPas = copy._calPas;
_calShuntErrorPercent = copy._calShuntErrorPercent;
_crc32 = copy._crc32;
_parent = channel;
_source = copy._source;
_version = copy._version;
}
}
}

BIN
DataPRO/SensorDB/.svn/wc.db Normal file

Binary file not shown.

View File

View File

@@ -0,0 +1,298 @@
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Interface.Sensors.SoftwareFilters;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using DTS.Common.Settings;
using Prism.Events;
namespace DTS.SensorDB
{
public class AnalogSettingDefaults : Common.Base.BasePropertyChanged, IAnalogDefaults
{
private List<ISoftwareFilter> _softwareFilters;
private IEventAggregator _eventAggregator;
public AnalogSettingDefaults()
{
_softwareFilters = SoftwareFilter.GetSoftwareFilters().ToList();
_eventAggregator = ContainerLocator.Container.Resolve<IEventAggregator>();
_eventAggregator.GetEvent<DTS.Common.Events.Sensors.SensorsList.SensorSavedEvent>().Subscribe(SelectSoftwareFilter);
}
//FB 13120 select default filter for new add hoc filter
private void SelectSoftwareFilter(double frequency)
{
if (_softwareFilters.Where(p => p.Frequency == frequency).Any())
{
return;
}
SoftwareFilter softwareFilter = new SoftwareFilter(-1, frequency.ToString(), 'S', DateTime.Now, "", frequency, true);
foreach (var sf in _softwareFilters)
{
sf.IsDefault = false;
}
_softwareFilters.Add(softwareFilter);
Save();
SelectedFilterOption = new FilterClass(FilterClassType.AdHoc, frequency);
OnPropertyChanged("FilterOptions");
}
//Fb 13120 save the filters to db
public void Save()
{
foreach (var sf in _softwareFilters)
{
sf.Commit();
}
}
//FB 13120 identify the selected filter option to be used in combo box
public IFilterClass SelectedFilterOption
{
get
{
var softwareFilter = _softwareFilters.Find(p => p.IsDefault);
FilterClass fc = null;
if (softwareFilter?.Id == 1)
{
fc = new FilterClass(FilterClassType.Unfiltered);
}
else if (softwareFilter?.Id == 2)
{
fc = new FilterClass(FilterClassType.None);
}
else if (softwareFilter?.ISOCode == 'S')
{
fc = new FilterClass(FilterClassType.AdHoc, softwareFilter.Frequency);
}
else
{
foreach (var fct in Enum.GetValues(typeof(FilterClassType))
.Cast<FilterClassType>().ToArray())
{
if (fct == FilterClassType.AdHoc
|| fct == FilterClassType.CFC10)
{
continue;
}
if (fct.ToString() == softwareFilter?.Description.Replace(" ", ""))
{
fc = new FilterClass(fct);
break;
}
}
}
return fc;
}
set
{
if (value == null)
return;
foreach (var sf in _softwareFilters)
{
sf.IsDefault = false;
}
ISoftwareFilter softwareFilter = null;
if (value.FClass == FilterClassType.Unfiltered)
{
softwareFilter = _softwareFilters.Find(p => p.Id == 1);
}
else if (value.FClass == FilterClassType.None)
{
softwareFilter = _softwareFilters.Find(p => p.Id == 2);
}
else if (value.FClass == FilterClassType.AdHoc && !_softwareFilters.Where(p => p.Frequency == value.Frequency).Any())
{
_filterOptions.Add(new FilterClass(FilterClassType.AdHoc, value.Frequency));
_softwareFilters.Add(new SoftwareFilter(-1, value.Frequency.ToString(), 'S', DateTime.Now, "", value.Frequency, false));
softwareFilter = _softwareFilters.Find(p => p.Frequency == value.Frequency);
}
else
{
softwareFilter = _softwareFilters.Find(p => p.Frequency == value.Frequency);
}
softwareFilter.IsDefault = true;
OnPropertyChanged("SelectedFilterOption");
}
}
public static IAnalogDefaults GetAnalogDefaults()
{
return new AnalogSettingDefaults();
}
private List<IFilterClass> _filterOptions;
//FB 13120 available filter classes to be used in drop down
public List<IFilterClass> FilterOptions
{
get
{
if (null == _filterOptions)
{
var softwareFilters = SoftwareFilter.GetSoftwareFilters();
var customFilters = softwareFilters.Where(p => p.ISOCode == 'S');
_filterOptions = new List<IFilterClass>();
foreach (var fct in Enum.GetValues(typeof(FilterClassType))
.Cast<FilterClassType>().ToArray())
{
if (fct == FilterClassType.AdHoc
|| fct == FilterClassType.CFC10)
{
//Dont include until we can handle this type.
continue;
}
FilterClass fc = new FilterClass(fct);
_filterOptions.Add(fc);
}
foreach (var filter in customFilters)
{
FilterClass fc = new FilterClass(FilterClassType.AdHoc, filter.Frequency);
_filterOptions.Add(fc);
}
}
_filterOptions.Sort(CompareFilters);
return _filterOptions;
}
}
//FB 18727 UseMeasuredExcitation setting
public bool UseMeasuredExcitation
{
get
{
return SettingsDB.GetGlobalValueBool(Common.Constants.UseMeasuredExcitation, false);
}
set
{
SettingsDB.SetGlobalValueBoolean(Common.Constants.UseMeasuredExcitation, value);
OnPropertyChanged(Common.Constants.UseMeasuredExcitation);
}
}
public bool TrackAnalogDiagnosticsEnabled
{
get => DTS.Common.Storage.DbOperations.GetConnectionDbVersion() >= Common.Constants.TRACK_ANALOG_DIAGNOSTICS_DB_VERSION;
}
//http://manuscript.dts.local/f/cases/39148/DataPRO-Instrumentation-Tracking-Functions-FAA-Request-Diagnostics-Tracking
public bool TrackAnalogDiagnostics
{
get => TrackAnalogDiagnosticsEnabled && SettingsDB.GetGlobalValueBool(Common.Constants.TrackAnalogDiagnostics, false);
set
{
SettingsDB.SetGlobalValueBoolean(Common.Constants.TrackAnalogDiagnostics, value);
OnPropertyChanged(Common.Constants.TrackAnalogDiagnostics);
}
}
private static int CompareFilters(IFilterClass f1, IFilterClass f2)
{
if (f1 == null)
{
if (f2 == null)
{
// both null, equal
return 0;
}
// left null but not right
return -1;
}
if (f2 == null)
{
// left not null, right null
return 1;
}
if (f1.FClass != FilterClassType.None)
return f2.FClass == FilterClassType.None ? 1 : f1.Frequency.CompareTo(f2.Frequency);
if (f2.FClass == FilterClassType.None)
{
return 0;
}
return -1;
}
public bool Validate()
{
return true;
}
public void ReadXML(System.Xml.XmlElement root)
{
var frequency = 0D;
var fClass = FilterClassType.None;
foreach (var node in root.ChildNodes)
{
if (node is System.Xml.XmlElement nodex)
{
if (Enum.TryParse(nodex.Name, out FilterXMLFields field))
{
switch (field)
{
case FilterXMLFields.Frequency:
frequency = Convert.ToDouble(nodex.InnerText);
break;
case FilterXMLFields.FClass:
if (Enum.TryParse(nodex.InnerText, out FilterClassType filterClass))
{
fClass = filterClass;
}
break;
default:
throw new NotSupportedException(
"AnalogSettingDefaults::ReadXML unsupported field: " + field);
}
}
}
}
SelectedFilterOption = new FilterClass(fClass, frequency);
}
public void WriteXML(ref System.Xml.XmlWriter writer)
{
writer.WriteStartElement("AnalogSettingDefaults");
writer.WriteStartElement("SelectedFilterOption");
writer.WriteStartElement(FilterXMLFields.Frequency.ToString());
writer.WriteString(SelectedFilterOption.Frequency.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteEndElement();
writer.WriteStartElement(FilterXMLFields.FClass.ToString());
writer.WriteString(SelectedFilterOption.FClass.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
}
/// <summary>
/// restores digital input settings to defaults
/// </summary>
/// <param name="sensorDefaults"></param>
public static void RestoreDefaults(IAnalogDefaults sensorDefaults)
{
sensorDefaults.TrackAnalogDiagnostics = false;
}
}
public enum FilterXMLFields
{
FilterName,
Frequency,
FClass
}
}

View File

@@ -0,0 +1,69 @@
using DTS.Common.Classes;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO.Ports;
namespace DTS.SensorDB
{
public class CanSetting : SensorData
{
///<summary>
///</summary>
public CanSetting() : base()
{
SetDefaults(this);
}
public CanSetting(CanSetting copy) : base(copy)
{
SetDefaults(this);
}
public CanSetting(ICANRecord record)
{
SetDefaults(this);
DatabaseId = record.Id;
SerialNumber = record.SerialNumber;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
LastModified = record.LastModified;
LastUpdatedBy = record.LastUpdatedBy;
}
public static void SetDefaults(SensorData sd)
{
sd.SupportedExcitation = new Common.Enums.ExcitationVoltageOptions.ExcitationVoltageOption[] { ExcitationVoltageOptions.ExcitationVoltageOption.Undefined };
sd.Bridge = SensorConstants.BridgeType.CAN;
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 1;
sd.DisplayUnit = "";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 0;
sd.OffsetToleranceLow = 0;
sd.Model = "CAN Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
ICANRecord record = new CANRecord(setting);
var hr = DbOperations.SensorsCanUpdateInsert(ref record);
if (0 == hr)
{
setting.DatabaseId = record.Id;
}
}
}
}

View File

@@ -0,0 +1,275 @@
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors.SensorSettingsModule;
using DTS.Common.Settings;
using System;
using System.Xml;
namespace DTS.SensorDB
{
public class CalibrationPolicy : Common.Base.BasePropertyChanged, ICalibrationPolicy
{
private SensorConstants.SensorCalPolicy _selectedCalPolicy;
/// <summary>
/// returns the currently selected calibration policy
/// </summary>
public SensorConstants.SensorCalPolicy SelectedCalPolicy
{
get => _selectedCalPolicy;
set => SetProperty(ref _selectedCalPolicy, value, "SelectedCalPolicy");
}
private static SensorConstants.SensorCalPolicy[] _availableCalPolicies = new[]
{SensorConstants.SensorCalPolicy.AllowAlways, SensorConstants.SensorCalPolicy.DONT_ALLOW};
/// <summary>
/// returns all the available calibration policies
/// </summary>
public SensorConstants.SensorCalPolicy[] AvailableSensorCalPolicies => _availableCalPolicies;
private int _warningPeriod;
/// <summary>
/// returns the period in days before the calibration is due for a sensor to warn
/// </summary>
public int WarningPeriod
{
get => _warningPeriod;
set => SetProperty(ref _warningPeriod, value, "WarningPeriod");
}
private bool _useSensorFirstUseDate = true;
/// <summary>
/// indicates whether calibration interval starts after calibration or first use
/// 13065 Sensor "First Use" Date
/// </summary>
public bool UseSensorFirstUseDate
{
get => _useSensorFirstUseDate;
set => SetProperty(ref _useSensorFirstUseDate, value, "UseSensorFirstUseDate");
}
public bool SensorAssemblyEnabled
{
get => DTS.Common.Storage.DbOperations.GetConnectionDbVersion() >= Common.Constants.SENSOR_ASSEMBLY_DB_VERSION;
}
private bool _dontAllowDataCollectionIfOverused = false;
/// <summary>
/// Indicates whether or not to keep track of, and validate Test Setups based on, sensor overuse.
/// </summary>
public bool DontAllowDataCollectionIfOverused
{
get => SensorAssemblyEnabled && _dontAllowDataCollectionIfOverused;
set
{
SetProperty(ref _dontAllowDataCollectionIfOverused, value, "DontAllowDataCollectionIfOverused");
}
}
public bool AllowInspectBeforeUseEnabled
{
get => DTS.Common.Storage.DbOperations.GetConnectionDbVersion() >= Common.Constants.ALLOW_INSPECT_BEFORE_USE_DB_VERSION;
}
private bool _allowInspectBeforeUse = false;
//FB 43142
public bool AllowInspectBeforeUse
{
get => AllowInspectBeforeUseEnabled && _allowInspectBeforeUse;
set
{
SetProperty(ref _allowInspectBeforeUse, value, "AllowInspectBeforeUse");
}
}
private int _usageRemainingForWarning;
/// <summary>
/// A warning will be displayed if a sensor's usage is within this amount of its maximum.
/// </summary>
public int UsageRemainingForWarning
{
get => _usageRemainingForWarning;
set => SetProperty(ref _usageRemainingForWarning, value, "UsageRemainingForWarning");
}
private int _defaultMaxUsageAllowed;
/// <summary>
/// The default maximum number of uses for sensors
/// </summary>
public int DefaultMaxUsageAllowed
{
get => _defaultMaxUsageAllowed;
set => SetProperty(ref _defaultMaxUsageAllowed, value, "DefaultMaxUsageAllowed");
}
protected CalibrationPolicy(SensorConstants.SensorCalPolicy calPolicy,
int warningPeriod,
bool useFirstUseDate,
bool dontAllowDataCollectionIfOverused,
int usageRemainingForWarning,
int defaultMaxUsageAllowed,
bool allowInspectBeforeUse)
{
WarningPeriod = warningPeriod;
SelectedCalPolicy = calPolicy;
UseSensorFirstUseDate = useFirstUseDate;
DontAllowDataCollectionIfOverused = dontAllowDataCollectionIfOverused;
UsageRemainingForWarning = usageRemainingForWarning;
DefaultMaxUsageAllowed = defaultMaxUsageAllowed;
AllowInspectBeforeUse = allowInspectBeforeUse;
}
/// <summary>
/// the key for the setting in the db for calibration policy
/// </summary>
private const string SENSOR_CAL_POLICY_KEY = "SensorCalPolicy";
/// <summary>
/// the key for the setting in the db for the warning period
/// </summary>
private const string SENSOR_WARNING_PERIOD_KEY = "SensorCalWarningPeriodDays";
/// <summmary>
/// the key for sensor first use setting in db
/// </summary>
private const string SENSOR_FIRST_USE_KEY = "UseSensorFirstUseDate";
/// <summary>
/// the key for inspect before use setting in db
/// </summary>
private const string ALLOW_INSPECT_BEFORE_USE = "AllowInspectBeforeUse";
/// <summary>
/// The key for sensor overuse setting in db
/// </summary>
private const string SENSOR_OVERUSE_KEY = "DontAllowDataCollectionIfOverused";
/// <summary>
/// The key for sensor overuse setting in db
/// </summary>
private const string SENSOR_USAGE_REMAINING_WARNING_KEY = "UsageRemainingForWarning";
/// <summary>
/// The default maximum number of uses for sensors
/// </summary>
private const string SENSOR_DEFAULT_MAX_USAGE_KEY = "DefaultMaxUsageAllowed";
/// <summary>
/// retrieves calibration policies for sensors from the db and returns it
/// </summary>
/// <returns></returns>
public static ICalibrationPolicy GetCalibrationPolicy()
{
var s = SettingsDB.GetGlobalValue(SENSOR_CAL_POLICY_KEY, SensorConstants.CAL_SENSOR_POLICY_DEFAULT.ToString());
SensorConstants.SensorCalPolicy policy;
Enum.TryParse(s, out policy);
var period = SettingsDB.GetGlobalValueInt(SENSOR_WARNING_PERIOD_KEY,
SensorConstants.CAL_SENSOR_POLICY_WARNING_DAYS_DEFAULT);
var firstUse = SettingsDB.GetGlobalValueBool(SENSOR_FIRST_USE_KEY, SensorConstants.SENSOR_FIRST_USE_DEFAULT);
var allowInspectBeforeUse = SettingsDB.GetGlobalValueBool(ALLOW_INSPECT_BEFORE_USE, SensorConstants.AllowInspectBeforeUse);
var overuse = SettingsDB.GetGlobalValueBool(SENSOR_OVERUSE_KEY, SensorConstants.SENSOR_OVERUSE_DEFAULT);
var usageRemainingForWarning = SettingsDB.GetGlobalValueInt(SENSOR_USAGE_REMAINING_WARNING_KEY, SensorConstants.SENSOR_USAGE_REMAINING_FOR_WARNING_DEFAULT);
var defaultMaxUsage = SettingsDB.GetGlobalValueInt(SENSOR_DEFAULT_MAX_USAGE_KEY, SensorConstants.SENSOR_DEFAULT_MAX_USAGE_DEFAULT);
return new CalibrationPolicy(policy, period, firstUse, overuse, usageRemainingForWarning, defaultMaxUsage, allowInspectBeforeUse);
}
/// <summary>
/// writes calibration policies to the db
/// </summary>
/// <param name="policy"></param>
public static void WriteCalibrationPolicyToDb(ICalibrationPolicy policy)
{
SettingsDB.SetGlobalValue(SENSOR_CAL_POLICY_KEY, policy.SelectedCalPolicy.ToString());
SettingsDB.SetGlobalValueInt(SENSOR_WARNING_PERIOD_KEY, policy.WarningPeriod);
SensorConstants.SensorCalPolicyCurrent = policy.SelectedCalPolicy;
SensorConstants.SensorCalOutOfDateWarningPeriodDays = policy.WarningPeriod;
SettingsDB.SetGlobalValueBoolean(SENSOR_FIRST_USE_KEY, policy.UseSensorFirstUseDate);
SensorConstants.UseSensorFirstUseDate = policy.UseSensorFirstUseDate;
SettingsDB.SetGlobalValueBoolean(SENSOR_OVERUSE_KEY, policy.DontAllowDataCollectionIfOverused);
SensorConstants.DontAllowDataCollectionIfOverused = policy.DontAllowDataCollectionIfOverused;
SettingsDB.SetGlobalValueInt(SENSOR_USAGE_REMAINING_WARNING_KEY, policy.UsageRemainingForWarning);
SensorConstants.UsageRemainingForWarning = policy.UsageRemainingForWarning;
SettingsDB.SetGlobalValueInt(SENSOR_DEFAULT_MAX_USAGE_KEY, policy.DefaultMaxUsageAllowed);
SensorConstants.DefaultMaxUsageAllowed = policy.DefaultMaxUsageAllowed;
//FB 43142
SettingsDB.SetGlobalValueBoolean(ALLOW_INSPECT_BEFORE_USE, policy.AllowInspectBeforeUse);
SensorConstants.AllowInspectBeforeUse = policy.AllowInspectBeforeUse;
}
/// <summary>
/// restores the defaults in the db of calibration policies
/// </summary>
public static void RestoreDefaults()
{
SettingsDB.SetGlobalValue(SENSOR_CAL_POLICY_KEY, SensorConstants.CAL_SENSOR_POLICY_DEFAULT.ToString());
SettingsDB.SetGlobalValueInt(SENSOR_WARNING_PERIOD_KEY, SensorConstants.CAL_SENSOR_POLICY_WARNING_DAYS_DEFAULT);
SettingsDB.SetGlobalValueBoolean(SENSOR_FIRST_USE_KEY, SensorConstants.SENSOR_FIRST_USE_DEFAULT);
SettingsDB.SetGlobalValueBoolean(SENSOR_OVERUSE_KEY, SensorConstants.SENSOR_OVERUSE_DEFAULT);
SettingsDB.SetGlobalValueInt(SENSOR_USAGE_REMAINING_WARNING_KEY, SensorConstants.SENSOR_USAGE_REMAINING_FOR_WARNING_DEFAULT);
SettingsDB.SetGlobalValueInt(SENSOR_DEFAULT_MAX_USAGE_KEY, SensorConstants.SENSOR_DEFAULT_MAX_USAGE_DEFAULT);
//FB 43142
SettingsDB.SetGlobalValueBoolean(ALLOW_INSPECT_BEFORE_USE, SensorConstants.ALLOW_INSPECT_BEFORE_USE_DEFAULT);
}
public void ReadXML(System.Xml.XmlElement root)
{
foreach (var node in root.ChildNodes)
{
if (node is System.Xml.XmlElement) { ProcessXMLElement(node as System.Xml.XmlElement); }
}
}
private void ProcessXMLElement(System.Xml.XmlElement node)
{
if (Enum.TryParse(node.Name, out CalPolicyXMLFields field))
{
switch (field)
{
case CalPolicyXMLFields.SelectedCalPolicy:
if (Enum.TryParse(node.InnerText, out SensorConstants.SensorCalPolicy calPolicy))
{
SelectedCalPolicy = calPolicy;
}
break;
case CalPolicyXMLFields.UseSensorFirstUseDate: UseSensorFirstUseDate = Convert.ToBoolean(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case CalPolicyXMLFields.WarningPeriod: WarningPeriod = Convert.ToInt32(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case CalPolicyXMLFields.DontAllowDataCollectionIfOverused: DontAllowDataCollectionIfOverused = Convert.ToBoolean(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case CalPolicyXMLFields.UsageRemainingForWarning: UsageRemainingForWarning = Convert.ToInt32(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
case CalPolicyXMLFields.DefaultMaxUsageAllowed: DefaultMaxUsageAllowed = Convert.ToInt32(node.InnerText, System.Globalization.CultureInfo.InvariantCulture); break;
default: throw new NotSupportedException("CalibrationPolicy::ProcessXMLElement unsupported field: " + field);
}
}
}
public void WriteXML(ref XmlWriter writer)
{
writer.WriteStartElement("CalibrationPolicy");
writer.WriteStartElement(CalPolicyXMLFields.SelectedCalPolicy.ToString());
writer.WriteString(SelectedCalPolicy.ToString());
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.UseSensorFirstUseDate.ToString());
writer.WriteString(UseSensorFirstUseDate.ToString());
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.WarningPeriod.ToString());
writer.WriteString(WarningPeriod.ToString(System.Globalization.CultureInfo.InvariantCulture));
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.DontAllowDataCollectionIfOverused.ToString());
writer.WriteString(DontAllowDataCollectionIfOverused.ToString());
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.UsageRemainingForWarning.ToString());
writer.WriteString(UsageRemainingForWarning.ToString());
writer.WriteEndElement();
writer.WriteStartElement(CalPolicyXMLFields.DefaultMaxUsageAllowed.ToString());
writer.WriteString(DefaultMaxUsageAllowed.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
}
public enum CalPolicyXMLFields
{
SelectedCalPolicy,
UseSensorFirstUseDate,
WarningPeriod,
DontAllowDataCollectionIfOverused,
UsageRemainingForWarning,
DefaultMaxUsageAllowed
}
}

View File

@@ -0,0 +1,63 @@
using DTS.Common.Classes.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Slice.Users.UserSettings;
using DTS.Common.Constant;
namespace DTS.SensorDB
{
public sealed class CanSettingDefaults : Common.Base.BasePropertyChanged, ICanSettingDefaults
{
private readonly ISensorData _defaultCan;
public bool IsFD { get => _defaultCan.CanIsFD; set => _defaultCan.CanIsFD = value; }
public int ArbBaseBitrate { get => _defaultCan.CanArbBaseBitrate; set => _defaultCan.CanArbBaseBitrate = value; }
public int ArbBaseSJW { get => _defaultCan.CanArbBaseSJW; set => _defaultCan.CanArbBaseSJW = value; }
public int DataBitrate { get => _defaultCan.CanDataBitrate; set => _defaultCan.CanDataBitrate = value; }
public int DataSJW { get => _defaultCan.CanDataSJW; set => _defaultCan.CanDataSJW = value; }
public string FileType { get => _defaultCan.CanFileType; set => _defaultCan.CanFileType = value; }
public bool Validate()
{
return true;
}
public static void CommitChange(CanSettingDefaults settingDefaults, int userID)
{
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANIsFD, settingDefaults.IsFD);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANArbBaseBitrate, settingDefaults.ArbBaseBitrate);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANArbBaseSJW, settingDefaults.ArbBaseSJW);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANDataBitrate, settingDefaults.DataBitrate);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANDataSJW, settingDefaults.DataSJW);
TestSetupDefaults.SetUserSetting(userID, PropertyEnums.PropertyIds.DefaultCANFileType, settingDefaults.FileType);
}
public static CanSettingDefaults GetCanSettingsDefault(int userID)
{
var sd = new SensorData()
{
CanIsFD = TestSetupDefaults.GetUserSettingValueBool(userID, PropertyEnums.PropertyIds.DefaultCANIsFD),
CanArbBaseBitrate = TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultCANArbBaseBitrate),
CanArbBaseSJW = TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultCANArbBaseSJW),
CanDataBitrate = TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultCANDataBitrate),
CanDataSJW = TestSetupDefaults.GetUserSettingValueInt(userID, PropertyEnums.PropertyIds.DefaultCANDataSJW),
CanFileType = TestSetupDefaults.GetUserSettingValueString(userID, PropertyEnums.PropertyIds.DefaultCANFileType)
};
return new CanSettingDefaults(sd);
}
private CanSettingDefaults(ISensorData defaultCan)
{
_defaultCan = defaultCan;
}
public static void RestoreDefaults(ICanSettingDefaults sensorDefaults)
{
sensorDefaults.IsFD = EmbeddedSensors.CANISFD_DEFAULT;
sensorDefaults.ArbBaseBitrate = EmbeddedSensors.CANFD_ARB_BASE_BITRATE_DEFAULT;
sensorDefaults.ArbBaseSJW = EmbeddedSensors.CANFD_1000000_ARB_BASE_SJW_MAX;
sensorDefaults.DataBitrate = EmbeddedSensors.DATA_BITRATE_DEFAULT;
sensorDefaults.DataSJW = EmbeddedSensors.DATA_SJW_DEFAULT;
sensorDefaults.FileType = EmbeddedSensors.FILETYPE_DEFAULT;
}
}
}

View File

@@ -0,0 +1,445 @@
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram MajorVersion="1" MinorVersion="1">
<Class Name="DTS.SensorDB.CalibrationRecords" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="16.25" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>IAAAAAAAEAEAAAAAAQAgAQAAEAAAAAAAAQAAAAAAAAA=</HashCode>
<FileName>CalibrationRecords.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.CalibrationRecord" Collapsed="true">
<Position X="14.5" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AICgAAAAEwIQBAgAEQAAAQIAQVAIAACAAAAAAIBAAAA=</HashCode>
<FileName>CalibrationRecords.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.DigitalInputSetting" Collapsed="true">
<Position X="0.5" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>DigitalInputSetting.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.DigitalOutputSetting" Collapsed="true">
<Position X="2.75" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAEAAQAAAAAAAIAAAAAAAgAEAAAAAAAAAAAAAAEA=</HashCode>
<FileName>DigitalOutputSetting.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.FilterClass" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="18" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAQAQAABAAAAAAAEoAQAAAAAgKEgAIAAAIAgARCABAA=</HashCode>
<FileName>FilterClass.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.IsoCode" Collapsed="true">
<Position X="18" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AEAAOAAAAAAEgIggACUokAAAAAAAACAAAAAIQIAAAAA=</HashCode>
<FileName>IsoCode.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.MeasurementUnit" Collapsed="true">
<Position X="21.5" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAEQAAEAAAIAAAEgAAABCAAAAQASAAAAAAAAAEAgAA=</HashCode>
<FileName>MeasurementUnit.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.MeasurementUnitList" Collapsed="true">
<Position X="23.25" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AIAEEIAAAAAgAAAAAAAAAAAAAECAAAAIAAIAAggAAAI=</HashCode>
<FileName>MeasurementUnit.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorCalibration" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="14.5" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>IEAAQFEIWCEKICUCsxAAkQQAoAFAAoAARGsRAAAhAAA=</HashCode>
<FileName>SensorCalibration.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SensorCalibrationList" Collapsed="true">
<Position X="16.25" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAEAAAAAAAAQgAABAAAQAMgEIAAAADAgBAAABAAA=</HashCode>
<FileName>SensorCalibrationList.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorData" Collapsed="true">
<Position X="2.75" Y="5" Width="1.5" />
<TypeIdentifier>
<HashCode>2EBMPEBcPHgEIQSlcs3AAQWCyIMUiocC7DGLhSUIBYU=</HashCode>
<FileName>SensorData.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" />
</Class>
<Class Name="DTS.SensorDB.LowHigh" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="19.75" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAQAgAAAAAAABAAAIhQAAAACgAlAAAAAQAAAARAAAAA=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SensorDBTables" Collapsed="true">
<Position X="19.75" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAA4ZaACBVDBIEYoAAmAocEhAgQgQCCTCwCQQoIHEE=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorDBBase" Collapsed="true">
<Position X="18" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>CAAAAAAAJAAAAQAAAAAAAAAAAAAAAAAAAAQAAAAAAAA=</HashCode>
<FileName>SensorDBBase.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorInformationFile" Collapsed="true">
<Position X="21.5" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>QAAAAgBAAAAAAAAAAAAAAQAgIAAAAIAAAAAAAAAAAEA=</HashCode>
<FileName>SensorInformationFile.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorBase" Collapsed="true">
<Position X="3.75" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>Mm5USGQAIBAIaASAAWhABICCAZhQJApxQluOwpwiCKs=</HashCode>
<FileName>SensorModel.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.SensorModel" Collapsed="true">
<Position X="7.25" Y="5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAQAAAAAAAEAoAAAAAAAAAAAgEAAAAAAAAACIE=</HashCode>
<FileName>SensorModel.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" />
</Class>
<Class Name="DTS.SensorDB.SensorModelCollection" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="23.25" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAEAAAQQACEIgIACEAIAAgIGIgAAgAEAAAEgAAAA=</HashCode>
<FileName>SensorModel.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SensorRange" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="25" Y="2.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACQAAAAAAAAAAAAAIhQAAgACgAlAAAAAAAAAARAEAAA=</HashCode>
<FileName>SensorRange.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SensorsCollection" Collapsed="true" BaseTypeListCollapsed="true">
<Position X="14.5" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AIAAIEGAAYACAAYkIAAEIIDIgAFARANEGMEgCANAAAE=</HashCode>
<FileName>SensorsCollection.cs</FileName>
</TypeIdentifier>
<Lollipop Position="0.2" Collapsed="true" />
</Class>
<Class Name="DTS.SensorDB.SquibSetting" Collapsed="true">
<Position X="5" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAgAAEAAQAAAAAAAAAAAAAQAAACEAAAAwAAAAAAAAAA=</HashCode>
<FileName>SquibSetting.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.StringResources" Collapsed="true">
<Position X="16.25" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAAAABEAAAAQAAAUAAAAAAAAAAAIA=</HashCode>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.Strings" Collapsed="true">
<Position X="18" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>wBKgBCDBDyAEQQl4BBABEAIgEQgABAIQAgACAABADMA=</HashCode>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINIFile" Collapsed="true">
<Position X="21.5" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>OWOOJv/hAMuGGvz0YvB5gz3K/JhVLU5Ii8qhUTsjIG4=</HashCode>
<FileName>TDCINI\TDCINIFile.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.G5DigtalInputChannelTSFEntry" Collapsed="true">
<Position X="0.75" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>IAABCGAAAAAAAAAEAAIAAAAAACAAAgAEAAAgCAgABCI=</HashCode>
<FileName>TSF\G5DigitalInputChannelTSFEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFCalibrationInformation" Collapsed="true">
<Position X="16.25" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>KAgCDAAgAkAAIQBgIBAAQgAYGAAAACEAIAABAKJCEAQ=</HashCode>
<FileName>TSF\TSFCalibrationInformation.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFChannel" Collapsed="true">
<Position X="6.25" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAABAAAAAAAAAAAAAAAAAAIAAAAAAAAQAAAAAAA=</HashCode>
<FileName>TSF\TSFChannel.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFChannelDescription" Collapsed="true">
<Position X="18" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>IAAABQAAA0AAIASQKgCAaACQQgBmgBEAIxAAEAXACCA=</HashCode>
<FileName>TSF\TSFChannelDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFTOMDigitalOutputChannel" Collapsed="true">
<Position X="12" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>ADABACAEAAAiIAQEABAAAAAAAAAIAgAAAQAACAgAAAA=</HashCode>
<FileName>TSF\TSFDigitalChannel.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFFile" Collapsed="true">
<Position X="21.5" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAkFQAAoAAAAAmRCIAAgAQgAQgEAIE0GAAAhAAAAUAU=</HashCode>
<FileName>TSF\TSFFile.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFInputChannelDescription" Collapsed="true">
<Position X="14.5" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>MBgAAQARIkUAIMAAAgEGQCExIcBCKAIAAAAhVQBACAA=</HashCode>
<FileName>TSF\TSFInputChannelDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFModuleDescription" Collapsed="true">
<Position X="16.25" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>JACAACABs0AAIAQAAhAoQIIQAAIkBAEAAREEAABAAiA=</HashCode>
<FileName>TSF\TSFModuleDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFOutputChannelDescription" Collapsed="true">
<Position X="19.75" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>KAAAAAIKCkgGIQCAMghAQAwYiAQCCAEQBAABDCFCAAA=</HashCode>
<FileName>TSF\TSFOutputChannelDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFRackDescription" Collapsed="true">
<Position X="21.5" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>OQDARQiCQ0AILAQEAMEIYJAwCAhEABICFRkQgQBAIAE=</HashCode>
<FileName>TSF\TSFRackDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFSensorEntry" Collapsed="true">
<Position X="5.25" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAIRMGQACEEgBAAAAAABAIAACZEFgkAIAAAgCCEAlBI=</HashCode>
<FileName>TSF\TSFSensorEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFSquibFireEntry" Collapsed="true">
<Position X="7.5" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>ABADACAEAAAiIARAADDAAAAAACAMAgAAAQABTggAAAA=</HashCode>
<FileName>TSF\TSFSquibFireEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSFSystemDescription" Collapsed="true">
<Position X="16.25" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>MRAkGEgYA0hQLAFMAIEBQmAkAAKQAQCGEAgAgAJILAA=</HashCode>
<FileName>TSF\TSFSystemDescription.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIDataZeroTimeWindowSeconds" Collapsed="true">
<Position X="19.75" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAIAAAAAACAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>TDCINI\INIDataZeroTimeWindowSeconds.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIIIHSExport" Collapsed="true">
<Position X="21.5" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AQEAAAAAAAAAAAAAAAAAAAQgAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>TDCINI\INIIIHSExport.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIISOExportParameters" Collapsed="true">
<Position X="23.25" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAACAAAAACAAAEAAAAAAAoACAAABAAAAAAEAAQIAA=</HashCode>
<FileName>TDCINI\INIISOExportParameters.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIRackInventory" Collapsed="true">
<Position X="25" Y="0.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAACAAAAAAAAAAAAAAAAAgAgAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>TDCINI\INIRackInventory.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INISmartBatteryThresholds" Collapsed="true">
<Position X="14.5" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAgAAAAAAAAAgAAAAAAAAAAAAACAAAAA=</HashCode>
<FileName>TDCINI\INISmartBatteryThresholds.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.INIViewerROI" Collapsed="true">
<Position X="16.25" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAACAACAAgAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>TDCINI\INIViewerROI.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.TDCINIError" Collapsed="true">
<Position X="19.75" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAQBAAAABAAAAAAAAIAAAAAAQAAABAAA=</HashCode>
<FileName>TDCINI\TDCINIError.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.TDCINIRS232Info" Collapsed="true">
<Position X="23.25" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAAABAAAAgAAAAAAAAAAAAAAQBAAA=</HashCode>
<FileName>TDCINI\TDCINIRS232Info.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDCINI.TSFINIRegionOfInterest" Collapsed="true">
<Position X="25" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAAIAAAAAgAAAAAAAAAAAAAgAAAAA=</HashCode>
<FileName>TDCINI\TSFINIRegionOfInterest.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TDM.TDMCSVImport" Collapsed="true">
<Position X="25" Y="3.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAAAAAAABAAAQAAAACAABIAAAAAAAAAA=</HashCode>
<FileName>TDM\TDMCSVImport.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.ReadTSFError" Collapsed="true">
<Position X="25" Y="1.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAQBAAAAJAAAAAAAAIAAAAAAQAAAAAAA=</HashCode>
<FileName>TSF\ReadTSFError.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFTOMChannelInformationSection" Collapsed="true">
<Position X="19.75" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>gAAAAAAAAAAAAADAAJAAAAAiAAQAAIAAAAAAAAAgAIA=</HashCode>
<FileName>TSF\TOMChannelInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFCalculatedChannelEntry" Collapsed="true">
<Position X="3" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AFAAIBABAABgAAAHAAAxAAAIAQAAAgAAAAAgAAmgAAA=</HashCode>
<FileName>TSF\TSFCalculatedChannelEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFCalculatedChannelInformationSection" Collapsed="true">
<Position X="14.5" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACAAAAAAAAAAAAAAAAAAAAQgAAEAAEAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFCalculatedChannelInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFDIMEntry" Collapsed="true">
<Position X="9.75" Y="1.75" Width="1.5" />
<TypeIdentifier>
<HashCode>EBABAOgCAIAoAAQEAgIAACAAACEAAgCAAAAgCAxQBCI=</HashCode>
<FileName>TSF\TSFDIMEntry.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFDIMSection" Collapsed="true">
<Position X="19.75" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ECAAAAAAAAAAAAAAAAAAAAAgAIAAAEAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFDIMSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFG5DigitalInputSection" Collapsed="true">
<Position X="23.25" Y="4.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACBAAAAAAAAAAAAAAAgAAAAgAAAAAEAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFG5DigitalInputSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFModuleInformationSection" Collapsed="true">
<Position X="18" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACAAAAAAAAAAAAAAAAAAAAAgAAAAAEAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFModuleInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFRackInformationSection" Collapsed="true">
<Position X="23.25" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAACAAAAAAAAAAAAAAAAAgAgQAAMAAAAAAAAAAAAA=</HashCode>
<FileName>TSF\TSFRackInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFSamplingInformationSection" Collapsed="true">
<Position X="25" Y="5.5" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAACCRAAAAAABAAAAAAAAAAgQAAMEEAAYAAAAAAAA=</HashCode>
<FileName>TSF\TSFSamplingInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFSensorChannelInformationSection" Collapsed="true">
<Position X="14.5" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>CCAAAAAAAAAAACEAAAIAAAAgAAAAAAAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFSensorChannelInformationSection.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="DTS.SensorDB.TSF.TSFTCFSection" Collapsed="true">
<Position X="18" Y="6.5" Width="1.5" />
<TypeIdentifier>
<HashCode>ACAAAAAAAAAAAAAAAAAAAAAwAAAACAAAAAAAAAABAAA=</HashCode>
<FileName>TSF\TSFTCFSection.cs</FileName>
</TypeIdentifier>
</Class>
<Enum Name="DTS.SensorDB.ShuntMode" Collapsed="true">
<Position X="18" Y="7.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAIAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAEACAA=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
</Enum>
<Enum Name="DTS.SensorDB.BridgeLeg" Collapsed="true">
<Position X="14.5" Y="7.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAgAAAAAAAQAAAAAAAAIAAAAAAAAAAAAAAAAAAQA=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
</Enum>
<Enum Name="DTS.SensorDB.CouplingModes" Collapsed="true">
<Position X="16.25" Y="7.75" Width="1.5" />
<TypeIdentifier>
<HashCode>AAAAAAAAAAAAAABAAgAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
<FileName>SensorDB.cs</FileName>
</TypeIdentifier>
</Enum>
<Font Name="Segoe UI" Size="9" />
</ClassDiagram>

View File

@@ -0,0 +1,99 @@
using DTS.Common.Interface.Sensors;
using DTS.Common.Settings;
namespace DTS.SensorDB
{
public class DigitalInputSensorDefault : DTS.Common.Base.BasePropertyChanged, IDigitalInputDefaults
{
private double _constantCurrentBreakpoint;
/// <summary>
/// breakpoint in ADC where transition is made from active state to default state or vice versa
/// only valid for Constant Current Normally Open (CCNO) or Normally Closed (CCNC)
/// </summary>
public double ConstantCurrentBreakpointADC
{
get => _constantCurrentBreakpoint;
set => SetProperty(ref _constantCurrentBreakpoint, value, "ConstantCurrentBreakpointADC");
}
private double _voltageBreakpoint;
/// <summary>
/// breakpoint in ADC where transition is made from active state to default state or vice versa
/// only valid for Transition High to Low (THL) or (TLH)
/// </summary>
public double VoltageBreakpointADC
{
get => _voltageBreakpoint;
set => SetProperty(ref _voltageBreakpoint, value, "VoltageBreakpointADC");
}
private bool _displaySPDADC;
/// <summary>
/// whether to display analog SLICE PRO DIGITAL ADC data
/// </summary>
public bool DisplaySPDADC
{
get => _displaySPDADC;
set => SetProperty(ref _displaySPDADC, value, "DisplaySPDADC");
}
/// <summary>
/// returns true if properties are valid
/// </summary>
/// <returns></returns>
public bool Validate()
{
return true;
}
private const string VOLTAGE_INPUT_KEY = "VoltageInputBreakpoint";
private const string CONSTANT_CURRENT_KEY = "ConstantCurrentInputBreakpoint";
private const string DISPLAY_SPD_ADC_KEY = "DisplaySPDADC";
/// <summary>
/// returns the defaults for digital inputs
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public static IDigitalInputDefaults GetDigitalInputDefaults(string user)
{
var ccDefault = SettingsDB.GetGlobalValueDouble(CONSTANT_CURRENT_KEY,
DTS.Common.Constant.DigitalInputs.ConstantCurrentBreakPointDefault);
var voltageDefault = SettingsDB.GetGlobalValueDouble(VOLTAGE_INPUT_KEY,
DTS.Common.Constant.DigitalInputs.VoltageInputBreakPointDefault);
var displaySPDADC = SettingsDB.GetGlobalValueBool(DISPLAY_SPD_ADC_KEY,
DTS.Common.Constant.DigitalInputs.DisplaySPDADCDefault);
return new DigitalInputSensorDefault()
{
ConstantCurrentBreakpointADC = ccDefault,
VoltageBreakpointADC = voltageDefault,
DisplaySPDADC = displaySPDADC
};
}
/// <summary>
/// commits digital inputs to storage
/// </summary>
/// <param name="defaults"></param>
public static void Save(IDigitalInputDefaults defaults)
{
SettingsDB.SetGlobalValueDouble(CONSTANT_CURRENT_KEY, defaults.ConstantCurrentBreakpointADC);
SettingsDB.SetGlobalValueDouble(VOLTAGE_INPUT_KEY, defaults.VoltageBreakpointADC);
SettingsDB.SetGlobalValueBoolean(DISPLAY_SPD_ADC_KEY, defaults.DisplaySPDADC);
DTS.Common.Constant.DigitalInputs.ConstantCurrentBreakPoint = defaults.ConstantCurrentBreakpointADC;
DTS.Common.Constant.DigitalInputs.VoltageInputBreakPoint = defaults.VoltageBreakpointADC;
DTS.Common.Constant.DigitalInputs.DisplaySPDADC = defaults.DisplaySPDADC;
}
/// <summary>
/// restores digital input settings to defaults
/// </summary>
/// <param name="sensorDefaults"></param>
public static void RestoreDefaults(IDigitalInputDefaults sensorDefaults)
{
sensorDefaults.ConstantCurrentBreakpointADC = DTS.Common.Constant.DigitalInputs.ConstantCurrentBreakPointDefault;
sensorDefaults.VoltageBreakpointADC = DTS.Common.Constant.DigitalInputs.VoltageInputBreakPointDefault;
sensorDefaults.DisplaySPDADC = DTS.Common.Constant.DigitalInputs.DisplaySPDADC;
}
}
}

View File

@@ -0,0 +1,140 @@
using System;
using System.Data;
using System.Data.SqlClient;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
namespace DTS.SensorDB
{
/// <summary>
/// Digital Inputs allow collected data to behave consistently with a digital data source
/// the settings are for configuring firmware appropriately and for transforming data for consumption
/// </summary>
public class DigitalInputSetting : SensorData
{
/// <summary>
/// constructor and copy constructor
/// </summary>
public DigitalInputSetting() : base()
{
SetDefaults(this);
}
public DigitalInputSetting(IDigitalInDbRecord record) : base()
{
SetDefaults(this);
try
{
DatabaseId = record.Id;
SettingName = record.SerialNumber;
ISOCode = record.ISOCode;
ISOChannelName = record.ISOChannelName;
UserCode = record.UserCode;
UserChannelName = record.UserChannelName;
Broken = record.Broken;
DoNotUse = record.DoNotUse;
LastModified = record.LastModified;
LastUpdatedBy = record.LastModifiedBy;
InputMode = record.Mode;
DIUnits = record.MeasurementUnit;
//Since the ISOCode is not stored in the SensorsDigitalIn table like it is in SensorsAnalog, create one
SetFilterAndFilterClassISO(record.FilterClass, true, true); //Always set Filter to 0
EID = record.EID;
UserValue1 = record.UserValue1;
UserValue2 = record.UserValue2;
UserValue3 = record.UserValue3;
TagsBlobBytes = record.UserTags;
Comment = record.UserValue1;
ScaleMultiplier.FromDbSerializeString(record.ScaleMultiplier.ToSerializeDbString());
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
}
public DigitalInputSetting(IDataRecord reader) : base()
{
SetDefaults(this);
try
{
DatabaseId = Convert.ToInt32(reader["Id"]);
SettingName = Convert.ToString(reader["SerialNumber"]);
ISOCode = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.ISOCode.ToString()]);
ISOChannelName = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.ISOChannelName.ToString()]);
UserCode = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserCode.ToString()]);
UserChannelName = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserChannelName.ToString()]);
Broken = Convert.ToBoolean(reader[DbOperations.DigitalInputSettings.Fields.Broken.ToString()]);
DoNotUse = Convert.ToBoolean(reader[DbOperations.DigitalInputSettings.Fields.DoNotUse.ToString()]);
LastModified = Convert.ToDateTime(reader[DbOperations.DigitalInputSettings.Fields.LastModified.ToString()]);
LastUpdatedBy = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.LastModifiedBy.ToString()]);
InputMode = (DigitalInputModes)Convert.ToInt32(reader[DbOperations.DigitalInputSettings.Fields.SettingMode.ToString()]);
DIUnits = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.MeasurementUnit.ToString()]);
//Since the ISOCode is not stored in the SensorsDigitalIn table like it is in SensorsAnalog, create one
SetFilterAndFilterClassISO(new FilterClass(Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.FilterClass.ToString()])), true, true); //Always set Filter to 0
EID = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.eId.ToString()]);
UserValue1 = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserValue1.ToString()]);
UserValue2 = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserValue2.ToString()]);
UserValue3 = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserValue3.ToString()]);
TagsBlobBytes = (byte[])reader[DbOperations.DigitalInputSettings.Fields.UserTags.ToString()];
Comment = Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.UserValue1.ToString()]);
ScaleMultiplier.FromDbSerializeString(Convert.ToString(reader[DbOperations.DigitalInputSettings.Fields.ScaleMultiplier.ToString()]));
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
}
public DigitalInputSetting(DigitalInputSetting copy)
: base(copy)
{
SetDefaults(this);
}
public static void SetDefaults(SensorData sd)
{
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 2400;
sd.Bridge = SensorConstants.BridgeType.DigitalInput;
sd.Capacity = 1;
sd.DisplayUnit = "V";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 2500;
sd.OffsetToleranceLow = 2500;
sd.Model = "Digital Input Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public DigitalInputSetting(SensorData sd)
: base(sd)
{
Bridge = SensorConstants.BridgeType.DigitalInput;
SetDefaults(this);
UserSerialNumber = sd.UserSerialNumber;
SerialNumber = sd.SerialNumber;
UserValue1 = sd.UserValue1;
UserValue2 = sd.UserValue2;
UserValue3 = sd.UserValue3;
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
var record = new DigitalInDbRecord(setting, setting.TagsBlobBytes, setting.ScaleMultiplier);
var hr = DbOperations.SensorsDigitalInUpdateInsert(record);
if (0 == hr)
{
setting.Id = record.Id;
}
}
}
}

View File

@@ -0,0 +1,49 @@
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
namespace DTS.SensorDB
{
/// <summary>
/// this class handles the updating the default squib settings
/// </summary>
public sealed class DigitalOutputDefaults : DTS.Common.Base.BasePropertyChanged, IDigitalOutDefaults
{
private ISensorData _defaultOut;
public DigitalOutputModes OutputMode { get => _defaultOut.DigitalOutputMode; set => _defaultOut.DigitalOutputMode = value; }
private static DigitalOutputModes[] _outputModes = new DigitalOutputModes[] { DigitalOutputModes.CCNC, DigitalOutputModes.CCNO, DigitalOutputModes.FVHL, DigitalOutputModes.FVLH };
public DigitalOutputModes[] AvailableModes { get => _outputModes; }
public double DelayMS { get => _defaultOut.DigitalOutputDelayMS; set => _defaultOut.DigitalOutputDelayMS = value; }
public bool LimitDuration
{
get => _defaultOut.DigitalOutputLimitDuration;
set
{
_defaultOut.DigitalOutputLimitDuration = value;
OnPropertyChanged("LimitDuration");
}
}
public double DurationMS { get => _defaultOut.DigitalOutputDurationMS; set => _defaultOut.DigitalOutputDurationMS = value; }
public static void CommitChange(DigitalOutputDefaults settingDefaults, string user)
{
DTS.SensorDB.SensorsCollection.SensorsList.Commit(user, (DTS.SensorDB.SensorData)settingDefaults._defaultOut, false);
}
public static DigitalOutputDefaults GetDigitalOutDefault(string user)
{
var sd = DTS.SensorDB.SensorsCollection.SensorsList.GetSensorBySerialNumber(SensorConstants.TEST_SPECIFIC_DIGITAL_OUT_SERIAL);
return new DigitalOutputDefaults(sd);
}
private DigitalOutputDefaults(ISensorData defaultOut)
{
_defaultOut = defaultOut;
}
}
}

View File

@@ -0,0 +1,138 @@
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using DTS.Common.Classes.Sensors;
using DTS.Common.Enums;
using DTS.Common.Enums.Sensors;
using DTS.Common.Interface.Sensors;
using DTS.Common.Storage;
using DTS.Common.Utilities.Logging;
namespace DTS.SensorDB
{
public class DigitalOutputSetting : SensorData
{
public string ChannelDescription
{
get => SerialNumber;
set
{
SerialNumber = value;
OnPropertyChanged("ChannelDescription");
}
}
public DigitalOutputSetting(DigitalOutputSetting copy) : base(copy)
{
SetDefaults(this);
}
public DigitalOutputSetting()
{
SetDefaults(this);
}
//public DigitalOutputSetting(SensorData sd)
// : base(sd)
//{
// SetDefaults(this);
//}
private static void SetDefaults(SensorData sd)
{
sd.SupportedExcitation = new[] { ExcitationVoltageOptions.ExcitationVoltageOption.Volt5 };
sd.Bridge = SensorConstants.BridgeType.TOMDigital;
sd.AxisNumber = 0;
sd.NumberOfAxes = 1;
sd.Capacity = 1;
sd.DisplayUnit = "V";
sd.BridgeResistance = double.NaN;
sd.CheckOffset = false;
sd.Manufacturer = "Generic";
sd.OffsetToleranceHigh = 2500;
sd.OffsetToleranceLow = 2500;
sd.Model = "Digital Output Setting";
sd.Shunt = ShuntMode.None;
sd.MeasureExcitation = false;
sd.MeasureNoise = false;
}
public DigitalOutputSetting(IDigitalOutDbRecord copy)
{
DatabaseId = copy.DatabaseId;
Broken = copy.Broken;
DoNotUse = copy.DoNotUse;
Bridge = SensorConstants.BridgeType.TOMDigital;
Version = copy.Version;
DigitalOutputMode = copy.DOMode;
DigitalOutputLimitDuration = copy.LimitDuration;
LastUpdatedBy = copy.ModifiedBy;
LastModified = copy.LastModified;
DigitalOutputDurationMS = copy.DODuration;
DigitalOutputDelayMS = copy.DODelay;
ChannelDescription = copy.SerialNumber;
SerialNumber = copy.SerialNumber;
if (null == copy.TagsBlobBytes)
{
TagsBlobBytes = null;
}
else if (copy.TagsBlobBytes.Any())
{
var bytes = new byte[copy.TagsBlobBytes.Length];
Array.Copy(copy.TagsBlobBytes, bytes, copy.TagsBlobBytes.Length);
TagsBlobBytes = bytes;
}
else
{
TagsBlobBytes = new byte[0];
}
SetDefaults(this);
}
public DigitalOutputSetting(IDataRecord reader)//, bool pre20 = false)
{
DatabaseId = Convert.ToInt32(reader["Id"]);
Broken = Convert.ToBoolean(reader[DbOperations.DigitalOutputSettings.Fields.Broken.ToString()]);
DoNotUse = Convert.ToBoolean(reader[DbOperations.DigitalOutputSettings.Fields.DoNotUse.ToString()]);
Bridge = SensorConstants.BridgeType.TOMDigital;
try
{
Version = Convert.ToInt32(reader[DbOperations.DigitalOutputSettings.Fields.Version.ToString()]);
DigitalOutputMode =
(DigitalOutputModes)Convert.ToInt16(
reader[DbOperations.DigitalOutputSettings.Fields.OutputMode.ToString()]);
//_localOnly = Convert.ToBoolean(reader[DbOperations.DigitalOutputSettings.Fields.LocalOnly.ToString()]);
DigitalOutputLimitDuration =
Convert.ToBoolean(reader[DbOperations.DigitalOutputSettings.Fields.LimitDuration.ToString()]);
LastUpdatedBy =
Convert.ToString(reader[DbOperations.DigitalOutputSettings.Fields.LastModifiedBy.ToString()]);
LastModified =
Convert.ToDateTime(reader[DbOperations.DigitalOutputSettings.Fields.LastModified.ToString()]);
DigitalOutputDurationMS =
Convert.ToDouble(reader[DbOperations.DigitalOutputSettings.Fields.DurationMSFloat.ToString()]);
DigitalOutputDelayMS =
Convert.ToDouble(reader[DbOperations.DigitalOutputSettings.Fields.DelayMS.ToString()]);
ChannelDescription = Convert.ToString(reader["SerialNumber"]);
TagsBlobBytes = (byte[])reader[DbOperations.DigitalOutputSettings.Fields.UserTags.ToString()];
}
catch (Exception ex)
{
APILogger.Log("Failed to process: ", ex);
}
SetDefaults(this);
}
public static void Commit(SensorData setting)
{
SetDefaults(setting);
var digitalOut = new DigitalOutDbRecord(setting, setting.TagsBlobBytes);
var hr = DbOperations.SensorsDigitalOutUpdateInsert(digitalOut);
if (0 == hr) { setting.DatabaseId = digitalOut.DatabaseId; }
}
}
}

Some files were not shown because too many files have changed in this diff Show More