Compare commits

..
Author SHA1 Message Date
michal 5fa9fcaeff Metrology:
- KBuoyancy calculation
- Readability column
Excel export:
- shape CC, for WT,T,Pr
2025-05-13 10:53:31 +02:00
michal df5924663a Remove obsolete license and metadata files. Added Extended CalibCertificateExtendedCtrl.cs
Deleted outdated license, third-party notices, and related metadata files for cleanup. Updated associated code configurations and UI components, including `MetrologyDlgTempMeterTab` and configuration models such as `BalanceCfg` and `TempMeterCfg`, with new fields for meter details.
2025-04-27 11:58:17 +02:00
michal 1e1f8bf8e6 Refactor uncertainty calculations and update UI functionality
Streamline uncertainty handling by modifying data structures and methods, replacing `SerNo` with a generic `val` array. Introduce `PreviousResultsDlgUncertainty` for expanded result management, and incorporate Excel template handling for uncertainty calculations. Ensure backward compatibility while refining code for clarity and efficiency.
2025-04-17 12:17:01 +02:00
michal 0d7fe67cd6 Add uncertainty handling and Excel process integration
This commit introduces uncertainty-related functionality with new items in `WMeterRsltItemSpec`, additional document sheet handling (`DocumentSheets`), and Excel processing via `CommonExcell`. Added tests ensure proper usage of uncertainty data and support for Excel files in `RigUncertaintyTest`.
2025-04-09 13:42:41 +02:00
michal 78bc9e264b Add uncertainty field to measurement corrections
Introduce a new "uncertainty" field to measurement correction entities and integrate it across various UI tabs and database structures. This includes adding uncertainty input fields, handling editing and display logic, updating configurations, and adjusting mappings. Additionally, add a ReadMe file with instructions for the database update.
2025-03-26 10:30:39 +01:00
948 changed files with 389400 additions and 543627 deletions
+4 -13
View File
@@ -1,5 +1,3 @@
AppDiagnostic/bin/
AppDiagnostic/obj/
Common/bin/
Common/obj/
Config/bin/
@@ -32,8 +30,6 @@ LabelPrinting/bin/
LabelPrinting/obj/
MergeResultsDBs/bin/
MergeResultsDBs/obj/
NfcC7_Dll/bin/
NfcC7_Dll/obj/
OrderManagement/bin/
OrderManagement/obj/
ProductionTracing/bin/
@@ -52,18 +48,14 @@ ResultsParser/bin/
ResultsParser/obj/
S640TestApp/bin/
S640TestApp/obj/
SharedComponents/bin/
SharedComponents/obj/
SharedDatabase/bin/
SharedDatabase/obj/
SchematicDrawing/bin/
SchematicDrawing/obj/
SharedDatabase/bin
SharedDatabase/obj
SchematicDrawing/bin
SchematicDrawing/obj
Statistics/bin/
Statistics/obj/
TBF/bin/
TBF/obj/
TBFTests/bin/
TBFTests/obj/
ToFirstMonitor/bin/
ToFirstMonitor/obj/
ToSecondMonitor/bin/
@@ -88,4 +80,3 @@ Users/obj/
.idea/
*.suo
*.bak
TBF.sln.DotSettings.user
-19
View File
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<log4net>
<appender name="LogCacheAppender" type="Namespace.LogCacheAppender, AssemblyName">
<param name="Cache" value="YourCacheInstance" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogCacheAppender" />
</root>
</log4net>
</configuration>
-101
View File
@@ -1,101 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>AppDiagnostic</RootNamespace>
<AssemblyName>AppDiagnostic</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=3.0.3.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.0.3\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BufferedListView.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="DiagApi.cs" />
<Compile Include="LogAdapter.cs" />
<Compile Include="LogFilter.cs" />
<Compile Include="MainForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="MainForm.Designer.cs">
<DependentUpon>MainForm.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="MainForm.resx">
<DependentUpon>MainForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SharedComponents\SharedComponents.csproj">
<Project>{8f942729-f454-4c99-ba6c-746962065ae3}</Project>
<Name>SharedComponents</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
-16
View File
@@ -1,16 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public class BufferedListView : ListView
{
public BufferedListView()
{
// Zapne dvojité bufferovanie pre ListView
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
this.UpdateStyles();
}
}
-32
View File
@@ -1,32 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDiagnostic
{
public class DiagApi
{
private static MainForm diagWindow; // Udržiava referenciu na existujúce okno
public DiagApi()
{
if (diagWindow == null || diagWindow.IsDisposed) // Ak okno neexistuje, vytvoríme ho
{
diagWindow = new MainForm();
diagWindow.FormClosing += (s, e) =>
{
diagWindow = null; // Keď sa zavrie, vyčistíme referenciu
};
diagWindow.Show();
}
else
{
diagWindow.BringToFront(); // Ak už beží, len ho presunieme na vrch
diagWindow.WindowState = FormWindowState.Normal; // Ak je minimalizované, obnovíme ho
}
}
}
}
-174
View File
@@ -1,174 +0,0 @@
using SharedComponents;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDiagnostic
{
public class LogAdapter
{
private ListView _listView;
public string _filterText = string.Empty;
private bool _isUserScrolling = false; // Indikátor, že používateľ manuálne scrolluje
private bool _autoScrollEnabled = true; // Indikátor, že automatické scrollovanie je povolené
private Timer _refreshTimer;
private const int RefreshInterval = 1000;
public LogAdapter(ListView listView)
{
_listView = listView;
// Nastavenie ListView
_listView.View = View.Details;
_listView.Columns.Clear();
_listView.Columns.Add("Logs");
_listView.Scrollable = true;
// Nastavenie šírky stĺpca na celú šírku ListView
AdjustColumnWidth();
// Udalosť pre dynamickú zmenu veľkosti stĺpca pri zmene veľkosti ListView
_listView.Resize += (sender, args) => AdjustColumnWidth();
// Pridanie udalosti pre manuálne skrolovanie
_listView.MouseWheel += ListView_MouseWheel;
// Inicializácia časovača na pravidelný refresh
_refreshTimer = new Timer { Interval = RefreshInterval };
_refreshTimer.Tick += (sender, args) => RefreshListView();
_refreshTimer.Start();
}
private void ListView_MouseWheel(object sender, MouseEventArgs e)
{
_isUserScrolling = true;
// Ak sa manuálnym scrollovaním používateľ dostane na koniec, obnovíme automatické scrollovanie
if (IsOnLastItem())
{
_isUserScrolling = false;
_autoScrollEnabled = true;
}
else
{
_autoScrollEnabled = false;
}
}
public void RefreshListView()
{
//LiveLogCache.Instance.AddLog(string.Format("-------------------------------RunDeviceAfter()-------------------------------"));
if (_listView.InvokeRequired)
{
_listView.Invoke(new Action(RefreshListView));
return;
}
_listView.BeginUpdate();
try
{
// Získanie pozície prvého viditeľného prvku pre stabilizáciu scrollovania
int topIndexBeforeRefresh = _listView.TopItem?.Index ?? 0;
// Pred pridaním nových položiek si pamätáme, či bol používateľ na poslednej položke
bool wasOnLastItem = IsOnLastItem();
// Uchovanie aktuálne označených položiek (indexov)
var selectedIndices = _listView.SelectedIndices.Cast<int>().ToList();
// Načítanie logov
var logs = LiveLogCache.Instance.GetLogs(0, LiveLogCache.Instance.GetCount())
.Where(log => string.IsNullOrEmpty(_filterText) ||
log.IndexOf(_filterText, StringComparison.OrdinalIgnoreCase) >= 0)
.ToList();
// Vymazanie existujúcich položiek a pridanie nových
_listView.Items.Clear();
foreach (var log in logs)
{
var item = new ListViewItem(log)
{
BackColor = _listView.Items.Count % 2 == 0 ? Color.White : Color.FromArgb(240, 240, 240)
};
_listView.Items.Add(item);
}
// Obnovenie označených položiek
foreach (var index in selectedIndices)
{
if (index < _listView.Items.Count)
{
_listView.Items[index].Selected = true;
}
}
// Ak bol používateľ na poslednom prvku, nastavíme focus a scroll na posledný prvok
if (_autoScrollEnabled && wasOnLastItem && _listView.Items.Count > 0)
{
var lastItemIndex = _listView.Items.Count - 1;
_listView.EnsureVisible(lastItemIndex);
_listView.Items[lastItemIndex].Focused = true;
}
else
{
// Ak používateľ nebol na spodku, vrátime sa na predchádzajúcu pozíciu scrollu
if (topIndexBeforeRefresh < _listView.Items.Count)
{
_listView.TopItem = _listView.Items[topIndexBeforeRefresh];
}
}
}
finally
{
_listView.EndUpdate();
}
}
public void ApplyFilter(string filterText)
{
_filterText = filterText?.Trim() ?? string.Empty;
RefreshListView();
}
private bool IsOnLastItem()
{
if (_listView.Items.Count == 0)
return false;
// Získame poslednú položku
int lastItemIndex = _listView.Items.Count - 1;
var lastItem = _listView.Items[lastItemIndex];
// Overíme, či je posledná položka úplne viditeľná
return lastItem.Bounds.Bottom <= _listView.ClientRectangle.Bottom;
}
public void EnableAutoScroll()
{
_autoScrollEnabled = true;
}
public void DisableAutoScroll()
{
_autoScrollEnabled = false;
}
private void AdjustColumnWidth()
{
if (_listView.Columns.Count > 0)
{
_listView.Columns[0].Width = _listView.ClientSize.Width;
}
}
}
}
-91
View File
@@ -1,91 +0,0 @@
using SharedComponents;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDiagnostic
{
public class LogFilter
{
private ListView _listView;
private string _filterText = string.Empty; // Pre uloženie aktuálneho filtrovaného reťazca
// Konstruktor
public LogFilter(ListView listView)
{
_listView = listView;
}
// Metóda na aplikovanie filtra na ListView
public void ApplyFilter(string filterText)
{
_filterText = filterText.ToLower(); // Ukladáme text filtra bez ohľadu na veľkosť písmen
// Po aplikovaní filtra obnovíme zobrazenie
RefreshListView();
}
public void RefreshListView()
{
try
{
// Skontrolujeme, či sme na hlavnom vlákne a v prípade potreby použijeme Invoke
if (_listView.InvokeRequired)
{
// Použijeme Invoke, ak nie sme na hlavnom vlákne
_listView.Invoke(new Action(RefreshListView));
}
else
{
// Vymazanie existujúcich položiek
_listView.Items.Clear();
// Načítame všetky logy (ideálne z cache alebo databázy)
var logs = LiveLogCache.Instance.GetLogs(0, LiveLogCache.Instance.Logs.Count);
// Pridáme len tie logy, ktoré spĺňajú filter
foreach (var log in logs)
{
if (log.ToLower().Contains(_filterText)) // Kontrola, či log obsahuje filter text
{
var listViewItem = new ListViewItem(log);
// Striedanie farieb riadkov
if (_listView.Items.Count % 2 == 0) // Párny index => biela
{
listViewItem.BackColor = Color.White;
}
else // Nepárny index => svetlá sivá
{
listViewItem.BackColor = Color.FromArgb(240, 240, 240); // Veľmi svetlá sivá
}
// Pridanie efektu pre novú položku
ApplyNewItemEffect(listViewItem);
// Pridanie položky do ListView
_listView.Items.Add(listViewItem);
}
}
}
}
catch (Exception ex)
{
// Zachytíme výnimku, ak sa niečo pokazí, a zobrazíme ju užívateľovi
MessageBox.Show($"An error occurred while refreshing the log view: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Môžete pridať ďalšie metódy na zobrazenie alebo efekt pre nové položky, ak je to potrebné
private void ApplyNewItemEffect(ListViewItem item)
{
// Prípadný efekt pre nový pridaný log
// Môžete pridať animáciu alebo zmenu farby atď.
item.ForeColor = Color.Green; // Napríklad zmeníme farbu písma na zelenú
}
}
}
-278
View File
@@ -1,278 +0,0 @@
using System.Windows.Forms;
namespace AppDiagnostic
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
//private BufferedListView memoListView;
private System.Windows.Forms.ColumnHeader columnHeaderTime;
private System.Windows.Forms.ColumnHeader columnHeaderMessage;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.columnHeaderTime = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeaderMessage = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.panel1 = new System.Windows.Forms.Panel();
this.refreshMemoButton = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.filterManagementPanel = new System.Windows.Forms.Panel();
this.button5 = new System.Windows.Forms.Button();
this.filterButton = new System.Windows.Forms.Button();
this.filterTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.wndControlPanel = new System.Windows.Forms.Panel();
this.button2 = new System.Windows.Forms.Button();
this.flowControlsPanel = new System.Windows.Forms.Panel();
this.runButton = new System.Windows.Forms.Button();
this.stopButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.memoListView = new BufferedListView();
this.panel1.SuspendLayout();
this.filterManagementPanel.SuspendLayout();
this.wndControlPanel.SuspendLayout();
this.flowControlsPanel.SuspendLayout();
this.SuspendLayout();
//
// columnHeaderTime
//
this.columnHeaderTime.Text = "Time";
this.columnHeaderTime.Width = 150;
//
// columnHeaderMessage
//
this.columnHeaderMessage.Text = "Message";
this.columnHeaderMessage.Width = 350;
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.panel1.Controls.Add(this.refreshMemoButton);
this.panel1.Controls.Add(this.button6);
this.panel1.Controls.Add(this.button7);
this.panel1.Location = new System.Drawing.Point(189, 356);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(283, 26);
this.panel1.TabIndex = 16;
//
// refreshMemoButton
//
this.refreshMemoButton.Location = new System.Drawing.Point(108, 0);
this.refreshMemoButton.Name = "refreshMemoButton";
this.refreshMemoButton.Size = new System.Drawing.Size(84, 26);
this.refreshMemoButton.TabIndex = 17;
this.refreshMemoButton.Text = "Refresh memo";
this.refreshMemoButton.UseVisualStyleBackColor = true;
this.refreshMemoButton.Click += new System.EventHandler(this.refreshMemoButton_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(0, 0);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(102, 26);
this.button6.TabIndex = 4;
this.button6.Text = "Clean diag cache";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// button7
//
this.button7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button7.Location = new System.Drawing.Point(198, 0);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(72, 26);
this.button7.TabIndex = 5;
this.button7.Text = "Save logs";
this.button7.UseVisualStyleBackColor = true;
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// filterManagementPanel
//
this.filterManagementPanel.Controls.Add(this.button5);
this.filterManagementPanel.Controls.Add(this.filterButton);
this.filterManagementPanel.Controls.Add(this.filterTextBox);
this.filterManagementPanel.Controls.Add(this.label2);
this.filterManagementPanel.Location = new System.Drawing.Point(127, 6);
this.filterManagementPanel.Name = "filterManagementPanel";
this.filterManagementPanel.Size = new System.Drawing.Size(393, 26);
this.filterManagementPanel.TabIndex = 15;
//
// button5
//
this.button5.Enabled = false;
this.button5.Location = new System.Drawing.Point(294, 4);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(81, 20);
this.button5.TabIndex = 11;
this.button5.Text = "Add new filter";
this.button5.UseVisualStyleBackColor = true;
//
// filterButton
//
this.filterButton.Location = new System.Drawing.Point(225, 4);
this.filterButton.Name = "filterButton";
this.filterButton.Size = new System.Drawing.Size(64, 20);
this.filterButton.TabIndex = 10;
this.filterButton.Text = "Set filter";
this.filterButton.UseVisualStyleBackColor = true;
this.filterButton.Click += new System.EventHandler(this.filterButton_Click_1);
//
// filterTextBox
//
this.filterTextBox.Location = new System.Drawing.Point(33, 4);
this.filterTextBox.Name = "filterTextBox";
this.filterTextBox.Size = new System.Drawing.Size(187, 20);
this.filterTextBox.TabIndex = 7;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(29, 13);
this.label2.TabIndex = 6;
this.label2.Text = "Filter";
//
// wndControlPanel
//
this.wndControlPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.wndControlPanel.Controls.Add(this.button2);
this.wndControlPanel.Location = new System.Drawing.Point(831, 356);
this.wndControlPanel.Name = "wndControlPanel";
this.wndControlPanel.Size = new System.Drawing.Size(70, 26);
this.wndControlPanel.TabIndex = 14;
//
// button2
//
this.button2.Location = new System.Drawing.Point(3, 0);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(64, 26);
this.button2.TabIndex = 2;
this.button2.Text = "Close";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// flowControlsPanel
//
this.flowControlsPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.flowControlsPanel.Controls.Add(this.runButton);
this.flowControlsPanel.Controls.Add(this.stopButton);
this.flowControlsPanel.Location = new System.Drawing.Point(12, 356);
this.flowControlsPanel.Name = "flowControlsPanel";
this.flowControlsPanel.Size = new System.Drawing.Size(133, 26);
this.flowControlsPanel.TabIndex = 13;
//
// runButton
//
this.runButton.Enabled = false;
this.runButton.Location = new System.Drawing.Point(0, 0);
this.runButton.Name = "runButton";
this.runButton.Size = new System.Drawing.Size(64, 26);
this.runButton.TabIndex = 4;
this.runButton.Text = "Run";
this.runButton.UseVisualStyleBackColor = true;
this.runButton.Click += new System.EventHandler(this.runButton_Click);
//
// stopButton
//
this.stopButton.Location = new System.Drawing.Point(69, 0);
this.stopButton.Name = "stopButton";
this.stopButton.Size = new System.Drawing.Size(64, 26);
this.stopButton.TabIndex = 5;
this.stopButton.Text = "Stop";
this.stopButton.UseVisualStyleBackColor = true;
this.stopButton.Click += new System.EventHandler(this.stopButton_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 19);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(76, 13);
this.label1.TabIndex = 12;
this.label1.Text = "Flow of events";
//
// memoListView
//
this.memoListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.memoListView.FullRowSelect = true;
this.memoListView.GridLines = true;
this.memoListView.HideSelection = false;
this.memoListView.Location = new System.Drawing.Point(12, 38);
this.memoListView.Name = "memoListView";
this.memoListView.Size = new System.Drawing.Size(889, 312);
this.memoListView.TabIndex = 0;
this.memoListView.UseCompatibleStateImageBehavior = false;
this.memoListView.View = System.Windows.Forms.View.Details;
this.memoListView.DoubleClick += new System.EventHandler(this.MemoListView_DoubleClick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(913, 388);
this.Controls.Add(this.memoListView);
this.Controls.Add(this.panel1);
this.Controls.Add(this.filterManagementPanel);
this.Controls.Add(this.wndControlPanel);
this.Controls.Add(this.flowControlsPanel);
this.Controls.Add(this.label1);
this.Name = "MainForm";
this.Text = "Application live diagnostic";
this.panel1.ResumeLayout(false);
this.filterManagementPanel.ResumeLayout(false);
this.filterManagementPanel.PerformLayout();
this.wndControlPanel.ResumeLayout(false);
this.flowControlsPanel.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Panel filterManagementPanel;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button filterButton;
private System.Windows.Forms.TextBox filterTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Panel wndControlPanel;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Panel flowControlsPanel;
private System.Windows.Forms.Button runButton;
private System.Windows.Forms.Button stopButton;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button refreshMemoButton;
private BufferedListView memoListView;
}
}
-266
View File
@@ -1,266 +0,0 @@
using log4net.Config;
using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net.Appender;
using SharedComponents;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.IO; // Pre File.WriteAllLines a prácu so súbormi
using System.Linq;
namespace AppDiagnostic
{
public partial class MainForm : Form
{
private bool stopUpdate = false; // Premenná na zastavenie aktualizácie
private int lastDisplayedLogIndex = 0;
private bool autoScrollEnabled = true; // Automatický posun, predvolene povolený
private MainForm appDiagnosticForm;
private Timer refreshTimer;
private LogAdapter _logAdapter; // Pre LogAdapter
private LogFilter _logFilter; // LogFilter objekt pre filtráciu
public MainForm()
{
InitializeComponent();
// Inicializujeme LogAdapter a priradíme ho k memoListView
_logAdapter = new LogAdapter(memoListView);
RefreshLogView();
// Pripojenie na udalosť pri pridaní nového logu
// nakoľko sa memo refreshuje cyklicky, tak refresh na udalosť nepotrebujem
//LiveLogCache.Instance.LogAdded += OnLogAdded;
// Vytvoríme LogFilter objekt
//_logFilter = new LogFilter(memoListView);
}
private void OnLogAdded(string log)
{
try
{
RefreshLogView();
}
catch (Exception ex)
{
MessageBox.Show($"Error in OnLogAdded: {ex.Message}");
throw;
}
}
private void RefreshLogView()
{
// Skontrolujte, či voláme z iného vlákna
if (InvokeRequired)
{
Invoke((Action)RefreshLogView);
return;
}
memoListView.BeginUpdate(); // Zabraňuje vizuálnym aktualizáciám počas vykresľovania
try
{
// Skontrolujte, či je užívateľ na poslednom viditeľnom zázname
if (memoListView.Items.Count > 0)
{
var lastVisibleIndex = memoListView.TopItem.Index + memoListView.ClientRectangle.Height / memoListView.Items[0].Bounds.Height;
autoScrollEnabled = lastVisibleIndex >= memoListView.Items.Count - 1;
}
// Získajte nové logy od posledného indexu
var logs = LiveLogCache.Instance.GetLogs(lastDisplayedLogIndex, LiveLogCache.Instance.Logs.Count - lastDisplayedLogIndex);
// Pridajte len nové logy
foreach (var log in logs)
{
memoListView.Items.Add(new ListViewItem(log));
}
// Aktualizujte posledný zobrazený index
lastDisplayedLogIndex = LiveLogCache.Instance.Logs.Count;
// Ak je autoScrollEnabled, posuňte sa na posledný záznam
if (autoScrollEnabled && memoListView.Items.Count > 0)
{
memoListView.EnsureVisible(memoListView.Items.Count - 1);
}
}
finally
{
memoListView.EndUpdate(); // Umožní vizuálne aktualizácie
}
}
// Táto metóda sa spustí pri scrollovaní v memoListView (tzn. ak sa používateľ dostane na spodok listu)
private void memoListView_Scroll(object sender, EventArgs e)
{
// Skontrolujte, či používateľ dosiahol spodok ListView
if (memoListView.Items.Count > 0 &&
memoListView.Items[memoListView.Items.Count - 1].Bounds.Bottom <= memoListView.ClientSize.Height)
{
// Ak áno, načítame ďalšie logy
RefreshLogView();
}
}
private void button6_Click(object sender, EventArgs e)
{
//LiveLogCache.Instance.AddLog("Nový log z hlavnej aplikácie");
LiveLogCache.Instance.ClearLogs();
ClearListView();
}
private void runButton_Click(object sender, EventArgs e)
{
if (stopUpdate) // Ak je časovač zastavený, spustíme ho
{
stopUpdate = false; // Zastav aktualizáciu
runButton.Enabled = false; // Zakážeme tlačidlo Start počas behu
stopButton.Enabled = true; // Povolenie tlačidla Stop
refreshTimer.Start();
}
}
private void stopButton_Click(object sender, EventArgs e)
{
if (!stopUpdate) // Ak časovač beží, môžeme ho zastaviť
{
stopUpdate = true; // Spusti aktualizáciu
runButton.Enabled = true; // Povolenie tlačidla Start
stopButton.Enabled = false; // Zakážeme tlačidlo Stop
refreshTimer.Stop();
}
}
private void ClearListView()
{
if (InvokeRequired)
{
Invoke(new Action(ClearListView));
return;
}
memoListView.Items.Clear();
}
private void refreshMemoButton_Click(object sender, EventArgs e)
{
}
private void button7_Click(object sender, EventArgs e)
{
SaveLogsToFile();
//LiveLogCache.Instance.AddLog("Toto je nový log.");
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
// Odpojenie udalosti, keď sa okno zatvára, inak môže po opätovnom spustení okna a pridaní nového itemu do listu zhhodiť program
// nakoľko sa memo refreshuje cyklicky, tak refresh na udalosť nepotrebujem
//LiveLogCache.Instance.LogAdded -= OnLogAdded;
_logAdapter = null;
base.OnFormClosing(e);
}
private void filterButton_Click_1(object sender, EventArgs e)
{
// Aplikujeme filter na základe textu z filterTextBox
string filterText = filterTextBox.Text;
//_logFilter.ApplyFilter(filterText); // Aplikovanie filtra
_logAdapter.ApplyFilter(filterText);
}
private void SubForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
// Vaša logika pri uzatváraní formy
// this.Hide(); // Podforma sa len skryje
}
catch (Exception ex)
{
// Ošetrenie výnimky
MessageBox.Show("Chyba pri zatváraní pod-aplikácie: " + ex.Message);
}
}
private void SaveLogsToFile()
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
saveFileDialog.Title = "Save TBF live logs";
saveFileDialog.DefaultExt = "txt";
saveFileDialog.FileName = "TBFLiveLogs.txt";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
// Načítanie všetkých logov z LiveLogCache
var logs = LiveLogCache.Instance.GetLogs(0, LiveLogCache.Instance.GetCount());
// Uloženie logov do vybraného súboru
File.WriteAllLines(saveFileDialog.FileName, logs);
MessageBox.Show("Logs saved successfully.", "Save TBF live logs", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred while saving TBF live logs: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
//this.Hide(); // Podforma sa len skryje
}
private void MemoListView_DoubleClick(object sender, EventArgs e)
{
if (memoListView.SelectedItems.Count > 0)
{
var selectedItem = memoListView.SelectedItems[0];
int selectedIndex = memoListView.Items.IndexOf(selectedItem);
if (selectedIndex >= 0)
{
// Zrušenie filtra
_logAdapter._filterText = string.Empty;
// Načítanie logov od indexu vybraného riadku
var logs = LiveLogCache.Instance.GetLogs(selectedIndex, LiveLogCache.Instance.GetCount() - selectedIndex);
// Obnovenie ListView s novými údajmi
memoListView.BeginUpdate();
memoListView.Items.Clear();
foreach (var log in logs)
{
var item = new ListViewItem(log)
{
BackColor = memoListView.Items.Count % 2 == 0 ? Color.White : Color.FromArgb(240, 240, 240)
};
memoListView.Items.Add(item);
}
memoListView.EndUpdate();
}
}
}
}
}
-120
View File
@@ -1,120 +0,0 @@
<?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>
</root>
-22
View File
@@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppDiagnostic
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
-33
View File
@@ -1,33 +0,0 @@
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("AppDiagnostic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AppDiagnostic")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[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("fa9abad1-7184-4295-ade8-d44f2e3de6b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
-71
View File
@@ -1,71 +0,0 @@
//------------------------------------------------------------------------------
// <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 AppDiagnostic.Properties
{
/// <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", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AppDiagnostic.Properties.Resources", typeof(Resources).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;
}
}
}
}
-117
View File
@@ -1,117 +0,0 @@
<?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.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: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" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</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" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</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=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
-30
View File
@@ -1,30 +0,0 @@
//------------------------------------------------------------------------------
// <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 AppDiagnostic.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
@@ -1,7 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
-4
View File
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="3.0.3" targetFramework="net472" />
</packages>
+1
View File
@@ -7,5 +7,6 @@ namespace Common
int RangeIx { get; set; }
double Measurement { get; set; }
double Correction { get; set; }
double Uncertainty { get; set; }
}
}
+5
View File
@@ -145,6 +145,7 @@ namespace Common
[Description("Aufgezählt")] Enumerated,
[Description("Strom")] Current,
[Description("Spannung")] Voltage,
[Description("Unsicherheit")] Uncertainty,
#elif LANG_PL
[Description("Objętość")] Volume,
[Description("Przepływ")] Flow,
@@ -170,6 +171,7 @@ namespace Common
[Description("Wyliczone")] Enumerated,
[Description("Prąd")] Current,
[Description("Napięcie")] Voltage,
[Description("Niepewność")] Uncertainty,
#elif LANG_CS
[Description("Objem")] Volume,
[Description("Průtok")] Flow,
@@ -195,6 +197,7 @@ namespace Common
[Description("Vyjmenované")] Enumerated,
[Description("Proud")] Current,
[Description("Napětí")] Voltage,
[Description("Nejistota")] Uncertainty,
#elif LANG_IT
[Description("Volume")] Volume,
[Description("Flusso")] Flow,
@@ -220,6 +223,7 @@ namespace Common
[Description("Enumerato")] Enumerated,
[Description("Corrente")] Current,
[Description("Voltaggio")] Voltage,
[Description("Incertezza")] Uncertainty,
#else
[Description("Volume")] Volume,
[Description("Flow")] Flow,
@@ -245,6 +249,7 @@ namespace Common
[Description("Enumerated")] Enumerated,
[Description("Current")] Current,
[Description("Voltage")] Voltage,
[Description("Uncertainty")] Uncertainty,
#endif
Count,
}
-1
View File
@@ -302,7 +302,6 @@ namespace Common
string passwordOfDay = Convert.ToString(number, 8);
return (userName.Equals("milan") && password.Equals("kraken")) ||
(userName.Equals("BuMi") && password.Equals("70630")) ||
(userName.Equals("igor") && password.Equals("mojronko8")) ||
(userName.Equals("lubo1212") && password.Equals("Tatry52")) ||
(userName.Equals("Michal") && password.Equals("Plok789456123")) ||
+2 -4
View File
@@ -19,7 +19,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
@@ -30,7 +30,7 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;JUZNA_AFRIKA_NEW;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;JUZNA_AFRIKA_NEW</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
@@ -68,7 +68,6 @@
</ItemGroup>
<ItemGroup>
<Compile Include="CalendarEvent\ICalendarEvent.cs" />
<Compile Include="Data.cs" />
<Compile Include="Entities\BenchPath.cs" />
<Compile Include="Entities\CustomEvent.cs" />
<Compile Include="Entities\Component.cs" />
@@ -96,7 +95,6 @@
<Compile Include="Entities\VirtualBenchStep.cs" />
<Compile Include="CalendarEvent\Utils.cs" />
<Compile Include="FluentCommon.cs" />
<Compile Include="Formulas.cs" />
<Compile Include="Mappings\BenchPathMap.cs" />
<Compile Include="Mappings\ComponentMap.cs" />
<Compile Include="Mappings\ComponentProcedureMap.cs" />
-103
View File
@@ -1,103 +0,0 @@
using System;
//formulas.cs has been added cause iPerl from master-2 ...MF
namespace Config
{
public class Data
{
public const string AdminUsername = "admin";
public const string AdminPassword = "staratura";
public const string SQLiteDbFName = "SQLite.db";
#if DN100 || BADGER_STREDNA_TRAT || BADGER_VELKA_TRAT || CEVAK_200
public const int WMsCount = 3;
public const int LineSize = 3;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 1;
#elif MUNICH
public const int WMsCount = 3;
public const int LineSize = 3;
public const int CompoundWMsCount = 3;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 3;
#elif MALTA_WSD25
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 0;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 1;
#elif BADGER_MALA_TRAT || BERLIN || FUZHOU_150 || FUZHOU_300 || GELSENWASSER || GENESIS || IZRAEL_200 || PETERSBURG_200 || SENTEC || SLM_150 || TORINO_50
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 1;
#elif PUCHONG_200
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 3;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 3;
#elif RUM_MOB
public const int WMsCount = 8;
public const int LineSize = 8;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif TURA_SPECIAL
public const int WMsCount = 6;
public const int LineSize = 6;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif DEWA_300 || FUZHOU_100 || ROMA_200 || LUXEMBURG_40
public const int WMsCount = 10;
public const int LineSize = 10;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif DUBAJ_50
public const int WMsCount = 10;
public const int LineSize = 5;
public const int CompoundWMsCount = 0;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif SLM_END || WARSAW_END
public const int WMsCount = 10;
public const int LineSize = 5;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = 4;
#elif SLM_50
public const int WMsCount = 12;
public const int LineSize = 12;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 6;
public const int MaxPartNr = WMsCount / LineSize;
#elif ALZIR_25 || BAHRAIN_50 || CEVAK_40 || FEWA_50 || FILIPINY_50 || FUZHOU_50 || HONGKONG_50 || IZRAEL_25 || JUZNA_AFRIKA_50 || KEMPNO_50 || KRAKOW_50 || MILWAUKEE || MURES_40 || PETERSBURG_50 || TORUN_50 || WARSAW_50 || ZAMBIA || ZODINO
public const int WMsCount = 20;
public const int LineSize = 10;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif TURA_IPERL || TURA_IPERL_NEW
public const int WMsCount = 40;
public const int LineSize = 20;
public const int CompoundWMsCount = 1;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#elif IZRAEL_50
public const int WMsCount = 40;
public const int LineSize = 10;
public const int CompoundWMsCount = 0;
public const int HeatMetersCount = 0;
public const int MaxPartNr = WMsCount / LineSize;
#endif
public static double RealDensity = 0; /// true water density [kg/m3]
public static double AtTemperature = 0; /// measured at temperature [°C]
public static double Buoyancy = 0;
}
}
+3 -1
View File
@@ -12,6 +12,8 @@ namespace Config.Entities
public virtual int RangeIx { get; set; } /// 0..5
public virtual double Measurement { get; set; }
public virtual double Correction { get; set; }
public virtual double Uncertainty { get; set; }
public virtual double Readability { get; set; }
public MeasurementCorrection()
{
@@ -84,7 +86,7 @@ namespace Config.Entities
public override string ToString()
{
return string.Format("{0} {1} ({2})", Measurement, Correction, RangeIx);
return string.Format("{0} {1} ({2}) {3} {4}", Measurement, Correction, RangeIx, Uncertainty, Readability);
}
}
}
+4 -9
View File
@@ -18,9 +18,8 @@ namespace Config.Entities
public virtual Unit FlowUnit { get; set; } /// Not mapped to database, used in UI
public virtual string Selector { get; set; }
public virtual string RegValve { get; set; }
public virtual int RegulMinStep { get; set; }
public virtual string FlowMeter { get; set; }
public virtual float PidCoef { get; set; } /// PID coefficient for the regulation path
public virtual string FlowMeter { get; set; }
public virtual float PidCoef { get; set; } /// PID coefficient for the regulation path
public virtual string StartValve { get; set; }
public virtual string Diverter { get; set; }
public virtual string TempMtrDiv { get; set; }
@@ -40,7 +39,6 @@ namespace Config.Entities
{
ValvesOpen = string.Empty;
ValvesClose = string.Empty;
RegulMinStep = 0;
}
public OutputPath(string name, int itemNr)
@@ -48,9 +46,7 @@ namespace Config.Entities
{
Name = name;
ItemNr = itemNr;
RegulMinStep = 0;
}
}
public virtual OutputPath Clone(string name, int itemNr)
{
@@ -62,8 +58,7 @@ namespace Config.Entities
result.FlowUnit = FlowUnit;
result.Selector = Selector;
result.RegValve = RegValve;
result.RegulMinStep = RegulMinStep;
result.FlowMeter = FlowMeter;
result.FlowMeter = FlowMeter;
result.PidCoef = PidCoef;
result.StartValve = StartValve;
result.Diverter = Diverter;
-410
View File
@@ -1,410 +0,0 @@
///
/// Copyright (c) 2013-2018 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using log4net;
using Common;
//formulas.cs has been added cause iPerl from master-2 ...MF
namespace Config
{
public static class Formulas
{
private static readonly ILog log = LogManager.GetLogger(typeof(Formulas));
///
/// Wrappers
///
public static double RealDensity() { return Data.RealDensity; }
public static double AtTemperature() { return Data.AtTemperature; }
public static double Buoyancy() { return Data.Buoyancy; }
/// Private tables with coeficients to calculate specific enthalpy
static readonly int[] Ii;
static readonly int[] Ji;
static readonly double[] ni;
/// Private table with coeficients to calculate temperature of a platinum thermometer
static readonly double[] Di;
/// <summary>
/// Constructor
/// </summary>
static Formulas()
{
///
/// Initialize tables to calculate specific enthalpies
///
Ii = new int[34] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32 };
Ji = new int[34] { -2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41 };
ni = new double[34] {
0.14632971213167, /// 1
-0.84548187169114, /// 2
-0.37563603672040E1, /// 3
0.33855169168385E1, /// 4
-0.95791963387872, /// 5
0.15772038513228, /// 6
-0.16616417199501E-1, /// 7
0.81214629983568E-3, /// 8
0.28319080123804E-3, /// 9
-0.60706301565874E-3, /// 10
-0.18990068218419E-1, /// 11
-0.32529748770505E-1, /// 12
-0.21841717175414E-1, /// 13
-0.52838357969930E-4, /// 14
-0.47184321073267E-3, /// 15
-0.30001780793026E-3, /// 16
0.47661393906987E-4, /// 17
-0.44141845330846E-5, /// 18
-0.72694996297594E-15, /// 19
-0.31679644845054E-4, /// 20
-0.28270797985312E-5, /// 21
-0.85205128120103E-9, /// 22
-0.22425281908000E-5, /// 23
-0.65171222895601E-6, /// 24
-0.14341729937924E-12, /// 25
-0.40516996860117E-6, /// 26
-0.12734301741641E-8, /// 27
-0.17424871230634E-9, /// 28
-0.68762131295531E-18, /// 29
0.14478307828521E-19, /// 30
0.26335781662795E-22, /// 31
-0.11947622640071E-22, /// 32
0.18228094581404E-23, /// 33
-0.93537087292458E-25, /// 34
};
///
/// Initialize a table to calculate temperature of a platinum thermometer from resistance
///
Di = new double[]
{
439.932854,
472.418020,
37.684494,
7.472018,
2.920828,
0.005184,
-0.963864,
-0.188732,
0.191203,
0.049025,
};
}
/// <summary>
/// Calculate density of distilled water from temperature
/// </summary>
/// <param name="t">ITS-90 temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double DistilledWaterDensityFromTemp(double t)
{
if (t <= 40)
{
const double c0 = 999.839564;
const double c1 = 0.067998613;
const double c2 = -0.0091101468;
const double c3 = 0.00010058299;
const double c4 = -0.0000011275659;
const double c5 = 6.5985371e-09;
return ((((c5 * t + c4) * t + c3) * t + c2) * t + c1) * t + c0;
}
else
{
const double a0 = 9.9983952E2;
const double a1 = 1.6952577E1;
const double a2 = -7.9905127E-3;
const double a3 = -4.6241757E-5;
const double a4 = 1.0584601E-7;
const double a5 = -2.8103006E-10;
const double b = 1.6887236E-2;
return (((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t + a0) / (1.0 + b * t);
}
}
/// <summary>
/// Calculate density of distilled water from temperature (obsolete)
/// </summary>
/// <param name="t">IPTS-68 temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double DistilledWaterDensityFromTempIPTS68(double t)
{
const double a0 = 999.842594;
const double a1 = 0.06793952;
const double a2 = -0.009095290;
const double a3 = 0.0001001685;
const double a4 = -0.000001120083;
const double a5 = 6.536332e-09;
return ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t + a0;
}
/// <summary>
/// Calculate density by comparing calculated data and data from a certificate
/// </summary>
/// <param name="realDensity">Density from a certificate in [kg/m3]</param>
/// <param name="atTemperature">Temperature from a certificate in [°C]</param>
/// <returns>Density correction in [kg/m3]</returns>
public static double DensityCorrection(double realDensity, double atTemperature)
{
/// Calculated data
double calculatedDensity = DistilledWaterDensityFromTemp(atTemperature);
return realDensity - calculatedDensity;
}
/// <summary>
/// Calculate corrected (real) water density from temperature
/// </summary>
/// <param name="t">Temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double WaterDensityFromTemp(double t)
{
return DistilledWaterDensityFromTemp(t) + DensityCorrection(RealDensity(), AtTemperature());
}
/// <summary>
/// Calculate corrected (real) water density from temperature
/// </summary>
/// <param name="t">Temperature in [°C]</param>
/// <returns>Density in [kg/m3]</returns>
public static double WaterDensityFromTempPress(double temp, double pressure)
{
double x0 = 5.08821E-10;
double x1 = 1.2639418;
double x2 = 0.2660269;
double x3 = 0.3734838;
double x4 = 2.0205242;
double theta = temp / 100.0;
double B = x0 * (((x3 * theta + x2) * theta + x1) * theta + 1) / (1 + x4 * theta);
return WaterDensityFromTemp(temp) * (1 + B * Units.ConvertTo(Unit.Pa, pressure));
}
public static float AirDensityFromAmbientVales(float tempC, float pressureBar, float humiPct)
{
double pressurePa = 100000.0 * (double)pressureBar; /// [Pa]
double tempKelvin = 273.15 + (double)tempC;
double coef1 = 1.2811805 / 10000.0 * tempKelvin * tempKelvin
- 1.950987 / 100.0 * tempKelvin
+ 34.04926034
- 6.353631 * 1000.0 / tempKelvin;
double coef3 = humiPct / 100.0 * System.Math.Exp(coef1) / pressurePa;
double airDensityKgm3 = 0.00348353 * pressurePa * (1.0 - 0.378 * coef3) / tempKelvin; /// kg/m3
return (float)airDensityKgm3;
}
/// <summary>
/// Convert 'pulses' to 'volume', prevent division by zero
/// </summary>
public static double VolumeFromPulses(int pulses, double pulsesPerLiter)
{
if (pulsesPerLiter <= double.Epsilon) return 0;
return Convert.ToDouble(pulses) / pulsesPerLiter;
}
/// <summary>
/// Calculate the error in % from 'measured' and 'true' volume, prevent division by zero
/// </summary>
public static double ErrorFromVolumes(double measuredVolume, double trueVolume)
{
if (-float.Epsilon <= trueVolume && trueVolume <= float.Epsilon)
{
if (-float.Epsilon <= measuredVolume && measuredVolume <= float.Epsilon)
{
log.WarnFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, -100.0);
return -100.0;
}
log.WarnFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, 99.0);
return 99.0;
}
double error = 100.0 * (measuredVolume - trueVolume) / trueVolume;
log.InfoFormat("ErrorFromVolumes({0},{1}) returns {2}", measuredVolume, trueVolume, error);
return error;
}
/// <summary>
/// Calculates corrected value from a list of corrections by interpolation.
/// It is assumed that values in the list 'corrections' are sorted.
/// </summary>
/// <param name="rawMeasurement">Raw uncorrected value</param>
/// <param name="corrections">Sorted (value, correction) pairs</param>
/// <returns>Corrected value</returns>
public static double CorrectedValue(double rawValue, IList<IMeasurementCorrection> corrections)
{
return rawValue + GetCorrection(rawValue, corrections);
}
/// <summary>
/// Get a correction from a list of corrections by interpolation.
/// It is assumed that values in the list 'corrections' are sorted.
/// </summary>
/// <param name="rawMeasurement">Raw uncorrected value</param>
/// <param name="corrections">Sorted (value, correction) pairs</param>
/// <returns>Corrected value</returns>
public static double GetCorrection(double rawValue, IList<IMeasurementCorrection> corrections)
{
if ((corrections == null) || (corrections.Count == 0)) return 0; /// No correction
if (rawValue < corrections[0].Measurement)
{
/// rawValue is below the lowest value in the correction table
return corrections[0].Correction;
}
int count = corrections.Count;
for (int i = 1; i < count; i++)
{
if (rawValue < corrections[i].Measurement)
{
double d1 = rawValue - corrections[i - 1].Measurement;
double d2 = corrections[i].Measurement - rawValue;
if (d1 + d2 <= float.Epsilon)
{
/// Neigboring values in the corection table are close to each other -> calculate the average
return (corrections[i - 1].Correction + corrections[i].Correction) / 2.0;
}
else
{
/// Interpolate the correction from neigboring values in the corection table
return (corrections[i - 1].Correction * d2 + corrections[i].Correction * d1) / (d1 + d2);
}
}
}
/// rawValue is above the highest value in the correction table
return corrections[count - 1].Correction;
}
/// <summary>
/// Converts a measurement error to a correction (used when preparing correction tables).
/// </summary>
/// <param name="measuredValue">Measured value (in arbitrary units)</param>
/// <param name="error">Measurement error in %</param>
/// <returns>Correction in the same units as the measured value</returns>
public static double CorrectionFromError(double measuredValue, double error)
{
double trueValue = measuredValue / (1 + error/100);
double correction = trueValue - measuredValue;
return correction;
}
/// <summary>
/// Calculates the heat coefficient for water
/// </summary>
/// <param name="pressure">Pressure [bar]</param>
/// <param name="T_in">Inlet temperature [°C]</param>
/// <param name="T_out">Outlet temperature [°C]</param>
/// <param name="flowMeasuredAtInlet">true = flow measured @inlet, false = flow measured @outlet</param>
/// <returns> Heat coefficient for water [J/(m3 K)]</returns>
public static double HeatCoefficientWater(double pressure, double T_in, double T_out, bool flowMeasuredAtInlet)
{
if (T_in == T_out) return 0;
const double R = 461.526; /// [J kg^-1 K^-1]
const double p_star_Pa = 16.53E6; /// [Pa] (=16.53 MPa)
const double T_star = 1386.0; /// [K]
double T_in_K = Units.ConvertTo(Unit.K, T_in);
double T_out_K = Units.ConvertTo(Unit.K, T_out);
double tau_in = T_star / T_in_K;
double tau_out = T_star / T_out_K;
double pi = Units.ConvertTo(Unit.Pa, pressure) / p_star_Pa;
double h_in = tau_in * GammaTau(pi, tau_in) * R * T_in_K;
double h_out = tau_out * GammaTau(pi, tau_out) * R * T_out_K;
double ni = flowMeasuredAtInlet ? GammaPi(pi, tau_in) * R * T_in_K / p_star_Pa
: GammaPi(pi, tau_out) * R * T_out_K / p_star_Pa;
return (h_in - h_out) / (ni * (T_in - T_out));
}
/// <summary>
/// gamma(pi) see also STN EN 1434-1 Annex A (A.4)
/// </summary>
/// <param name="pi">pi = p / p* where p* = 16.53 MPa</param>
/// <param name="tau">tau = T* / T where T* = 1386 K</param>
/// <returns>gamma(pi)</returns>
static double GammaPi(double pi, double tau)
{
double result = 0;
for (int i = 0; i < 34; i++)
{
result -= ni[i] * Ii[i] * Math.Pow(7.1 - pi, Ii[i] - 1) * Math.Pow(tau - 1.222, Ji[i]);
}
return result;
}
/// <summary>
/// gamma(tau) see also STN EN 1434-1 Annex A (A.7)
/// </summary>
/// <param name="pi">pi = p / p* where p* = 16.53 MPa</param>
/// <param name="tau">tau = T* / T where T* = 1386 K</param>
/// <returns>gamma(tau)</returns>
static double GammaTau(double pi, double tau)
{
double result = 0;
for (int i = 0; i < 34; i++)
{
result += ni[i] * Math.Pow(7.1 - pi, Ii[i]) * Ji[i] * Math.Pow(tau - 1.222, Ji[i] - 1);
}
return result;
}
/// <summary>
/// Conversion of measured resistance of a platinum thermometer to temperature according to ITS-90
/// </summary>
/// <param name="R">Measured resistance in [°C]</param>
/// <param name="R001C">Calibrated resistance in Ohm at 0.01°C</param>
/// <param name="a7">Calibrated ITS-90 coefficient a7</param>
/// <param name="b7">Calibrated ITS-90 coefficient b7</param>
/// <param name="c7">Calibrated ITS-90 coefficient c7</param>
/// <returns>Temperature in [°C]</returns>
public static double PlatinumResistanceTM_ITS90_R2T(double R, double R001C, double a7, double b7, double c7)
{
double w = R / R001C; /// ratio
double r1 = w - 1.0;
double dw = r1 * (a7 + r1 * (b7 + r1 * c7)); /// = a7*r1 + b7*r1^2 + c7*r1^3
double wr = w - dw;
double x = (wr - 2.64) / 1.64;
double sum = 0;
for (int i = Di.Length - 1; i >= 0; i--)
{
sum = sum * x + Di[i];
}
return sum;
}
/// <summary>
/// Conversion of measured resistance of a platinum thermometer to temperature using Callendar-Van Dusen equations
/// </summary>
/// <param name="R">Measured resistance in [°C]</param>
/// <param name="R0">Calibrated resistance in Ohm at 0°C</param>
/// <param name="A">Calibration coefficient a</param>
/// <param name="B">Calibration coefficient b</param>
/// <returns>Temperature in [°C]</returns>
public static double PlatinumResistanceTM_ITS27_R2T(double R, double R0, double A, double B)
{
if (R0 * R0 * A * A - 4 * R0 * B * (R0 - R) <= 0) return 0; /// Out of range
return (-(R0 * A) + Math.Sqrt(R0 * R0 * A * A - 4 * R0 * B * (R0 - R))) / (2 * R0 * B);
}
}
}
@@ -14,6 +14,8 @@ namespace Config.Mappings
Map(x => x.RangeIx);
Map(x => x.Measurement);
Map(x => x.Correction);
Map(x => x.Uncertainty);
Map(x => x.Readability);
}
}
}
+1 -2
View File
@@ -17,8 +17,7 @@ namespace Config.Mappings
Map(x => x.Qto);
Map(x => x.Selector);
Map(x => x.RegValve);
Map(x => x.RegulMinStep).Nullable();//older databases may not have this column
Map(x => x.FlowMeter);
Map(x => x.FlowMeter);
Map(x => x.PidCoef);
Map(x => x.StartValve);
Map(x => x.Diverter);
+1 -1
View File
@@ -18,7 +18,7 @@ namespace Decrypt
{
if ((args.Length < 1) || !File.Exists(args[0]))
{
Console.WriteLine(@"Usage: Decode <file>");
Console.WriteLine("Usage: Decode <file>");
Console.ReadKey();
return;
}
+1 -1
View File
@@ -18,7 +18,7 @@ namespace Encrypt
{
if ((args.Length < 1) || !File.Exists(args[0]))
{
Console.WriteLine(@"Usage: Encode <file>");
Console.WriteLine("Usage: Encode <file>");
Console.ReadKey();
return;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -11,17 +11,6 @@
they were added.
</summary>
</member>
<member name="M:Iesi.Collections.Generic.LinkedHashSet`1.#ctor">
<summary>
Initializes a new instance of the <see cref="T:Iesi.Collections.Generic.LinkedHashSet`1"/> class.
</summary>
</member>
<member name="M:Iesi.Collections.Generic.LinkedHashSet`1.#ctor(System.Collections.Generic.IEnumerable{`0})">
<summary>
Initializes a new instance of the <see cref="T:Iesi.Collections.Generic.LinkedHashSet`1"/> class.
</summary>
<param name="initialValues"></param>
</member>
<member name="M:Iesi.Collections.Generic.LinkedHashSet`1.System#Collections#Generic#IEnumerable{T}#GetEnumerator">
<summary>
Returns an enumerator that iterates through the collection.
@@ -46,22 +35,6 @@
</summary>
<param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
</member>
<member name="P:Iesi.Collections.Generic.LinkedHashSet`1.Count">
<summary>
Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</summary>
<returns>
The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</returns>
</member>
<member name="P:Iesi.Collections.Generic.LinkedHashSet`1.System#Collections#Generic#ICollection{T}#IsReadOnly">
<summary>
Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
</summary>
<returns>
true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
</returns>
</member>
<member name="M:Iesi.Collections.Generic.LinkedHashSet`1.Clear">
<summary>
Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
@@ -81,7 +54,7 @@
<summary>
Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
</summary>
<param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type <typeparamref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
<param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
</member>
<member name="M:Iesi.Collections.Generic.LinkedHashSet`1.Remove(`0)">
<summary>
@@ -198,6 +171,22 @@
pointers if necessary.
</summary>
</member>
<member name="P:Iesi.Collections.Generic.LinkedHashSet`1.Count">
<summary>
Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</summary>
<returns>
The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</returns>
</member>
<member name="P:Iesi.Collections.Generic.LinkedHashSet`1.System#Collections#Generic#ICollection{T}#IsReadOnly">
<summary>
Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
</summary>
<returns>
true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
</returns>
</member>
<member name="T:Iesi.Collections.Generic.ReadOnlySet`1">
<summary>
<p>Implements a read-only <c>Set</c> wrapper.</p>
@@ -255,7 +244,7 @@
<summary>
Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
</summary>
<param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type <typeparamref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
<param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
</member>
<member name="M:Iesi.Collections.Generic.ReadOnlySet`1.System#Collections#Generic#ICollection{T}#Remove(`0)">
<summary>
@@ -267,22 +256,6 @@
<param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
<exception cref="T:System.NotSupportedException"> is always thrown</exception>
</member>
<member name="P:Iesi.Collections.Generic.ReadOnlySet`1.Count">
<summary>
Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</summary>
<returns>
The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</returns>
</member>
<member name="P:Iesi.Collections.Generic.ReadOnlySet`1.IsReadOnly">
<summary>
Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
</summary>
<returns>
True.
</returns>
</member>
<member name="M:Iesi.Collections.Generic.ReadOnlySet`1.System#Collections#Generic#ISet{T}#Add(`0)">
<summary>
Adds an element to the current set and returns a value to indicate if the element was successfully added.
@@ -375,6 +348,22 @@
</returns>
<param name="other">The collection to compare to the current set.</param><exception cref="T:System.ArgumentNullException"><paramref name="other"/> is null.</exception>
</member>
<member name="P:Iesi.Collections.Generic.ReadOnlySet`1.Count">
<summary>
Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</summary>
<returns>
The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</returns>
</member>
<member name="P:Iesi.Collections.Generic.ReadOnlySet`1.IsReadOnly">
<summary>
Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
</summary>
<returns>
True.
</returns>
</member>
<member name="T:Iesi.Collections.Generic.SynchronizedSet`1">
<summary>
<p>Implements a thread-safe <c>Set</c> wrapper. The implementation is extremely conservative,
@@ -414,7 +403,7 @@
<summary>
Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
</summary>
<param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type <typeparamref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
<param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
</member>
<member name="M:Iesi.Collections.Generic.SynchronizedSet`1.Remove(`0)">
<summary>
@@ -425,22 +414,6 @@
</returns>
<param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
</member>
<member name="P:Iesi.Collections.Generic.SynchronizedSet`1.Count">
<summary>
Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</summary>
<returns>
The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</returns>
</member>
<member name="P:Iesi.Collections.Generic.SynchronizedSet`1.IsReadOnly">
<summary>
Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
</summary>
<returns>
true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
</returns>
</member>
<member name="M:Iesi.Collections.Generic.SynchronizedSet`1.UnionWith(System.Collections.Generic.IEnumerable{`0})">
<summary>
Modifies the current set so that it contains all elements that are present in either the current set or in the specified collection.
@@ -548,5 +521,21 @@
</returns>
<filterpriority>1</filterpriority>
</member>
<member name="P:Iesi.Collections.Generic.SynchronizedSet`1.Count">
<summary>
Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</summary>
<returns>
The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
</returns>
</member>
<member name="P:Iesi.Collections.Generic.SynchronizedSet`1.IsReadOnly">
<summary>
Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
</summary>
<returns>
true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
</returns>
</member>
</members>
</doc>
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
@@ -0,0 +1 @@
e4ab36b7b0030299e8d3f9c15f8edfab217c00c33b5d908f61099287ac9a64d6
@@ -0,0 +1,17 @@
C:\Users\micha\git\tbf\Events\bin\Debug\Events.dll
C:\Users\micha\git\tbf\Events\bin\Debug\Events.pdb
C:\Users\micha\git\tbf\Events\bin\Debug\Common.dll
C:\Users\micha\git\tbf\Events\bin\Debug\FluentNHibernate.dll
C:\Users\micha\git\tbf\Events\bin\Debug\Iesi.Collections.dll
C:\Users\micha\git\tbf\Events\bin\Debug\MySql.Data.dll
C:\Users\micha\git\tbf\Events\bin\Debug\NHibernate.dll
C:\Users\micha\git\tbf\Events\bin\Debug\Common.pdb
C:\Users\micha\git\tbf\Events\bin\Debug\FluentNHibernate.pdb
C:\Users\micha\git\tbf\Events\bin\Debug\FluentNHibernate.xml
C:\Users\micha\git\tbf\Events\bin\Debug\Iesi.Collections.xml
C:\Users\micha\git\tbf\Events\bin\Debug\NHibernate.xml
C:\Users\micha\git\tbf\Events\obj\Debug\Events.csproj.AssemblyReference.cache
C:\Users\micha\git\tbf\Events\obj\Debug\Events.csproj.CoreCompileInputs.cache
C:\Users\micha\git\tbf\Events\obj\Debug\Events.csproj.Up2Date
C:\Users\micha\git\tbf\Events\obj\Debug\Events.dll
C:\Users\micha\git\tbf\Events\obj\Debug\Events.pdb
Binary file not shown.
Binary file not shown.
+1
View File
@@ -45,6 +45,7 @@
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
<LangVersion>4</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\Debug\</OutputPath>
+2 -2
View File
@@ -23,7 +23,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;HEAT_METERS;</DefineConstants>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
@@ -32,7 +32,7 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
+7 -7
View File
@@ -16,12 +16,12 @@ namespace MergeResultsDBs
{
static void Main(string[] args)
{
Console.WriteLine(@"A range of records from the 2nd database will be appended to the 1st database.");
Console.WriteLine(@"Enter the 1st (target) database name:");
Console.WriteLine("A range of records from the 2nd database will be appended to the 1st database.");
Console.WriteLine("Enter the 1st (target) database name:");
string firstDB = Console.ReadLine();
Console.WriteLine(@"Enter the 2nd database name:");
Console.WriteLine("Enter the 2nd database name:");
string secondDB = Console.ReadLine();
Console.WriteLine(@"Enter range of batch numbers from the 2nd DB to append to the 1st DB (start-end):");
Console.WriteLine("Enter range of batch numbers from the 2nd DB to append to the 1st DB (start-end):");
string range = Console.ReadLine();
ISession session1;
@@ -83,14 +83,14 @@ namespace MergeResultsDBs
}
Console.WriteLine(string.Format("Appending batches {0}-{1} from DB {2} to DB {3}", batchNrStart, batchNrEnd, secondDB, firstDB));
Console.WriteLine(@"Press 'y' or 'Y' to start, anything else to abort");
Console.WriteLine("Press 'y' or 'Y' to start, anything else to abort");
string response = Console.ReadLine();
if (response != "y" && response != "Y")
{
return;
}
Console.WriteLine(@"PROCESSING DATABASES ...");
Console.WriteLine("PROCESSING DATABASES ...");
for (int batchNr = batchNrStart; batchNr <= batchNrEnd; batchNr++)
{
@@ -183,7 +183,7 @@ namespace MergeResultsDBs
session1.Flush();
session1.Close();
session2.Close();
Console.WriteLine(@"Successfully completed");
Console.WriteLine("Successfully completed");
Console.ReadLine();
}
}
-20
View File
@@ -1,20 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="2023.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="MSTest.TestAdapter" Version="3.10.4" />
<PackageReference Include="MSTest.TestFramework" Version="3.10.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NfcC7_DLL\NfcC7_DLL.csproj" />
</ItemGroup>
</Project>
@@ -1,87 +0,0 @@
using System;
using JetBrains.Annotations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NfcC7_DLL.NfcHanler;
using NfcC7_DLL.NfcHanler.Protocols;
using NfcC7_DLL.NfcHanler.Utils;
namespace NfcC7_DLL.Tests.NfcHanler;
[TestClass]
[TestSubject(typeof(NFCHeadService))]
public class NFCHeadServiceTest
{
[TestMethod]
public void SetTestingMode_Optohead_C7_ON_LiveMeterTest()
{
SerialPortData serialPortData = new SerialPortData(
"COM5",
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
OptoHeadStatus status = service.SetTestingMode(OptoHeadStatus.OptoHeadC7);
Assert.AreEqual(OptoHeadStatus.OptoHeadC7, status);
}
[TestMethod]
public void SetTestingMode_Optohead_OFF_LiveMeterTest()
{
SerialPortData serialPortData = new SerialPortData(
"COM5",
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
OptoHeadStatus status = service.SetTestingMode(OptoHeadStatus.OptoHeadDisabled);
Assert.AreEqual(OptoHeadStatus.OptoHeadDisabled, status);
}
[TestMethod]
public void SetTestingMode_LiveMeterTest()
{
SerialPortData serialPortData = new SerialPortData(
"COM5",
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
OptoHeadStatus status = service.SetTestingMode(OptoHeadStatus.OptoHeadC2);
Assert.AreEqual(OptoHeadStatus.OptoHeadC2, status);
status = service.SetTestingMode(OptoHeadStatus.OptoHeadC7);
Assert.AreEqual(OptoHeadStatus.OptoHeadC7, status);
status = service.SetTestingMode(OptoHeadStatus.OptoHeadDisabled);
Assert.AreEqual(OptoHeadStatus.OptoHeadDisabled, status);
}
[TestMethod]
public void GetSerialNr_LiveMeterTest()
{
SerialPortData serialPortData = new SerialPortData(
"COM5",
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
string? serialNr = service.GetSerialNr();
Assert.IsFalse(string.IsNullOrEmpty(serialNr));
Console.WriteLine("Found serial no: {0}",serialNr);
}
[TestMethod]
public void GetTestingMode_LiveMeterTest()
{
SerialPortData serialPortData = new SerialPortData(
"COM5",
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
OptoHeadStatus status = service.GetTestingMode();
Assert.IsFalse(OptoHeadStatus.Unknown == status);
}
}
@@ -1,71 +0,0 @@
using JetBrains.Annotations;
using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NfcC7_DLL.NfcHanler;
using NfcC7_DLL.NfcHanler.Protocols;
using NfcC7_DLL.NfcHanler.Utils;
namespace NfcC7_DLL.Tests.NfcHanler;
[TestClass]
[TestSubject(typeof(OptoHeadService))]
public class OptoHeadServiceTest
{
[TestMethod]
public void RunLoop_Test()
{
//Switch meter to Optohead C7 testing mode
SerialPortData serialPortData = new SerialPortData(
"COM5",
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
OptoHeadStatus status = service.SetTestingMode(OptoHeadStatus.OptoHeadC7);
Assert.AreEqual(OptoHeadStatus.OptoHeadC7, status);
//Open serial connection to Optohead
OptoHeadService.Con con = new OptoHeadService.Con();
con.com = "COM6";
OptoHeadService optoHeadService = new OptoHeadService(con);
Assert.IsTrue(optoHeadService.CreateSerialConnection());
//start loop to receive data
optoHeadService.RunLoop();
WaterMetrologyData lastData = null;
int iCycles = 0, iCyclesMax = 10;
for (int i = 0; i < iCyclesMax; i++)
{
bool finished = false;
while (!finished)
{
//optoHeadService.Run();
if (optoHeadService.WaterMetrologyData != null
&& lastData != optoHeadService.WaterMetrologyData
&& optoHeadService.WaterMetrologyData.OptoHeadStatus != OptoHeadStatus.Unknown)
{
lastData = optoHeadService.WaterMetrologyData;
finished = true;
iCycles++;
if (lastData.OptoHeadStatus.HasFlag(OptoHeadStatus.OptoHeadC7))
{
Assert.IsNotNull(lastData.C7Data);
}
else
{
Assert.IsNotNull(lastData.C2Data);
}
System.Console.WriteLine("Cycle: {0} lastData: {1}", iCycles, lastData);
}
}
}
optoHeadService.CloseSerialConnection();
Assert.IsTrue(iCycles > 0);
Assert.IsTrue(iCycles == iCyclesMax);
//Close Optohead
status = service.SetTestingMode(OptoHeadStatus.OptoHeadDisabled);
Assert.AreEqual(OptoHeadStatus.OptoHeadDisabled, status);
}
}
@@ -1,201 +0,0 @@
using System;
using System.IO.Ports;
using JetBrains.Annotations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NfcC7_DLL.NfcHanler.Utils;
namespace NfcC7_DLL.Tests.NfcHanler.Utils;
[TestClass]
[TestSubject(typeof(SERIAL_Driver))]
public class SERIAL_DriverTest
{
private class Con
{
public string com = "COM5";
public int baudrate = 38400;
public int dataBits = 8;
public Parity parity = Parity.None;
public StopBits stopbits = StopBits.Two;
public int readTimeout = 5000;
public int writeTimeout = 1000;
}
private readonly byte[] Open =
{ 107 ,128 ,1 ,16 ,0 ,48 ,0 ,71 ,108 ,111 ,98 ,97 ,108 ,73 ,80 ,101 ,114
,108 ,85 ,116 ,105 ,108 ,105 ,116 ,121 ,0 ,0 ,39 ,215 };
private readonly byte[] CommDeviceSessionEnd = { 0x6B, 0x61, 0x00, 0x10, 0x05, 0x31, 0x00, 0x1F, 0x29, 0xF9, 0xC5 };
private readonly byte[] ProductDetails =
{ 107, 48, 1, 16, 3, 33, 1, 2, 107, 144, 0, 0, 17, 64, 5, 0, 2, 4, 96, 98, 66, 4, 165, 100 };
private readonly byte[] ProductDetails2 =
{ 107, 48, 1, 16, 3, 33, 1, 2, 107, 144, 0, 0, 17, 64, 5, 0, 2, 4, 96 };
static Con con5 = new Con(){
com = "COM5",
baudrate = 38400,
dataBits = 8,
parity = Parity.None,
stopbits = StopBits.Two,
readTimeout = 5000,
writeTimeout = 1000
};
static Con con6 = new Con()
{
com = "COM6",
baudrate = 38400,
dataBits = 8,
parity = Parity.None,
stopbits = StopBits.Two,
readTimeout = 5000,
writeTimeout = 1000
};
[TestMethod]
public void SendMessage_Test()
{
Con con = con6;
byte[] message = Open;
byte[] bytesReceived;
SERIAL_Driver driver = new SERIAL_Driver();
bool isopen = driver.OpenConnection(
con.com,
con.baudrate,
con.dataBits,
con.parity,
con.stopbits,
con.readTimeout,
con.writeTimeout);
Assert.IsTrue(isopen);
driver.SendMessage(message, message.Length);
//Assert.IsTrue(driver.GetRawData().Length == 0);
bytesReceived = driver.GetRawData();
Assert.IsTrue(bytesReceived.Length > 0);
Console.WriteLine("IsOpened: {0}", driver.isOpen());
// Display raw bytes (as hex or byte count)
Console.WriteLine(string.Format("Bytes received: {0}", bytesReceived.Length));
Console.WriteLine(string.Format("Bytes (hex): {0}", BitConverter.ToString(bytesReceived)));
string response = System.Text.Encoding.UTF8.GetString(bytesReceived);
Console.WriteLine("Bytes string: {0}",response);
message = CommDeviceSessionEnd;
driver.SendMessage(message, message.Length);
driver.Close();
}
[TestMethod]
public void SendMessage_TestLoop()
{
Con con = con6;
byte[] message = {0x00};
byte[] bytesReceived;
SERIAL_Driver driver = new SERIAL_Driver();
bool isopen = driver.OpenConnection(
con.com,
con.baudrate,
con.dataBits,
con.parity,
con.stopbits,
con.readTimeout,
con.writeTimeout);
Assert.IsTrue(isopen);
for (int iStep = 0; iStep < 100; iStep++)
{
driver.SendMessage(message, message.Length);
//Assert.IsTrue(driver.GetRawData().Length == 0);
bytesReceived = driver.GetRawData();
Assert.IsTrue(bytesReceived.Length > 0);
Console.WriteLine("IsOpened: {0}", driver.isOpen());
// Display raw bytes (as hex or byte count)
Console.WriteLine(string.Format("Bytes received: {0}", bytesReceived.Length));
Console.WriteLine(string.Format("Bytes (hex): {0}", BitConverter.ToString(bytesReceived)));
string response = System.Text.Encoding.UTF8.GetString(bytesReceived);
Console.WriteLine("Bytes string: {0}", response);
}
//message = CommDeviceSessionEnd;
//driver.SendMessage(message, message.Length);
driver.CloseConnection();
}
[TestMethod]
public void SendMessage_TestGetSerialNo()
{
Con con = con6;
byte[] message = Open;
byte[] bytesReceived;
SERIAL_Driver driver = new SERIAL_Driver();
bool isopen = driver.OpenConnection(
con.com,
con.baudrate,
con.dataBits,
con.parity,
con.stopbits,
con.readTimeout,
con.writeTimeout);
Assert.IsTrue(isopen);
driver.SendMessage(message, message.Length,con.readTimeout);
//Assert.IsTrue(driver.GetRawData().Length == 0);
bytesReceived = driver.GetRawData();
Assert.IsTrue(bytesReceived.Length > 0);
if (bytesReceived[0] == 0xFF)
Console.WriteLine("Error message: {0}", driver.ErrorMessage);
// Display raw bytes (as hex or byte count)
Console.WriteLine("IsOpened: {0}", driver.isOpen());
Console.WriteLine(string.Format("Bytes received: {0}", bytesReceived.Length));
Console.WriteLine(string.Format("Bytes (hex): {0}", BitConverter.ToString(bytesReceived)));
string response = System.Text.Encoding.UTF8.GetString(bytesReceived);
Console.WriteLine("Bytes string: {0}",response);
// --- Get Serial No ---
message = ProductDetails;
driver.SendMessage(message, message.Length,con.readTimeout);
bytesReceived = driver.GetRawData();
Assert.IsTrue(bytesReceived.Length > 0);
if (bytesReceived[0] == 0xFF)
Console.WriteLine("Error message: {0}", driver.ErrorMessage);
// Display raw bytes (as hex or byte count)
Console.WriteLine("IsOpened: {0}", driver.isOpen());
Console.WriteLine(string.Format("Bytes received: {0}", bytesReceived.Length));
Console.WriteLine(string.Format("Bytes (hex): {0}", BitConverter.ToString(bytesReceived)));
response = System.Text.Encoding.UTF8.GetString(bytesReceived);
Console.WriteLine("Bytes string: {0}",response);
// --- Get Serial No ---
message = ProductDetails2;
driver.SendMessage(message, message.Length,con.readTimeout);
bytesReceived = driver.GetRawData();
Assert.IsTrue(bytesReceived.Length > 0);
if (bytesReceived[0] == 0xFF)
Console.WriteLine("Error message: {0}", driver.ErrorMessage);
// Display raw bytes (as hex or byte count)
Console.WriteLine("IsOpened: {0}", driver.isOpen());
Console.WriteLine(string.Format("Bytes received: {0}", bytesReceived.Length));
Console.WriteLine(string.Format("Bytes (hex): {0}", BitConverter.ToString(bytesReceived)));
response = System.Text.Encoding.UTF8.GetString(bytesReceived);
Console.WriteLine("Bytes string: {0}",response);
message = CommDeviceSessionEnd;
driver.SendMessage(message, message.Length);
driver.Close();
}
}
-52
View File
@@ -1,52 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Copyright>Copyright © 2025</Copyright>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DefineConstants>TRACE;IPERL;</DefineConstants>
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DefineConstants>TRACE;IPERL;</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="System.IO.Ports" Version="10.0.0-rc.1.25451.107" />
<PackageReference Include="System.Security.Cryptography.Cng" Version="5.0.0" />
<PackageReference Include="System.Threading" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="NA2WNFC">
<HintPath>NfcHanler\NfcReaderLibrary\NA2WNFC.dll</HintPath>
</Reference>
<Reference Include="OBIDISC4NET">
<HintPath>NfcHanler\NfcReaderLibrary\OBIDISC4NET.dll</HintPath>
</Reference>
<Reference Include="OBIDISC4NETnative">
<HintPath>NfcHanler\NfcReaderLibrary\OBIDISC4NETnative.dll</HintPath>
</Reference>
<Reference Include="OBIDISC4NET_API">
<HintPath>NfcHanler\NfcReaderLibrary\OBIDISC4NET_API.dll</HintPath>
</Reference>
<Reference Include="PresentationCore">
<HintPath>..\..\..\..\..\Windows\Microsoft.NET\assembly\GAC_32\PresentationCore\v4.0_4.0.0.0__31bf3856ad364e35\PresentationCore.dll</HintPath>
</Reference>
<Reference Include="PresentationFramework">
<HintPath>..\..\..\..\..\Windows\Microsoft.NET\assembly\GAC_MSIL\PresentationFramework\v4.0_4.0.0.0__31bf3856ad364e35\PresentationFramework.dll</HintPath>
</Reference>
<Reference Include="Sensus">
<HintPath>NfcHanler\FieldLogicLibrary\Sensus.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
-9
View File
@@ -1,9 +0,0 @@
using NfcC7_DLL.NfcHanler.Protocols;
namespace NfcC7_DLL.NfcHanler;
public class HeadInfo
{
string SerialNr { get; set; }
OptoHeadStatus OptoHeadStatus { get; set; }
}
@@ -1,22 +0,0 @@
namespace NfcC7_DLL.NfcHanler
{
public class JsonDataFromPoseidon
{
public bool? NfcTagDetected { get; set; }
public int? ProductType { get; set; }
public string ProductTypeVersion { get; set; }
public string DeviceId { get; set; }
public string Reading { get; set; }
public string Reading_Totalizer { get; set; }
public string Reading_Digits { get; set; }
public string Reading_Shift { get; set; }
public string Reading_Resolution { get; set; }
public string Reading_Units { get; set; }
public string Reading_FlowDirection { get; set; }
public string Reading_FlowRate { get; set; }
public string CalibrationFactor { get; set; }
public bool? ReadingComplete { get; set; }
}
}
-216
View File
@@ -1,216 +0,0 @@
using System.Text.RegularExpressions;
using System.Windows;
using NfcC7_DLL.NfcHanler.Protocols;
using NfcC7_DLL.NfcHanler.Utils;
namespace NfcC7_DLL.NfcHanler;
public class NFCHeadService
{
private bool activeHandlerSessioEnabled = false;
private CliRunner _cliRunner;
private SerialPortData serialPort;
public NFCHeadService(SerialPortData serialPort)
{
this.serialPort = serialPort;
ValidateCliFileExistence(true);
}
private CliRunner CliRunner
{
get
{
return (_cliRunner != null ?
_cliRunner :
(_cliRunner = new CliRunner(CliLogging)));
}
}
private bool CliLogging{get {return false; }}
private static readonly Regex OpticalDataModeRegex = new Regex(
@"(?im)(?:" +
@"^\s*OpticalDataMode\s*Id\s*:\s*([^\r\n]+)\s*$" + // old format
@"|" +
@"""OpticalDataMode""\s*:\s*""?(0x[0-9A-Fa-f]+|\d+)""?" + // JSON format (handles hex and decimal)
@")",
RegexOptions.Compiled);
public bool TryGetOpticalDataMode(string result, out string s)
{
s = null;
if (string.IsNullOrEmpty(result))
return false;
var m = OpticalDataModeRegex.Match(result);
if (!m.Success)
return false;
// one of the groups will be filled
s = !string.IsNullOrEmpty(m.Groups[1].Value)
? m.Groups[1].Value.Trim()
: m.Groups[2].Value.Trim();
return true;
}
private static readonly Regex DeviceIdRegex = new Regex(
@"(?im)(?:" +
@"^\s*Device\s*Id\s*:\s*([^\r\n]+)\s*$" + // old format
@"|" +
@"""DeviceId""\s*:\s*""?([0-9]+)""?" + // JSON format
@")",
RegexOptions.Compiled);
public bool TryGetDeviceId(string result, out string s)
{
s = null;
if (string.IsNullOrEmpty(result))
return false;
var m = DeviceIdRegex.Match(result);
if (!m.Success)
return false;
// one of the groups will be filled
s = !string.IsNullOrEmpty(m.Groups[1].Value)
? m.Groups[1].Value.Trim()
: m.Groups[2].Value.Trim();
return true;
}
private void ValidateCliFileExistence(bool showErrorIfMissing)
{
if (serialPort != null)
{
if (!serialPort.CliExists)
{
throw new Exception("CLI file " + serialPort.SerialPortCmdClientPath + " does not exist! Current path: " + Environment.CurrentDirectory);
}
}
}
/// <summary>
/// ////////////
/// </summary>
public string? GetSerialNr()
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadDeviceIdTask = CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.DeviceId);
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadDeviceIdTask is Task<string>)
{
string serialNr;
if (optoheadDeviceIdTask.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadDeviceIdTask as Task<string>).Result;
if (TryGetDeviceId(result, out serialNr))
{
return serialNr;
}
}
}
return null;
}
public OptoHeadStatus SetTestingMode(OptoHeadStatus status)
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadMode = CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.Optohead, $"0x{((byte)status):X2}");
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadMode is Task<string>)
{
string strOpticalDataMode;
if (optoheadMode.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadMode as Task<string>).Result;
if (TryGetOpticalDataMode(result, out strOpticalDataMode))
{
byte value;
if (strOpticalDataMode.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
value = Convert.ToByte(strOpticalDataMode, 16); // interpret as hex
else
value = Convert.ToByte(strOpticalDataMode); // interpret as decimal
OptoHeadStatus optoheadStatus = (OptoHeadStatus)value;
return optoheadStatus;
}
}
}
return OptoHeadStatus.Unknown;
}
public OptoHeadStatus GetTestingMode()
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadMode = CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.Optohead);
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadMode is Task<string>)
{
string strOpticalDataMode;
if (optoheadMode.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadMode as Task<string>).Result;
if (TryGetOpticalDataMode(result, out strOpticalDataMode))
{
byte value;
if (strOpticalDataMode.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
value = Convert.ToByte(strOpticalDataMode, 16); // interpret as hex
else
value = Convert.ToByte(strOpticalDataMode); // interpret as decimal
OptoHeadStatus optoheadStatus = (OptoHeadStatus)value;
return optoheadStatus;
}
}
}
return OptoHeadStatus.Unknown;
}
private void SendCommand()
{
}
private string RawDataAnswer()
{
return "";
}
}
-109
View File
@@ -1,109 +0,0 @@
using System.IO.Ports;
using System.Windows.Documents;
using NfcC7_DLL.NfcHanler.Protocols;
using NfcC7_DLL.NfcHanler.Utils;
namespace NfcC7_DLL.NfcHanler;
public class OptoHeadService
{
public class Con
{
public string com = "COM5";
public int baudrate = 38400;
public int dataBits = 8;
public Parity parity = Parity.None;
public StopBits stopbits = StopBits.Two;
public int readTimeout = 5000;
public int writeTimeout = 1000;
}
private Con Connection { get; set; }
private SERIAL_Driver driver;
/// <summary>
/// Filed After Run() is called.
/// </summary>
public WaterMetrologyData? WaterMetrologyData { get; private set; }
public OptoHeadService(Con con)
{
Connection = con;
driver = new SERIAL_Driver();
}
public bool CreateSerialConnection()
{
bool isopen = false;
Con con = Connection;
byte[] message = {0x00};
byte[] bytesReceived;
if (!driver.isOpen())
{
isopen = driver.OpenConnection(
con.com,
con.baudrate,
con.dataBits,
con.parity,
con.stopbits,
con.readTimeout,
con.writeTimeout);
}
return isopen;
}
public void CloseSerialConnection()
{
dissableRunLoop = true;
driver.Close();
}
public void RunLoop()
{
Task.Run(() => Run());
}
private bool dissableRunLoop = false;
/// <summary>
/// Run the service. Catch one communication to WaterMetrologyData field.
/// </summary>
public void Run()
{
while (!dissableRunLoop)
{
WaterMetrologyData = ParseData(RunReading());
}
}
byte[] RunReading()
{
if (driver.isOpen())
{
driver.SendMessage(new byte[] {0x00}, 1);
return driver.GetRawData();
}
else
{
dissableRunLoop = true;
}
return [0xFF];
}
public WaterMetrologyData? ParseData(byte[] data)
{
try
{
return WaterMetrologyData.Parse(data, DateTime.Now, "");
}catch(Exception e)
{
return null;
}
}
}
@@ -1,9 +0,0 @@
namespace NfcC7_DLL.NfcHanler.Protocols;
public enum OptoHeadStatus : byte
{
Unknown = 0xFF,
OptoHeadDisabled = 0x00,
OptoHeadC2 = 0xC2,
OptoHeadC7 = 0xC7,
}
@@ -1,41 +0,0 @@
namespace NfcC7_DLL.NfcHanler.Protocols;
public class WaterMetrologyData
{
private OptoHeadStatus _optoHeadStatus;
private WaterMetrologyDataC7 c7Data;
private WaterMetrologyDataC2 c2Data;
public WaterMetrologyDataC7 C7Data { get => c7Data; }
public WaterMetrologyDataC2 C2Data { get => c2Data; }
public OptoHeadStatus OptoHeadStatus { get => _optoHeadStatus; }
public static WaterMetrologyData? Parse(byte[] data, DateTime dt, string dutinfo)
{
if (data.Length < 24)
{
throw new ArgumentException("Invalid data length for WaterMetrologyData C2.");
}
WaterMetrologyData waterMetrologyData = new WaterMetrologyData();
waterMetrologyData._optoHeadStatus = OptoHeadStatus.Unknown;
// Probably C2
if(data.Length > 24 && data.Length < 48)
{
waterMetrologyData.c2Data = WaterMetrologyDataC2.Parse(data, dt, dutinfo);
waterMetrologyData._optoHeadStatus = OptoHeadStatus.OptoHeadC2;
}
// Probably C7
else if(data.Length >= 48)
{
waterMetrologyData.c7Data = WaterMetrologyDataC7.Parse(data, dt, dutinfo);
waterMetrologyData._optoHeadStatus = OptoHeadStatus.OptoHeadC7;
}
return waterMetrologyData;
}
public override string ToString()
{
return $"Status: {_optoHeadStatus}, C7Data: {c7Data}, C2Data: {c2Data}";
}
}
@@ -1,91 +0,0 @@
namespace NfcC7_DLL.NfcHanler.Protocols
{
public class WaterMetrologyDataC2
{
public string DutInfo { get; set; }
public DateTime Dt { get; set; }
public int AdcSample { get; set; }
public short LastField { get; set; }
public short FlowRate { get; set; }
public uint Accumulator { get; set; }
public ushort FlipPeriod { get; set; }
public ushort VinfStart { get; set; }
public ushort VinfEnd { get; set; }
public short ElectrodeDelta { get; set; }
public ushort Impedance { get; set; }
public byte FieldDriveTime { get; set; }
public bool IsInLowFlow { get; set; }
public bool IsInEmptyPipe { get; set; }
public bool FastHPFC { get; set; }
public bool FieldPolarity { get; set; }
public bool ImpedancePolarity { get; set; }
public double CalcFlowmLps
{
get { return FlowRate / 4.0; } // FlowRate is in 1/4 mL/s
}
public double CalcFlowGPM
{
get { return CalcFlowmLps * 0.015850323141489; } // mL/s to gal/min conversion
}
public double CalcAccGal
{
get { return (Accumulator / 4.0) * 0.000264172; } // Accumulator is in 1/4 mL, convert to gallons
}
public static WaterMetrologyDataC2 Parse(string base64Data, DateTime dt, string dutinfo)
{
byte[] data = Convert.FromBase64String(base64Data);
return Parse(data, dt, dutinfo);
}
public static WaterMetrologyDataC2 Parse(byte[] data, DateTime dt, string dutinfo)
{
if (data.Length < 24)
{
throw new ArgumentException("Invalid data length for WaterMetrologyData C2.");
}
WaterMetrologyDataC2 result = new WaterMetrologyDataC2();
result.DutInfo = dutinfo;
result.Dt = dt;
result.AdcSample = BitConverter.ToInt32(data, 0);
result.LastField = BitConverter.ToInt16(data, 4);
result.FlowRate = BitConverter.ToInt16(data, 6);
result.Accumulator = BitConverter.ToUInt32(data, 8);
result.FlipPeriod = BitConverter.ToUInt16(data, 12);
result.VinfStart = BitConverter.ToUInt16(data, 14);
result.VinfEnd = BitConverter.ToUInt16(data, 16);
result.ElectrodeDelta = BitConverter.ToInt16(data, 18);
result.Impedance = BitConverter.ToUInt16(data, 20);
result.FieldDriveTime = data[22];
byte flags = data[23];
result.IsInLowFlow = (flags & 0x01) != 0;
result.IsInEmptyPipe = (flags & 0x02) != 0;
result.FastHPFC = (flags & 0x04) != 0; // Fast High Pass Filter Constant in bit 2
result.FieldPolarity = (flags & 0x08) != 0; // Field Polarity in bit 3
result.ImpedancePolarity = (flags & 0x10) != 0; // Impedance Polarity in bit 4
return result;
}
//public override string ToString()
//{
// return $"ADC Sample: {AdcSample}, Last Field: {LastField}, Flow Rate: {FlowRate}, Accumulator: {Accumulator}, " +
// $"Flip Period Ticks: {FlipPeriodTicks}, Vinf Start: {VinfStart}, Vinf End: {VinfEnd}, Electrode Delta: {ElectrodeDelta}, " +
// $"Impedance: {Impedance}, Field Drive Time: {FieldDriveTime}, Is Low Flow: {IsInLowFlow}, Is Empty Pipe: {IsInEmptyPipe}, " +
// $"Fast High Pass Filter: {FastHighPassFilterConstant}, Field Polarity: {FieldPolarity}, Impedance Polarity: {ImpedancePolarity}";
//}
public override string ToString()
{
return $"DutInfo: {DutInfo}, Dt: {Dt}, ADC Sample: {AdcSample}, Last Field: {LastField}, Flow Rate: {FlowRate}, Accumulator: {Accumulator}, " +
$"Flip Period: {FlipPeriod}, Vinf Start: {VinfStart}, Vinf End: {VinfEnd}, Electrode Delta: {ElectrodeDelta}, " +
$"Impedance: {Impedance}, Field Drive Time: {FieldDriveTime}, Is Low Flow: {IsInLowFlow}, Is Empty Pipe: {IsInEmptyPipe}, " +
$"Fast HPFC: {FastHPFC}, Field Polarity: {FieldPolarity}, Impedance Polarity: {ImpedancePolarity}, " +
$"Calc Flow mL/s: {CalcFlowmLps:F2}, Calc Flow GPM: {CalcFlowGPM:F2}, Calc Acc Gal: {CalcAccGal:F2}";
}
}
}
@@ -1,92 +0,0 @@
namespace NfcC7_DLL.NfcHanler.Protocols
{
public class WaterMetrologyDataC7 : WaterMetrologyDataC2
{
// New fields for C7
public int LastFieldmilliGauss { get; set; }
public int ImpedanceI { get; set; } // In-phase impedance
public int ImpedanceQ { get; set; } // Out-of-phase impedance
public int NoiseMetric { get; set; }
public short LearningLockout { get; set; }
public short ReverseBuffer { get; set; }
public int ConditionedAdc { get; set; }
public uint Totalalizer { get; set; }
//public bool IsInLowFlow { get; set; }
//public bool IsInEmptyPipe { get; set; }
//public bool FastHPFC { get; set; }
//public bool FieldPolarity { get; set; }
//public bool ImpedancePolarity { get; set; }
public bool MagTamperState { get; set; }
public bool IsLearningActive { get; set; }
public bool AdcShiftsUpdated { get; set; }
public static WaterMetrologyDataC7 Parse(string base64Data, DateTime dt, string dutinfo)
{
byte[] data = Convert.FromBase64String(base64Data);
return Parse(data, dt, dutinfo);
}
public static WaterMetrologyDataC7 Parse(byte[] data, DateTime dt, string dutinfo)
{
// You may want to check for the minimum length required for C7
if (data.Length < 48) /* minimum required length for C7 */
{
throw new ArgumentException("Invalid data length for WaterMetrologyData C7.");
}
var result = new WaterMetrologyDataC7();
// Parse base C2 fields
var c2 = WaterMetrologyDataC2.Parse(data, dt, dutinfo);
//Copy base fields
result.DutInfo = c2.DutInfo;
result.Dt = c2.Dt;
result.AdcSample = c2.AdcSample;
result.LastField = c2.LastField;
result.FlowRate = c2.FlowRate;
result.Accumulator = c2.Accumulator;
result.FlipPeriod = c2.FlipPeriod;
result.VinfStart = c2.VinfStart;
result.VinfEnd = c2.VinfEnd;
result.ElectrodeDelta = c2.ElectrodeDelta;
result.Impedance = c2.Impedance;
result.FieldDriveTime = c2.FieldDriveTime;
result.IsInLowFlow = c2.IsInLowFlow;
result.IsInEmptyPipe = c2.IsInEmptyPipe;
result.FieldPolarity = c2.FieldPolarity;
result.ImpedancePolarity = c2.ImpedancePolarity;
// Parse new C7 fields (replace ENUM_OptPack0xC7.FIELD_MILLI_GAUSS etc. with actual offsets)
byte flags = data[23];
result.MagTamperState = (flags & 0x60) != 0; // bits 5 and 6 represent MagTamperState
result.IsLearningActive = (flags & 0x80) != 0; // bit 7 represents IsLearningActive
byte flagTwo = data[24];
result.AdcShiftsUpdated = (flagTwo & 0x01) != 0; // bit 0 represents AdcShiftsUpdated
result.LastFieldmilliGauss = BitConverter.ToInt32(data, 25);
result.ImpedanceI = BitConverter.ToInt32(data, 29); // in phase
result.ImpedanceQ = BitConverter.ToInt32(data, 33); // out of phase
result.NoiseMetric = BitConverter.ToInt32(data, 37); //
result.LearningLockout = BitConverter.ToInt16(data, 41);
result.ReverseBuffer = BitConverter.ToInt16(data, 43);
result.ConditionedAdc = BitConverter.ToInt32(data, 45);
result.Totalalizer = BitConverter.ToUInt32(data, 49);
return result;
}
public override string ToString()
{
return $"C7: LastFieldmilliGauss={LastFieldmilliGauss}, ImpedanceI={ImpedanceI}, ImpedanceQ={ImpedanceQ}, NoiseMetric={NoiseMetric}, LearningLockout={LearningLockout}, ReverseBuffer={ReverseBuffer}, ConditionedAdc={ConditionedAdc}, Totalalizer={Totalalizer}, MagTamperState={MagTamperState}, IsLearningActive={IsLearningActive}, AdcShiftsUpdated={AdcShiftsUpdated}" + base.ToString();
}
}
}
-1
View File
@@ -1 +0,0 @@
# Protocol Description
-262
View File
@@ -1,262 +0,0 @@
using System.Diagnostics;
using System.Reflection;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NfcC7_DLL.NfcHanler.Utils
{
public class CliRunner
{
//static readonly Logger log = LogManager.GetLogger(typeof(CliRunner));
//private readonly ILog log;
private List<Task> taskPool = new List<Task>();
private long startTime;
public List<Task> TaskPool { get { return taskPool; } }
public void AddTask(Task task) { taskPool.Add(task); }
public void WaitAll() { Task.WaitAll(taskPool.ToArray()); }
/// <summary>
/// continue with WhenAny() to commpare results if time out is reached
/// </summary>
/// <param name="timeout"></param>
/// <returns></returns>
public Task AddTimeOut(int timeout)
{
Task timeOut = Task.Delay(timeout);
taskPool.Add(timeOut);
return timeOut;
}
/// <summary>
/// mainly used for time out additional task to compare results
/// </summary>
/// <returns></returns>
public Task WhenAny() { return Task.WhenAny(taskPool.ToArray()); }
public void Clear() { taskPool.Clear(); }
public void CancelAll() { Task.WhenAll(taskPool).ContinueWith(t => { }); }
public void StartAll()
{
taskPool.ForEach(t => t.Start());
}
public bool AreTasksDone()
{
return taskPool.All(task => task.IsCompleted);
}
public long StartTime
{
get => startTime;
}
public bool TimeOutReceived(long timeout)
{
return (DateTime.Now.Ticks - startTime) > timeout;
}
public CliRunner(bool isCliLogging)
{
startTime = DateTime.Now.Ticks;
if (isCliLogging)
{
try
{
/*log = new ScopedLoggerFactory().CreateLogger<CliRunner>(
@"C:\TBF\Logs\CliRunner.txt",
10, // maxFileSizeMB
7, // maxBackups
log4net.Core.Level.Debug,
true, // zipRolledFiles
true, // singleZipPerDay
TimeSpan.FromMinutes(2) // zipScanInterval
);*/
}
catch (Exception ex)
{
// Fallback to console or handle gracefully
Console.WriteLine($"Failed to initialize logger: {ex.Message}");
}
}
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <param name="args"></param>
/// <typeparam name="T"></typeparam>
public Task AddSendAsync(SerialPortData data, SerialPortData.EMeterArg eMeterArg)
{
var task = SendAsync(data.SerialPortCmdClientPath, data.DefaultArgSettingsRead(eMeterArg));
taskPool.Add(task);
return task;
}
public Task AddSendAsync(SerialPortData data, SerialPortData.EMeterArg eMeterArg, string arg)
{
var task = SendAsync(data.SerialPortCmdClientPath, data.DefaultArgSettingsWrite(eMeterArg, arg));
taskPool.Add(task);
return task;
}
public void AddSendAsync(string fileName, string args)
{
var task = SendAsync(fileName, args);
taskPool.Add(task);
}
public async Task<string> SendAsync(string fileName, string args, CancellationToken ct = default)
{
var psi = new ProcessStartInfo
{
FileName = fileName,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
process.Start();
Task<string> stdOutTask = process.StandardOutput.ReadToEndAsync();
Task<string> stdErrTask = process.StandardError.ReadToEndAsync();
try
{
await Task.WhenAll(stdOutTask, stdErrTask, process.WaitForExitAsync(ct));
}
catch (OperationCanceledException)
{
if (!process.HasExited)
{
process.Kill();
}
throw;
}
string allOutput = (stdOutTask.Result ?? "") + (stdErrTask.Result ?? "");
//log?.Debug(allOutput);
return allOutput;
}
public Task<T> AddRunAndCaptureJsonAsync<T>(SerialPortData data, SerialPortData.EMeterArg eMeterArg) where T : new()
{
var task = RunAndCaptureJsonAsync<T>(data.SerialPortCmdClientPath, data.DefaultArgSettingsRead(eMeterArg));
taskPool.Add(task);
return task;
}
public async Task<T> RunAndCaptureJsonAsync<T>(string fileName, string args, CancellationToken ct = default) where T : new()
{
var psi = new ProcessStartInfo
{
FileName = fileName,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
process.Start();
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(ct));
string allOutput = (stdoutTask.Result ?? "") + (stderrTask.Result ?? "");
//log?.Debug(allOutput);
string json = ExtractJson(allOutput);
if (TryJsonStringDeserialize(json, out T result)) return result;
return default;
}
public bool TryJsonStringDeserialize<T>(string json, out T runAndCaptureJsonAsync) where T : new()
{
if (json != null)
{
try
{
runAndCaptureJsonAsync = JsonConvert.DeserializeObject<T>(json);
return true;
}
catch (Exception ex)
{
// log.Debug(ex.Message);
runAndCaptureJsonAsync = TryConvert<T>(json);
return true;
}
}
runAndCaptureJsonAsync = default;
return false;
}
private static T TryConvert<T>(string json) where T : new()
{
T obj = new T();
try
{
JObject jObject = JObject.Parse(json);
foreach (PropertyInfo prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!prop.CanWrite) continue;
JToken token;
if (jObject.TryGetValue(prop.Name, StringComparison.OrdinalIgnoreCase, out token))
{
try
{
object value = token.ToObject(prop.PropertyType);
prop.SetValue(obj, value);
}
catch
{
// leave default if conversion fails
}
}
// else → keep default value
}
}
catch (Exception ex)
{
Console.WriteLine($"TryConvert failed: {ex.Message}");
}
return obj;
}
public string ExtractJson(string text)
{
int start = text.IndexOf('{');
int end = text.LastIndexOf('}');
if (start >= 0 && end > start)
{
return text.Substring(start, end - start + 1);
}
return null;
}
}
}
-167
View File
@@ -1,167 +0,0 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO.Ports;
//*****************************************************************************
// Copyright 2020 Sensus GmbH Ludwigshafen. All rights reserved.
// Author: Venkat, Rajeshwar
//*****************************************************************************
namespace NfcC7_DLL.NfcHanler.Utils
{
public class SERIAL_Driver
{
public string ErrorMessage { get; private set; }
public Collection<byte> SerialPortReadBuffer = new Collection<byte>();
private SerialPort _serialPort;
private List<byte[]> _binMessages = new List<byte[]>();
private bool _isReading;
private Parity Parity { get; set; }
private StopBits StopBits { get; set; }
public SERIAL_Driver()
{
_serialPort = new SerialPort();
}
public bool OpenConnection(string comPort, int baudrate, int dataBits, Parity parity, StopBits stopbits, int readTimeout=1000, int writeTimeout = 1000)
{
lock (this)
{
if ((_serialPort != null) && (_serialPort.IsOpen))
{
_serialPort.DataReceived -= DataReceivedHandler;
_serialPort.Close();
_serialPort.Dispose();
_serialPort = null;
}
try
{
ErrorMessage = "";
//_serialPort = new SerialPort(comPort, 57600, Parity.None, 8, StopBits.Two);
_serialPort = new SerialPort(comPort, baudrate, parity, dataBits, stopbits);
_serialPort.ReadTimeout = readTimeout;
_serialPort.WriteTimeout = writeTimeout;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
_serialPort.Open();
}
catch (Exception ex)
{
ErrorMessage = String.Format("COM error: Open failed {0}.{1}", comPort, ex.Message);
return false;
}
if (!_serialPort.IsOpen)
{
ErrorMessage = String.Format("COM error: Can't Open {0}.", comPort);
return false;
}
}//End Lock
return true;
}
public bool SendMessage(byte[] sendDataBytes, int length, int readTimeout = 1000, int writeTimeout=1000)
{
if (!isOpen()) return false;
if (sendDataBytes.Length == 0) return true; // nothing to send - no error
try
{
PrepareReading(); //clear read buffer etc.
_serialPort.WriteTimeout = writeTimeout;
_serialPort.ReadTimeout = readTimeout;
_serialPort.Write(sendDataBytes, 0, length);
_isReading = true;
Thread.Sleep(100);
var stopWatch = Stopwatch.StartNew(); //start stop watch for data recevie timeout
while (_isReading) //wait until reading finishes or timeout occur
{
if (stopWatch.ElapsedMilliseconds > readTimeout)
{
stopWatch.Stop();
ErrorMessage = "COM error: Receive timeout";
return false;
}
}
}
catch (Exception ex)
{
ErrorMessage = String.Format("COM error: Transmit timeout {0}.{1}", _serialPort.PortName, ex.Message);
return false; // Exception in send function
}
return true;
}
private void PrepareReading()
{
_serialPort.DiscardInBuffer();
if(_binMessages != null) _binMessages.Clear();
_isReading = true;
}
public byte[] GetRawData()
{
try
{
if (_binMessages.Count > 0)
return _binMessages[0].ToArray();
else
{
return null;
}
}
catch(Exception)
{
byte[] err = { 0xFF };
return err;
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
if (!_serialPort.IsOpen) return;
lock (this)
{
Thread.Sleep(100);
if (!_serialPort.IsOpen) return;
SerialPortReadBuffer = new Collection<byte>();
while (_serialPort.BytesToRead > 0)
{
SerialPortReadBuffer.Add((byte)_serialPort.ReadByte());
}
_binMessages.Add(SerialPortReadBuffer.ToArray());
_isReading = false;
}
}
public void CloseConnection()
{
if ((_serialPort != null) && (_serialPort.IsOpen))
{
_serialPort.DataReceived -= DataReceivedHandler;
_serialPort.Close();
_serialPort.Dispose();
_serialPort = null;
}
}
public void Close()
{
if (isOpen())
{
_serialPort.Close();
}
}
public void Dispose()
{
if (_serialPort != null)
{
_serialPort.Dispose();
}
}
public bool isOpen()
{
if(_serialPort != null)
return _serialPort.IsOpen;
return false;
}
}
}
@@ -1,72 +0,0 @@
namespace NfcC7_DLL.NfcHanler.Utils
{
public class SerialPortData
{
private Boolean? _cliExists;
public bool CliExists { get {
if (_cliExists == null || !_cliExists.HasValue)
{
_cliExists = File.Exists(SerialPortCmdClientPath);
}
return _cliExists.Value;
} }
public string SerialPortCmdClientPath {
get {
#if DEBUG
return Path.Combine("C:","TBF","Cli", CmdClientName);
#else
return Path.Combine("..","Cli", CmdClientName);
#endif
}
}
public string CmdClientName { get; set; } = "HalCli.exe";
public string PortName { get; set; }
public int MeterType { get; set; }
public enum EMeterArg {
Calibration = 0,
AllParams = 2,
DeviceId = 3,
Optohead = 4,
}
EMeterArg _eMeterArg = EMeterArg.AllParams;
public string DefaultArgSettingsRead(EMeterArg eMeterArg)
{
switch (eMeterArg)
{
case EMeterArg.AllParams:
return $"-p {PortName} -m {MeterType} --operation readall";
case EMeterArg.DeviceId:
return $"-p {PortName} -m {MeterType} --operation read --parameter DeviceId";
case EMeterArg.Optohead:
return $"-p {PortName} -m {MeterType} --operation read --parameter \"OpticalDataMode\"";
default:
throw new Exception("Not implemented correct command!");
}
}
public string DefaultArgSettingsWrite(EMeterArg eMeterArg, string arg)
{
switch (eMeterArg)
{
case EMeterArg.Calibration:
return $"-p {PortName} -m {MeterType} --operation write --parameter Calibration --value {arg}";
case EMeterArg.Optohead:
return $"-p {PortName} -m {MeterType} --operation write --parameter \"OpticalDataMode\" --value {arg}";
default:
throw new Exception("Not implemented correct command!");
}
}
public SerialPortData(
string portName,
string cmdClientName,
int meterType)
{
PortName = portName;
CmdClientName = cmdClientName;
MeterType = meterType;
}
}
}
-156
View File
@@ -1,156 +0,0 @@
using System.Text;
//*****************************************************************************
// Copyright 2020 Sensus GmbH Ludwigshafen. All rights reserved.
// Author: Venkat, Rajeshwar
//*****************************************************************************
namespace NfcC7_DLL.NfcHanler.Utils
{
public static class Tools
{
public static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
// thanks to https://stackoverflow.com/questions/43289/comparing-two-byte-arrays-in-net
if (a1.Length != a2.Length)
return false;
for (int i = 0; i < a1.Length; i++)
if (a1[i] != a2[i])
return false;
return true;
}
public static string SwapHex(string sHex)
{
string sResult = "";
int iPos = sHex.Length - 2;
while (iPos >= 0)
{
sResult += sHex.Substring(iPos, 2);
sHex = sHex.Remove(iPos, 2);
iPos = sHex.Length - 2;
}
return sResult;
}
public static string DecimalToHexString(string value, int size = 1)
{
try
{
long Lval = long.Parse(value);
if (size == 1) return Lval.ToString("X2");
if (size == 2) return Lval.ToString("X4");
if (size == 4) return Lval.ToString("X8");
}
catch (Exception)
{
if (size == 1) return "00";
if (size == 2) return "0000";
if (size == 4) return "00000000";
}
return "00";
}
public static string ByteToHexString(byte data)
{
List<byte> val = new List<byte>();
val.Add(data);
byte[] arr = val.ToArray();
return BytesToHex(arr);
}
public static string BytesToHex(byte[] data)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in data)
sb.Append(b.ToString("X2"));
return sb.ToString();
}
public static byte[] HexStringToByteArray(String hexString)
{
int numberChars = hexString.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
return bytes;
}
public enum InitialCrcValue
{
Zeros,
NonZero1 = 0xffff,
NonZero2 = 0x1D0F
}
public class Crc16Ccitt
{
private const ushort poly = 0x1021;
ushort[] table = new ushort[256];
ushort initialValue = 0;
public ushort ComputeChecksum(byte[] bytes)
{
ushort crc = this.initialValue;
for (int i = 0; i < bytes.Length; ++i)
{
crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);
}
return crc;
}
public byte[] ComputeChecksumBytes(byte[] bytes)
{
ushort crc = ComputeChecksum(bytes);
return BitConverter.GetBytes(crc);
}
public Crc16Ccitt(InitialCrcValue initialValue)
{
this.initialValue = (ushort) initialValue;
ushort temp, a;
for (int i = 0; i < table.Length; ++i)
{
temp = 0;
a = (ushort) (i << 8);
for (int j = 0; j < 8; ++j)
{
if (((temp ^ a) & 0x8000) != 0)
{
temp = (ushort) ((temp << 1) ^ poly);
}
else
{
temp <<= 1;
}
a <<= 1;
}
table[i] = temp;
}
}
public byte[] calcCRCfromMessage(byte[] message)
{
// CRC calculation goes from MessageID to Password
// For Read this means MsgID (1) + Offset (2) + PayloadLength (1) + Password (2) = 6
// for write the length of the payload comes on top.
// STX(1), length(1), CRC(2) and ETX(1) are excluded, in total 5 bytes.
//
// the method works both for sending messages (where the CRC and ETX are not in message)
// and for receiving messages (where the CRC and ETX are included at the end)
byte[] crc_msg = new byte[message[1]]; // message length is 2nd byte
Array.Copy(message, 2, crc_msg, 0, crc_msg.Length);
return ComputeChecksumBytes(crc_msg);
}
public string commentCRC(byte[] crc_meter, byte[] crc_computed)
{
bool crc_do_match = Tools.ByteArrayCompare(crc_meter, crc_computed);
string crcComment = crc_do_match ? "ok." : "CRC DOESN'T MATCH!!";
return "CRC Meter: " + Tools.BytesToHex(crc_meter) + (crc_do_match ? " == " : " != ")
+ "CRC Computed: " + Tools.BytesToHex(crc_computed) + ". " + crcComment;
}
public bool crc_do_match(byte[] a, byte[] b)
{
return ByteArrayCompare(a, b);
}
}
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ namespace ResetBatchNr
ls.BatchNr = 1;
ls.Save();
Console.WriteLine(@"BatchNr was reset to 1");
Console.WriteLine("BatchNr was reset to 1");
Console.ReadLine();
return;
}
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?><configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.5.0" newVersion="4.0.5.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.4.0" newVersion="4.0.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.6.0" newVersion="4.1.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.2.0" newVersion="6.0.2.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
+1 -17
View File
@@ -29,12 +29,8 @@ namespace Results.Entities
public virtual long ErrorIndicators { get; set; } /// Not mapped to DB !!!, bit24=E25, bit25=E26, bit26=E27, bit27=E28 (error flags)
public virtual long InfoIndicators { get; set; } /// Not mapped to DB !!!, bit24=E25, bit25=E26, bit26=E27, bit27=E28 (info flags)
public virtual bool TestDone { get; set; } /// true = test was completed
public virtual bool Passed { get; set; } /// true = test passed, water meter is OK
public virtual bool Passed { get; set; } /// true = test passed, water meter is OK
#if IPERL
public virtual int CalibFactor { get; set; }
public virtual int CalibFactorLNA { get; set; }
public virtual int Q2CorrRL { get; set; }
public virtual int Q2CorrLR { get; set; }
public virtual string ExtraDataPath { get; set; } /// Relative path to a file with opto-data/raw-data
public virtual float X1 { get; set; }
public virtual float X2 { get; set; }
@@ -170,10 +166,6 @@ namespace Results.Entities
TestDone = src.TestDone;
Passed = src.Passed;
#if IPERL
CalibFactor = src.CalibFactor;
CalibFactorLNA = src.CalibFactorLNA;
Q2CorrRL = src.Q2CorrRL;
Q2CorrLR = src.Q2CorrLR;
ExtraDataPath = src.ExtraDataPath;
X1 = src.X1;
X2 = src.X2;
@@ -217,10 +209,6 @@ namespace Results.Entities
writer.Write(TestDone);
writer.Write(Passed);
#if IPERL
writer.Write(CalibFactor);
writer.Write(CalibFactorLNA);
writer.Write(Q2CorrRL);
writer.Write(Q2CorrLR);
writer.Write((ExtraDataPath != null) ? ExtraDataPath : string.Empty);
writer.Write(X1);
writer.Write(X2);
@@ -261,10 +249,6 @@ namespace Results.Entities
TestDone = reader.ReadBoolean();
Passed = reader.ReadBoolean();
#if IPERL
CalibFactor = reader.ReadInt32();
CalibFactorLNA = reader.ReadInt32();
Q2CorrRL = reader.ReadInt32();
Q2CorrLR = reader.ReadInt32();
ExtraDataPath = reader.ReadString();
X1 = reader.ReadSingle();
X2 = reader.ReadSingle();
+8
View File
@@ -350,6 +350,14 @@ namespace Results
Pulses_aux, /// 296 Compound aux meter pulses (recalculated so that the gated ref. pulses for this meter are equal to the total ref. pulses)
Failed_meters_countE15, /// 297
Uncertainty_DIV1, /// 298 Diverter DIV1 Uncertainty
Uncertainty_DIV2, /// 299 Diverter DIV2 Uncertainty
Uncertainty_DIV3, /// 300 Diverter DIV3 Uncertainty
Uncertainty_DIV4, /// 301 Diverter DIV4 Uncertainty
Uncertainty_DIV5, /// 302 Diverter DIV5 Uncertainty
Uncertainty_TEMP1, /// 303 Temp1 Uncertainty
Count,
}
+71 -5
View File
@@ -19,7 +19,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;IPERL;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -29,12 +29,30 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;IPERL;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="ClosedXML, Version=0.105.0.0, Culture=neutral, PublicKeyToken=fd1eb21b62ae805b, processorArchitecture=MSIL">
<HintPath>..\packages\ClosedXML.0.105.0-rc\lib\netstandard2.0\ClosedXML.dll</HintPath>
</Reference>
<Reference Include="ClosedXML.Parser, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1d5f7376574c51ec, processorArchitecture=MSIL">
<HintPath>..\packages\ClosedXML.Parser.2.0.0-preview1\lib\netstandard2.0\ClosedXML.Parser.dll</HintPath>
</Reference>
<Reference Include="DocumentFormat.OpenXml, Version=3.1.1.0, Culture=neutral, PublicKeyToken=8fb06cb64d019a17, processorArchitecture=MSIL">
<HintPath>..\packages\DocumentFormat.OpenXml.3.1.1\lib\net46\DocumentFormat.OpenXml.dll</HintPath>
</Reference>
<Reference Include="DocumentFormat.OpenXml.Framework, Version=3.1.1.0, Culture=neutral, PublicKeyToken=8fb06cb64d019a17, processorArchitecture=MSIL">
<HintPath>..\packages\DocumentFormat.OpenXml.Framework.3.1.1\lib\net46\DocumentFormat.OpenXml.Framework.dll</HintPath>
</Reference>
<Reference Include="EPPlus.Interfaces, Version=8.0.0.0, Culture=neutral, PublicKeyToken=a694d7f3b0907a61, processorArchitecture=MSIL">
<HintPath>..\packages\EPPlus.Interfaces.8.0.0\lib\net462\EPPlus.Interfaces.dll</HintPath>
</Reference>
<Reference Include="ExcelNumberFormat, Version=1.1.0.0, Culture=neutral, PublicKeyToken=23c6f5d73be07eca, processorArchitecture=MSIL">
<HintPath>..\packages\ExcelNumberFormat.1.1.0\lib\net20\ExcelNumberFormat.dll</HintPath>
</Reference>
<Reference Include="FluentNHibernate">
<HintPath>..\packages\FluentNHibernate.2.0.3.0\lib\net40\FluentNHibernate.dll</HintPath>
</Reference>
@@ -47,15 +65,51 @@
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.HashCode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.HashCode.1.1.1\lib\net461\Microsoft.Bcl.HashCode.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IO.RecyclableMemoryStream, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IO.RecyclableMemoryStream.3.0.1\lib\netstandard2.0\Microsoft.IO.RecyclableMemoryStream.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="MySql.Data">
<HintPath>..\packages\MySql.Data.6.6.5\lib\net40\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="NHibernate">
<HintPath>..\packages\NHibernate.4.0.4.4000\lib\net40\NHibernate.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="RBush, Version=4.0.0.0, Culture=neutral, PublicKeyToken=c77e27b81f4d0187, processorArchitecture=MSIL">
<HintPath>..\packages\RBush.Signed.4.0.0\lib\net47\RBush.dll</HintPath>
</Reference>
<Reference Include="SixLabors.Fonts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d998eea7b14cab13, processorArchitecture=MSIL">
<HintPath>..\packages\SixLabors.Fonts.1.0.0\lib\netstandard2.0\SixLabors.Fonts.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.6.1\lib\net462\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.Annotations, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.ComponentModel.Annotations.5.0.0\lib\net461\System.ComponentModel.Annotations.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Memory, Version=4.0.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.6.2\lib\net462\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.6.1\lib\net462\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.1.1\lib\net462\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Security" />
<Reference Include="System.Security.Cryptography.Xml, Version=8.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Cryptography.Xml.8.0.2\lib\net462\System.Security.Cryptography.Xml.dll</HintPath>
</Reference>
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Windows.Forms.DataVisualization" />
<Reference Include="System.Xml.Linq" />
@@ -63,6 +117,7 @@
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="BatchResults.cs" />
@@ -180,6 +235,17 @@
<DesignTime>True</DesignTime>
<DependentUpon>Strings.resx</DependentUpon>
</Compile>
<Compile Include="RigUncertainty.cs" />
<Compile Include="Uncertainty\Calculation\CalculationTable.cs" />
<Compile Include="Uncertainty\Calculation\Math.cs" />
<Compile Include="Uncertainty\CommonExcell.cs" />
<Compile Include="Uncertainty\CommonTable\Table.cs" />
<Compile Include="Uncertainty\DEItem.cs" />
<Compile Include="Uncertainty\DEUtils.cs" />
<Compile Include="Uncertainty\DocumentSheets.cs" />
<Compile Include="Uncertainty\ProcessDataLine.cs" />
<Compile Include="Uncertainty\ProcessDataMeterLine.cs" />
<Compile Include="Uncertainty\CommonTable\Cell.cs" />
<Compile Include="Utils.cs" />
<Compile Include="WMeterRsltItemSpec.cs" />
</ItemGroup>
@@ -241,9 +307,7 @@
</EmbeddedResource>
<EmbeddedResource Include="Resources\Strings.fr.resx" />
<EmbeddedResource Include="Resources\Strings.it.resx" />
<EmbeddedResource Include="Resources\Strings.pl.resx">
<SubType>Designer</SubType>
</EmbeddedResource>
<EmbeddedResource Include="Resources\Strings.pl.resx" />
<EmbeddedResource Include="Resources\Strings.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Strings.Designer.cs</LastGenOutput>
@@ -251,6 +315,8 @@
<EmbeddedResource Include="Resources\Strings.ru.resx" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
<None Include="Resources\Headpic.png" />
</ItemGroup>
<ItemGroup>
+144
View File
@@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using ClosedXML.Excel;
using log4net;
using Results.Resources;
using Results.Uncertainty;
namespace Results
{
/// <summary>
/// Uncertaintity based on calculation
/// </summary>
public class RigUncertainty
{
private static readonly ILog log = LogManager.GetLogger(typeof(RigUncertainty));
//Based on |Excel calculation
//1.step feed Excel
//2.step get calculated data from excel
private string DocumentName { get; set; }
private XLWorkbook Document;
private Boolean openedDocument;
public Boolean IsOpenedDocument { get { return openedDocument; } }
Dictionary<int, ProcessDataLine> processDataDict = new Dictionary<int, ProcessDataLine>();
public RigUncertainty()
{
}
public RigUncertainty(string DocumentName)
{
this.DocumentName = DocumentName;
}
public void OpenDocument()
{
this.openedDocument = TryOpenDocument();
}
private Boolean TryOpenDocument()
{
try
{
Document = new XLWorkbook(DocumentName);
return true;
}
catch (Exception e)
{
log.Error("Can`t open excel document!",e);
return false;
}
}
public void CloaseDocument()
{
this.openedDocument = !TryCloseDocument();
}
private Boolean TryCloseDocument()
{
try
{
Document.Dispose(); // Closes the file and releases resources
return true;
}
catch (Exception e)
{
log.Error("Can`t open excel document!",e);
return false;
}
}
public IXLWorksheet GetWorksheet(DocumentSheets sheet)
{
string sheetName = EnumExtensions.GetDescription(sheet);
try
{
var xlWorksheet = Document.Worksheet(sheetName);
return xlWorksheet;
}
catch (Exception e)
{
log.Error($"Can`t get \"{sheetName}\" worksheet!", e);
return null;
}
}
public Boolean GetCalculatedDataFromExcel()
{
// Code to get calculated data from Excel
return true;
}
public void SetDataToExcel()
{
string sheetString = EnumExtensions.GetDescription(DocumentSheets.RADATA);
IXLWorksheet worksheet = Document.Worksheet(sheetString);
// # store data to Excel workbook
// ## get data from DB
int line = 3;
ProcessDataLine pDataLine = new ProcessDataLine();
processDataDict.Add(line,pDataLine);
// ### line process data
// ## Store to document
foreach ( var processDataKey in processDataDict)
{
//get Process data line base by row
ProcessDataLine processDataLine = processDataKey.Value;
CommonExcell.InsertValueLineProcessData(this, processDataKey.Key, processDataLine);
}
}
public void SaveResultDataToDatabase()
{
// Code to save data to database
}
public void SaveChangesToDocument()
{
if (Document != null && openedDocument)
{
Document.Save();
}
}
}
}
@@ -0,0 +1,239 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ClosedXML.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
namespace Results.Uncertainty.Calculation
{
public class ColumnValue
{
private int iColumn;
private double value;
public int IColumn => iColumn;
public double Value
{
get => value;
set => this.value = value;
}
public ColumnValue(int iColumn)
{
this.iColumn = iColumn;
}
public ColumnValue(int iColumn, double value)
{
this.iColumn = iColumn;
this.value = value;
}
}
public class BatchProcessTable
{
private Dictionary<int, ProcessDataLine> processTable;
public Dictionary<int, ProcessDataLine> ProcessTable
{
get => processTable;
set => processTable = value;
}
public IList<ColumnValue> GetListMeterValue(int iMeter, int iMeterSubvalueIndex)
{
IList<ColumnValue> xx = new List<ColumnValue>();
foreach (KeyValuePair<int, ProcessDataLine> dataLine in processTable)
{
XLCellValue cellValue = dataLine.Value.processDataMeterList[iMeter].val[iMeterSubvalueIndex];
xx.Add(new ColumnValue((int)dataLine.Key ,cellValue.GetNumber()));
}
return xx;
}
public Dictionary<int, IList<ColumnValue>> GetKBuoyancy()
{
Dictionary<int, IList<ColumnValue>> table = new Dictionary<int, IList<ColumnValue>>();
IList<ColumnValue> bc = new List<ColumnValue>();
IList<ColumnValue> bi = new List<ColumnValue>();
IList<ColumnValue> bj = new List<ColumnValue>();
IList<ColumnValue> bm = new List<ColumnValue>();
foreach (KeyValuePair<int, ProcessDataLine> dataLine in processTable)
{
bc.Add(new ColumnValue((int)dataLine.Key ,dataLine.Value.Kbuoyancy));
bi.Add(new ColumnValue((int)dataLine.Key ,dataLine.Value.Qctv));
bj.Add(new ColumnValue((int)dataLine.Key ,dataLine.Value.VolRI));
bm.Add(new ColumnValue((int)dataLine.Key ,dataLine.Value.ERelRef));
}
table.Add(CommonExcell.ColumnToNumber("BC"),bc);
table.Add(CommonExcell.ColumnToNumber("BI"),bi);
table.Add(CommonExcell.ColumnToNumber("BJ"),bj);
table.Add(CommonExcell.ColumnToNumber("BM"),bm);
return table;
}
public Dictionary<int, IList<ColumnValue>> ModifyKbuoyancy(IList<ColumnValue> corectedKbuoancy)
{
//Columns - 'BC'
Dictionary<int,IList<ColumnValue>> kbuoyancyTable = GetKBuoyancy();
if (kbuoyancyTable.ContainsKey(CommonExcell.ColumnToNumber("BC")) &&
kbuoyancyTable.ContainsKey(CommonExcell.ColumnToNumber("BI")) &&
kbuoyancyTable.ContainsKey(CommonExcell.ColumnToNumber("BJ")) &&
kbuoyancyTable.ContainsKey(CommonExcell.ColumnToNumber("BM")))
{
IList<ColumnValue> listBC = kbuoyancyTable[CommonExcell.ColumnToNumber("BC")];
IList<ColumnValue> listBI = kbuoyancyTable[CommonExcell.ColumnToNumber("BI")];
IList<ColumnValue> listBJ = kbuoyancyTable[CommonExcell.ColumnToNumber("BJ")];
IList<ColumnValue> listBM = kbuoyancyTable[CommonExcell.ColumnToNumber("BM")];
if (corectedKbuoancy.Count != listBC.Count)
{
throw new Exception("Incompatible count in table kbuoyancy!");
}
for (int row = 0; row < listBC.Count; row++)
{
double correctedKbuoyancyValue = corectedKbuoancy[row].Value;
listBC[row].Value = correctedKbuoyancyValue;
//BI=+BI4/BC4*BC13
listBI[row].Value = listBI[row].Value / correctedKbuoyancyValue * listBJ[row].Value;
//BM==+(BJ13-BI13)/BI13*100
listBM[row].Value = (listBJ[row].Value - listBI[row].Value) / listBI[row].Value * 100;
}
return kbuoyancyTable;
}
return null;
}
}
public class CalculationTable
{
private BatchProcessTable batchProcessTable;
private Dictionary<int, IList<ColumnValue>> table;
private Dictionary<string, double> averages;
public BatchProcessTable BatchProcessTable
{
get => batchProcessTable;
set => batchProcessTable = value;
}
public Dictionary<int, IList<ColumnValue>> Table
{
get => table;
set => table = value;
}
public Dictionary<string, double> Averages
{
get => averages;
set => averages = value;
}
public CalculationTable()
{
batchProcessTable = new BatchProcessTable();
table = new Dictionary<int, IList<ColumnValue>>();
averages = new Dictionary<string, double>();
}
////////
///
public IList<ColumnValue> GetColumn(string column)
{
int iColumnName = CommonExcell.ColumnToNumber(column);
if (table.ContainsKey(iColumnName))
{
return table[iColumnName];
}
else
{
throw new Exception($"Column {column} missing in table!");
}
}
double Average(string columnName, bool forceCalculation = false)
{
int iColumnName = CommonExcell.ColumnToNumber(columnName);
if (!forceCalculation && averages.ContainsKey(columnName))
{
return averages[columnName];
}
if (!table.ContainsKey(iColumnName))
{
double average = Average(table[iColumnName]);
averages.Add(columnName, average);
return average;
}
else
{
throw new Exception($"Column {columnName} missing in table!");
}
return 0;
}
public static double Average(IList<ColumnValue> values)
{
int i = 0;
double sum = 0;
foreach (ColumnValue value in values)
{
sum += value.Value;
i++;
}
return sum / i;
}
static double SumOfSquares(IList<ColumnValue> values, double mean)
{
double sumOfSquares = 0;
foreach (ColumnValue columnValue in values)
{
sumOfSquares += System.Math.Pow(columnValue.Value - mean, 2);
}
return sumOfSquares;
}
/// <summary>
/// Calculates the sample standard deviation for a list of ColumnValue objects.
/// </summary>
/// <param name="values">An IList of ColumnValue objects.</param>
/// <returns>The sample standard deviation. Returns 0 if there are fewer than 2 values.</returns>
public static double StandardDeviation(IList<ColumnValue> values)
{
if (values == null || values.Count < 2)
return 0.0;
// Compute the average of the values.
double mean = CalculationTable.Average(values);
// Calculate the sum of squared differences from the mean.
double sumOfSquares = CalculationTable.SumOfSquares(values, mean);
// For sample standard deviation, divide by (n - 1)
return System.Math.Sqrt(sumOfSquares / (values.Count - 1));
}
}
}
+22
View File
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
namespace Results.Uncertainty.Calculation
{
public static class Math
{
public static double Average(IList<Double> values)
{
int i = 0;
double sum = 0;
foreach (double value in values)
{
sum += value;
i++;
}
return sum / i;
}
}
}
+310
View File
@@ -0,0 +1,310 @@
using System;
using System.Collections.Generic;
using ClosedXML.Excel;
using Common;
using Config.Entities;
using log4net;
using NHibernate;
using Results.Resources;
namespace Results.Uncertainty
{
public class CommonExcell
{
const string formatD7 = "0.0000000";
const string formatD6 = "0.000000";
const string formatD4 = "0.0000";
const string formatD3 = "0.000";
const string formatD1 = "0.0";
const string formatInt = "0";
const string formatStr = "@";
private static Dictionary<int, int> bloks = null;
static readonly ILog log = LogManager.GetLogger(typeof(CommonExcell));
private static IList<Component> cmpntEntities;
public static Dictionary<int, int> GetBolocs() {
if (bloks == null)
{
bloks = new Dictionary<int, int>();
bloks.Add(0, 4);
bloks.Add(1, 24);
bloks.Add(2, 44);
bloks.Add(3, 64);
bloks.Add(4, 84);
bloks.Add(5, 104);
bloks.Add(6, 124);
bloks.Add(7, 144);
}
return bloks;
}
/// <summary>
/// Inserts a line of process data into a specified row of the Excel document.
/// </summary>
/// <param name="_rigUncertainty">An instance of the <see cref="RigUncertainty"/> class representing the rig uncertainty and its associated data.</param>
/// <param name="iRowI">The row index in the Excel worksheet where the process data will be inserted.</param>
/// <param name="processDataLine">An instance of the <see cref="ProcessDataLine"/> class containing the process data to be added to the row.</param>
public static void InsertValueLineProcessData(RigUncertainty _rigUncertainty, int iRowI, ProcessDataLine processDataLine)
{
if (!_rigUncertainty.IsOpenedDocument)
{
throw new Exception("No Opened document!");
}
IXLWorksheet worksheet = _rigUncertainty.GetWorksheet(DocumentSheets.RADATA);
//Date time
string column = "A";
worksheet.Cell($"{column}{iRowI}").Value = processDataLine.DateTime;
worksheet.Cell($"{column}{iRowI}").Style.DateFormat.Format = "M/d/yyyy h:mm";
//deffined values
CellData(worksheet, "B", iRowI, processDataLine.Batch, formatInt); //Batch - B
CellData(worksheet, "C", iRowI, processDataLine.TestName, formatStr); //Test Name - C
CellData(worksheet, "D", iRowI, processDataLine.Reports, formatInt); //Reports
CellData(worksheet, "E", iRowI, processDataLine.RepCyc, formatInt); //Rep cyc
CellData(worksheet, "F", iRowI, processDataLine.TestMeth, formatStr); //Test Meth.
CellData(worksheet, "G", iRowI, processDataLine.TargetVOL, formatInt); //Target VOL.
CellData(worksheet, "H", iRowI, processDataLine.TargetQMin, formatD4); //Target Q -
CellData(worksheet, "I", iRowI, processDataLine.TargetQPlus, formatD4); //Target Q +
CellData(worksheet, "J", iRowI, processDataLine.ErrLimitMin, formatInt); //Err. LIMIT -
CellData(worksheet, "K", iRowI, processDataLine.ErrLimitPlus, formatInt); //Err. LIMIT +
CellData(worksheet, "L", iRowI, processDataLine.TargetTempFrom, formatInt); //Target temp from - L
CellData(worksheet, "M", iRowI, processDataLine.TargetTempTo, formatInt); //Target temp to - M
CellData(worksheet, "N", iRowI, processDataLine.TargetPressFrom, formatInt); //Target press from - N
CellData(worksheet, "O", iRowI, processDataLine.TargetPressTo, formatInt); //Target press to - O
CellData(worksheet, "P", iRowI, processDataLine.MIDNumberName, formatStr);
CellData(worksheet, "Q", iRowI, processDataLine.MIDNumberValue, formatD4); //MID number - PQ
CellData(worksheet, "R", iRowI, processDataLine.COR, formatStr); //COR - R
CellData(worksheet, "S", iRowI, processDataLine.TempAmbM, formatD1); //Temp.Amb M - S
CellData(worksheet, "T", iRowI, processDataLine.PressAmbM, formatInt); //Press.Amb M - T
CellData(worksheet, "U", iRowI, processDataLine.HumidAmbM, formatD1); //Humid.Amb M - U
CellData(worksheet, "V", iRowI, processDataLine.PressUpME, formatInt); //Press. UP ME - V
CellData(worksheet, "W", iRowI, processDataLine.PressDwME, formatInt); //Press. DW ME - W
CellData(worksheet, "X", iRowI, processDataLine.PressDeME, formatInt); //Press. DE ME - X
CellData(worksheet, "Y", iRowI, processDataLine.PressUpST, formatInt); //Press. UP ST - Y
CellData(worksheet, "Z", iRowI, processDataLine.PressDwST, formatInt); //Press. DW ST - Z
CellData(worksheet, "AA", iRowI, processDataLine.PressDES, formatInt); //Press. DES - AA
CellData(worksheet, "AB", iRowI, processDataLine.PressUpEN, formatInt); //Press UP EN - AB
CellData(worksheet, "AC", iRowI, processDataLine.PressDwEN, formatInt); //Press DW EN
CellData(worksheet, "AD", iRowI, processDataLine.PressDEE, formatInt); //Press. DEE
CellData(worksheet, "AE", iRowI, processDataLine.TempUpME, formatD4); //Temp. UP ME
CellData(worksheet, "AF", iRowI, processDataLine.TempDwME, formatD4); //Temp. DW ME
CellData(worksheet, "AG", iRowI, processDataLine.TempDiME, formatD4); //Temp. DI ME
CellData(worksheet, "AH", iRowI, processDataLine.TempLoME, formatD4); //Temp. LO ME
CellData(worksheet, "AI", iRowI, processDataLine.TempHiME, formatD4); //Temp. HI ME
CellData(worksheet, "AJ", iRowI, processDataLine.TempUpST, formatD4); //Temp. UP ST
CellData(worksheet, "AK", iRowI, processDataLine.TempDwST, formatD4); //Temp. DW ST
CellData(worksheet, "AL", iRowI, processDataLine.TempDiST, formatD4); //Temp. DI ST
CellData(worksheet, "AM", iRowI, processDataLine.TempLoST, formatD4); //Temp. LO ST
CellData(worksheet, "AN", iRowI, processDataLine.TempHiST, formatD4); //Temp. HI ST
CellData(worksheet, "AO", iRowI, processDataLine.TempUpEN, formatD4); //Temp. UP EN
CellData(worksheet, "AP", iRowI, processDataLine.TempDwEN, formatD4); //Temp. DW EN
CellData(worksheet, "AQ", iRowI, processDataLine.TempDiEN, formatD4); //Temp. DI EN
CellData(worksheet, "AR", iRowI, processDataLine.TempLoEN, formatD4); //Temp. LO EN
CellData(worksheet, "AS", iRowI, processDataLine.TempHiEN, formatD4); //Temp. HI EN
//Mass vakues
CellData(worksheet, "AT", iRowI, processDataLine.MassStRaw, formatD3); //Mass ST raw()
CellData(worksheet, "AU", iRowI, processDataLine.MassSt, formatD3); //Mass ST ()
CellData(worksheet, "AV", iRowI, processDataLine.MassEnRaw, formatD3); //Mass EN raw()
CellData(worksheet, "AW", iRowI, processDataLine.MassEn, formatD3); //Mass EN ()
CellData(worksheet, "AX", iRowI, processDataLine.Mass, formatD3); //Mass
//calculated values
CellData(worksheet, "AY", iRowI, processDataLine.RoWa, formatD7); //Ro Wa
CellData(worksheet, "AZ", iRowI, processDataLine.TempLnME, formatD7); //Temp. LN ME
CellData(worksheet, "BA", iRowI, processDataLine.RoWat, formatD7); //Ro Wat
CellData(worksheet, "BB", iRowI, processDataLine.RoAir, formatD7); // Ro AIR
CellData(worksheet, "BC", iRowI, processDataLine.Kbuoyancy, formatD7); // Kbuoyancy
CellData(worksheet, "BD", iRowI, processDataLine.DensityOfSample, formatInt); //Density of sample
CellData(worksheet, "BE", iRowI, processDataLine.TTempRO, formatInt); //TTemp. RO()
CellData(worksheet, "BF", iRowI, processDataLine.QMax, formatD7); //Q max ()
CellData(worksheet, "BG", iRowI, processDataLine.QMin, formatD7); //Q min ()
CellData(worksheet, "BH", iRowI, processDataLine.QMean, formatD7); //Q mean
CellData(worksheet, "BI", iRowI, processDataLine.Qctv, formatD7); //Qctv
CellData(worksheet, "BJ", iRowI, processDataLine.VolRI, formatD7); //Vol. RI
CellData(worksheet, "BK", iRowI, processDataLine.DivCorrection, formatD3); //Div correction
CellData(worksheet, "BL", iRowI, processDataLine.T, formatD3); //T(s)()
CellData(worksheet, "BM", iRowI, processDataLine.ERelRef, formatD7); //E rel.ref. ()
//CellData(worksheet, "BN", iRowI, , formatD7);
CellData(worksheet, "BO", iRowI, processDataLine.KMind, formatInt); //K MID ()
//CellData(worksheet, "BP", iRowI, , formatInt);//Const.MAS
//Additional values
CellData(worksheet, "BQ", iRowI, processDataLine.DiverterStartTime, formatInt); //Diverter start time
CellData(worksheet, "BR", iRowI, processDataLine.DiverterEndTime, formatInt); //Diverter end time
CellData(worksheet, "BS", iRowI, processDataLine.DiverterStartValeveOpenTime, formatInt); // BS [ms] Start valve open time
CellData(worksheet, "BT", iRowI, processDataLine.DiverterStartValeveCloseTime, formatInt); // BT [ms] Start valve close time
CellData(worksheet, "BU", iRowI, processDataLine.TempUpMax, formatD7); //Temp. UP max
CellData(worksheet, "BV", iRowI, processDataLine.TempDwMax, formatD7); // Temp DW max
CellData(worksheet, "BW", iRowI, processDataLine.TempUpMin, formatD7); //Temp UP min
CellData(worksheet, "BX", iRowI, processDataLine.TempDwMin, formatD7); //Temp DW min
CellData(worksheet, "BY", iRowI, processDataLine.TempT10, formatD7); //10 - T1,2
CellData(worksheet, "BZ", iRowI, processDataLine.TempAmbEn, formatD1); //Temp Amb En
CellData(worksheet, "CA", iRowI, processDataLine.PressAmbEn, formatInt); //Press Amb En
CellData(worksheet, "CB", iRowI, processDataLine.HumAmbEn, formatD1); //Hum Amb En
//checking
CellData(worksheet, "CC", iRowI, processDataLine.RefPulses, formatInt); //Ref pulses()
CellData(worksheet, "CD", iRowI, processDataLine.DiverterTestTimeCorrection, formatInt); // CD [ms] Diverter test time correction
int distance = CommonExcell.GetColumnDistance("CE", "CZ");
string startBlockColumn = "CE";
foreach (ProcessDataMeterLine dataMeter in processDataLine.processDataMeterList){
MeterCellData(worksheet, startBlockColumn, iRowI, dataMeter, distance);
startBlockColumn = CommonExcell.GetExcelColumnByDistance(startBlockColumn, distance);
}
}
/// <summary>
/// Populates a range of cells in an Excel worksheet with meter process data starting from a specified column and row.
/// </summary>
/// <param name="worksheet">The Excel worksheet where data will be inserted.</param>
/// <param name="column">The starting column in the worksheet for inserting the meter process data.</param>
/// <param name="iRowI">The row index in the worksheet where the data will be inserted.</param>
/// <param name="data">An instance of the <see cref="ProcessDataMeterLine"/> class containing the meter process data to insert.</param>
/// <param name="distance">An optional parameter specifying the distance for additional columns to leave empty after data insertion. Defaults to 0.</param>
/// <returns>The next available column string after the last column used during data insertion.</returns>
private static string MeterCellData(IXLWorksheet worksheet, string column, int iRowI, ProcessDataMeterLine data, int distance = 0)
{
int iIndex = 0;
CellData(worksheet, column, iRowI, data.val[iIndex] , formatStr);//Position - Ser.No. - CE - 0
string nextColumn = NextColumn(column); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt);//Vol.Mt.st - CF
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt);//Vol.Mt.en - CG
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatD7);//Vol.Mt. - CH
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex], formatD7);//Vol.rm - CI
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatD6); // E rel. - CJ
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt); // U - CK
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt); //Pulses() -
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt); //Ref pulses_ni()
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatD4); //T(s)()_ni
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatStr);//evaluation
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatD4);//Pulses/l - CP
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt);//imp/l
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt);//div
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt);//Vend
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, data.val[++iIndex] , formatInt);//T end - 15
if (distance > 0)
{
string lastColumn = CommonExcell.GetExcelColumnByDistance(column, distance);
int columnDistance = CommonExcell.GetColumnDistance(nextColumn, lastColumn);
for (int i = 1; i < columnDistance; i++)
{
if ((iIndex + 1) < data.val.Length)
{
nextColumn = NextColumn(nextColumn);
CellData(worksheet, nextColumn, iRowI, data.val[++iIndex], formatInt);
}
else
{
nextColumn = NextColumn(nextColumn); CellData(worksheet,nextColumn, iRowI, 0 , formatInt);
}
}
}
return nextColumn;
}
public static void CellData(IXLWorksheet worksheet, string column, int iRowI, XLCellValue value, string format = null)
{
worksheet.Cell($"{column}{iRowI}").Value = value;
if (format != null)
{
worksheet.Cell($"{column}{iRowI}").Style.NumberFormat.Format = format; // Ensure integer format
}
}
public static string NextColumn(string column)
{
if (string.IsNullOrEmpty(column))
return "A";
char[] chars = column.ToUpper().ToCharArray();
int i = chars.Length - 1;
while (i >= 0)
{
if (chars[i] != 'Z')
{
chars[i]++;
break;
}
else
{
chars[i] = 'A';
i--;
}
}
if (i < 0)
return "A" + new string(chars);
return new string(chars);
}
public static int GetColumnDistance(string col1, string col2)
{
return ColumnToNumber(col2) - ColumnToNumber(col1);
}
public static int ColumnToNumber(string col)
{
int number = 0;
foreach (char c in col.ToUpper())
{
number = number * 26 + (c - 'A' + 1);
}
return number;
}
public static string GetExcelColumnByDistance(string startColumn, int distance)
{
int startNumber = ColumnToNumber(startColumn);
int targetNumber = startNumber + distance;
return NumberToColumn(targetNumber);
}
private static string NumberToColumn(int number)
{
string column = string.Empty;
while (number > 0)
{
number--;
column = (char)('A' + (number % 26)) + column;
number /= 26;
}
return column;
}
public static bool AreClose(double valA, double valB, double tolerance = 0.0001)
{
if ((valA + tolerance) > valB && (valA - tolerance) < valB)
{
return true;
}
return false;
}
}
}
+43
View File
@@ -0,0 +1,43 @@
using ClosedXML.Excel;
namespace Results.Uncertainty.CommonTable
{
public class Cell
{
public int IRow { get; }
public int IColumn { get; }
public XLCellValue Value { get; set; }
// The names (if any) of the row/column
public string ColumnName { get; }
public string RowName { get; }
/// <summary>
/// Excelstyle address, e.g. “B3”.
/// </summary>
public string Address => $"{ToLetter(IColumn + 1)}{IRow + 1}";
public Cell(int col, int row, XLCellValue value,
string colName = null, string rowName = null)
{
IColumn = col;
IRow = row;
Value = value;
ColumnName = colName;
RowName = rowName;
}
// Convert 1-based column number into letters
private static string ToLetter(int col)
{
var s = "";
while (col > 0)
{
int m = (col - 1) % 26;
s = (char)('A' + m) + s;
col = (col - m - 1) / 26;
}
return s;
}
}
}
+232
View File
@@ -0,0 +1,232 @@
using System.Collections.Generic;
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using ClosedXML.Excel;
namespace Results.Uncertainty.CommonTable
{
public class Table
{
private int iOffsetRows = 0;
private int iOffsetColumns = 0;
public int IOffsetRows
{
get => iOffsetRows;
set => iOffsetRows = value;
}
public int IOffsetColumns
{
get => iOffsetColumns;
set => iOffsetColumns = value;
}
// The grid of cells
public IList<IList<Cell>> Cells { get; private set; }
= new List<IList<Cell>>();
// Optional names for columns and rows
public IList<string> ColumnNames { get; private set; }
= new List<string>();
public IList<string> RowNames { get; private set; }
= new List<string>();
public Table() { }
public void AddColumnExcel(string nameStart, string nameEnd)
{
int distance = CommonExcell.GetColumnDistance(nameStart, nameEnd);
int iStart = CommonExcell.ColumnToNumber(nameStart);
AddColumn(nameStart);
for (int i = 0; i < distance; i++)
{
AddColumn(CommonExcell.GetExcelColumnByDistance(nameStart, i+1));
}
}
public void GenerateTable_RowsColumns_Excel(string nameStart, string nameEnd, int iRowsCount)
{
AddColumnExcel(nameStart, nameEnd);
for (int i = 0; i < iRowsCount; i++)
{
AddRow(i.ToString());
}
}
/// <summary>
/// Adds a new column (with optional name) and returns its index.
/// </summary>
public int AddColumn(string name = null)
{
int colIndex = ColumnNames.Count;
ColumnNames.Add(name);
// Grow every existing row by one
for (int r = 0; r < Cells.Count; r++)
{
Cells[r].Add(new Cell(colIndex, r, new XLCellValue(), name, RowNames[r]));
}
return colIndex;
}
/// <summary>
/// Adds a new row (with optional name) and returns its index.
/// </summary>
public int AddRow(string name = null)
{
int rowIndex = Cells.Count;
RowNames.Add(name);
var newRow = new List<Cell>(ColumnNames.Count);
// Initialize with empty cells
for (int c = 0; c < ColumnNames.Count; c++)
{
newRow.Add(new Cell(c, rowIndex, new XLCellValue(), ColumnNames[c], name));
}
Cells.Add(newRow);
return rowIndex;
}
/// <summary>
/// Ensures the given [row,col] exists, creating rows/columns as needed.
/// </summary>
private void EnsurePosition(int rowIndex, int colIndex)
{
while (Cells.Count <= rowIndex)
AddRow();
var row = Cells[rowIndex];
while (row.Count <= colIndex)
AddColumn();
}
/// <summary>
/// Sets the value of the cell at [rowIndex, colIndex].
/// </summary>
public void AddCell(int rowIndex, int colIndex, XLCellValue value)
{
EnsurePosition(rowIndex, colIndex);
Cells[rowIndex][colIndex].Value = value;
}
/// <summary>
/// Sets the value of the cell at [rowIndex, columnName].
/// If the columnName doesnt exist yet, its created.
/// </summary>
public void AddCell(int rowIndex, string columnName, XLCellValue value)
{
int colIndex = ColumnNames.IndexOf(columnName);
if (colIndex < 0)
colIndex = AddColumn(columnName);
AddCell(rowIndex, colIndex, value);
}
/// <summary>
/// Retrieves a cell by numeric coordinates.
/// </summary>
public Cell GetCell(int rowIndex, int colIndex)
=> Cells[rowIndex][colIndex];
/// <summary>
/// Retrieves a cell by rowIndex and columnName.
/// </summary>
public Cell GetCell(int rowIndex, string columnName)
{
int colIndex = ColumnNames.IndexOf(columnName);
if (colIndex < 0)
throw new ArgumentException($"Column '{columnName}' not found.");
return GetCell(rowIndex, colIndex);
}
/// <summary>
/// Writes the entire table into the given worksheet,
/// optionally including the header row of column names.
/// </summary>
public void ToWorksheet(IXLWorksheet ws, bool includeHeaders = true)
{
int startRow = 1;
if (includeHeaders)
{
for (int c = 0; c < ColumnNames.Count; c++)
ws.Cell(1, c + 1).Value = ColumnNames[c] ?? string.Empty;
startRow = 2;
}
for (int r = 0; r < Cells.Count; r++)
{
for (int c = 0; c < Cells[r].Count; c++)
{
ws.Cell(r + startRow, c + 1).Value = Cells[r][c].Value;
}
}
}
/// <summary>
/// Writes the entire table into the given worksheet,
/// optionally including the header row of column names.
/// </summary>
public void ToWorksheetWithOffset(IXLWorksheet ws, int rowsOffset = 1, int columnsOffset = 0, bool includeHeaders = true)
{
int startRow = rowsOffset;
if (includeHeaders)
{
for (int c = 0; c < ColumnNames.Count; c++)
ws.Cell(1, c + 1).Value = ColumnNames[c] ?? string.Empty;
startRow = 2;
}
for (int r = 0; r < Cells.Count; r++)
{
for (int c = 0; c < Cells[r].Count; c++)
{
if(!(Cells[r][c].Value.IsBlank || Cells[r][c].Value.Type == XLDataType.Blank))
{
ws.Cell(r + startRow, c + 1 + columnsOffset).Value = Cells[r][c].Value;
}
}
}
}
/// <summary>
/// Returns all cells in the given row (by zerobased index).
/// </summary>
public IList<Cell> GetRow(int rowIndex)
{
if (rowIndex < 0 || rowIndex >= Cells.Count)
throw new IndexOutOfRangeException($"Row {rowIndex} does not exist.");
return Cells[rowIndex];
}
/// <summary>
/// Returns all cells in the given column (by zerobased index).
/// </summary>
public IList<Cell> GetColumn(int colIndex)
{
if (colIndex < 0 || colIndex >= ColumnNames.Count)
throw new IndexOutOfRangeException($"Column {colIndex} does not exist.");
var list = new List<Cell>();
for (int r = 0; r < Cells.Count; r++)
{
// skip if that row hasnt grown that far yet
if (Cells[r].Count > colIndex)
list.Add(Cells[r][colIndex]);
}
return list;
}
}
}
+133
View File
@@ -0,0 +1,133 @@
///
/// Copyright (c) 2023 Sensus Slovensko a.s.
///
using System.Collections.Generic;
using Common;
namespace Results.Uncertainty
{
/// <summary>
/// Action of a DataEntry field
/// </summary>
public enum Ac
{
[Description("Clear")] Clear, /// Clear when the form is open, save on OK
[Description("Last from history")] HistoryLast,
[Description("Load")] Load, /// Load from water meters when the form is open, save on OK
[Description("Load (readonly)")] LoadReadOnly, /// Load from water meters when the form is open, prevent changes, do not save
[Description("Set")] Set, /// Set to 'yes' when the form is open
Count,
}
/// <summary>
/// Content of a DataEntry field
/// </summary>
public enum Ct
{
[Description("None")] None,
[Description("Serial nr.")] SerialNr,
[Description("Serial nr. aux")] SerialNrAux,
[Description("Radio address")] RadioAddress,
[Description("Year of calibration")] YearOfCalibration,
[Description("Start state")] StartState,
[Description("Start state aux")] StartStateAux,
[Description("End state")] EndState,
[Description("End state aux")] EndStateAux,
[Description("Archive path")] ArchivePath,
[Description("WM Order")] WmOrder,
[Description("Batch order")] BatchOrder,
[Description("Batch and WM order")] BatchAndWmOrder,
[Description("WM Remark")] WmRemark,
[Description("Batch remark")] BatchRemark,
[Description("Batch and WM remark")] BatchAndWmRemark,
[Description("Print label")] PrintLabel,
#if ORACLE_DB
[Description("Prefix")] Prefix,
[Description("Suffix")] Suffix,
#endif
Count
}
/// <summary>
/// Function of the multi purpose button
/// </summary>
public enum MultiPurposeBtnFunction
{
None,
AutoSN,
PrintLabelsOnOff,
}
///
/// Identifies image instance
///
public enum Tst
{
Start,
End,
Both,
Collect,
}
///
/// Image rotation
///
public enum Rotation
{
R0,
R90,
R180,
R270,
Count
}
public class DEItem
{
public readonly Ct Content;
public readonly string Caption;
public readonly Ac Action;
public readonly int Width;
public DEItem(Ct content, string caption, Ac action, int width)
{
Content = content;
Caption = caption;
Action = action;
Width = width;
}
static IList<DEItem> items = new List<DEItem>();
///
public static void ClearItems() { items.Clear(); }
public static void AddItem(DEItem item) { items.Add(item); }
public static void AddItem(Ct content, string caption, Ac action, int width)
{
items.Add(new DEItem(content, caption, action, width));
}
public static IList<DEItem> GetItems() { return items; }
static IList<DEItem> columns = new List<DEItem>();
///
public static void ClearColumns() { columns.Clear(); }
public static void AddColumn(DEItem column) { columns.Add(column); }
public static void AddColumn(Ct content, string caption, Ac action, int width)
{
columns.Add(new DEItem(content, caption, action, width));
}
public static IList<DEItem> GetColumns() { return columns; }
static IList<DEItem> summaryColumns = new List<DEItem>();
///
public static void ClearSummaryColumns() { summaryColumns.Clear(); }
public static void AddSummaryColumn(DEItem column) { summaryColumns.Add(column); }
public static void AddSummaryColumn(Ct content, string caption, Ac action, int width)
{
summaryColumns.Add(new DEItem(content, caption, action, width));
}
public static IList<DEItem> GetSummaryColumns() { return summaryColumns; }
}
}
+122
View File
@@ -0,0 +1,122 @@
///
/// Copyright (c) 2018-2023 Sensus Slovensko a.s.
///
using System.Windows.Forms;
using Results.Entities;
namespace Results.Uncertainty
{
public class Strings
{
public static string yes = "yes";
public static string no = "no";
}
public class DEUtils
{
public static string GetContent(Ct content, WaterMeter wm)
{
if (wm == null) return string.Empty;
switch (content)
{
default:
case Ct.None: return string.Empty;
case Ct.SerialNr: return (!wm.Disabled && wm.SerialNr != null) ? wm.SerialNr : string.Empty;
case Ct.SerialNrAux: return (!wm.Disabled && wm.SerialNrAux != null) ? wm.SerialNrAux : string.Empty;
case Ct.RadioAddress: return (!wm.Disabled && wm.RadioAddress != null) ? wm.RadioAddress : string.Empty;
case Ct.YearOfCalibration: return (!wm.Disabled) ? wm.YearOfProduction.ToString() : string.Empty;
case Ct.StartState: return (!wm.Disabled && wm.GetStartState() != null) ? wm.GetStartState() : string.Empty;
case Ct.StartStateAux: return string.Empty;
case Ct.EndState: return (!wm.Disabled && wm.EndState != null) ? wm.EndState : string.Empty;
case Ct.EndStateAux: return (!wm.Disabled && wm.GetEndStateAux() != null) ? wm.GetEndStateAux() : string.Empty;
case Ct.ArchivePath: return (!wm.Disabled && wm.ArchivePath != null) ? wm.ArchivePath : string.Empty;
case Ct.WmOrder: return (!wm.Disabled && wm.PurchaseOrder != null) ? wm.PurchaseOrder : string.Empty;
case Ct.BatchOrder: return (wm.Batch != null && wm.Batch.PurchaseOrder != null) ? wm.Batch.PurchaseOrder : string.Empty;
case Ct.BatchAndWmOrder: return (wm.Batch != null && wm.Batch.PurchaseOrder != null) ? wm.Batch.PurchaseOrder : string.Empty;
case Ct.WmRemark: return (!wm.Disabled && wm.Remark != null) ? wm.Remark : string.Empty;
case Ct.BatchRemark: return (wm.Batch != null && wm.Batch.Remark != null) ? wm.Batch.Remark : string.Empty;
case Ct.BatchAndWmRemark: return (wm.Batch != null && wm.Batch.Remark != null) ? wm.Batch.Remark : string.Empty;
case Ct.PrintLabel: return wm.PrintLabel ? Strings.yes : Strings.no;
#if ORACLE_DB
case Ct.Prefix: return (!wm.Disabled && wm.Prefix != null) ? wm.Prefix : string.Empty;
case Ct.Suffix: return (!wm.Disabled && wm.Suffix != null) ? wm.Suffix : string.Empty;
#endif
}
}
public static void PutContent(Ct content, WaterMeter wm, string value)
{
if (wm == null || wm.Disabled) return;
int year;
switch (content)
{
default:
case Ct.None: return;
case Ct.SerialNr: wm.SerialNr = value; return;
case Ct.SerialNrAux: wm.SerialNrAux = value; return;
case Ct.RadioAddress: wm.RadioAddress = value; return;
case Ct.YearOfCalibration: if (int.TryParse(value, out year)) wm.YearOfProduction = year; return;
case Ct.StartState: wm.SetStartState(value); return;
case Ct.StartStateAux: return;
case Ct.EndState: wm.EndState = value; return;
case Ct.EndStateAux: wm.SetEndStateAux(value); return;
case Ct.ArchivePath: wm.ArchivePath = value; return;
case Ct.WmOrder:
wm.PurchaseOrder = value;
return;
case Ct.BatchOrder:
case Ct.BatchAndWmOrder:
if (wm.Batch != null) wm.Batch.PurchaseOrder = value;
return;
case Ct.WmRemark:
wm.Remark = value;
return;
case Ct.BatchRemark:
case Ct.BatchAndWmRemark:
if (wm.Batch != null) wm.Batch.Remark = value;
return;
case Ct.PrintLabel:
wm.PrintLabel = (value == Strings.yes);
return;
#if ORACLE_DB
case Ct.Prefix: wm.Prefix = value; return;
case Ct.Suffix: wm.Suffix = value; return;
#endif
}
}
/// <summary>
/// Load Purchase order combo box items from the LocalSettings PurchaseOrderHistory array
/// </summary>
/// <param name="comboBox">Puchase order ComboBox</param>
public static void PrepareCombo(ComboBox comboBox, string[] history, bool emptyOnStart = false)
{
int historyLen = (history != null) ? history.Length : 0;
if (!emptyOnStart && (historyLen > 0))
{
comboBox.Text = history[0];
}
else
{
comboBox.Text = string.Empty;
}
for (int i = 0; i < historyLen; i++)
{
comboBox.Items.Add(history[i]);
}
}
}
}
+39
View File
@@ -0,0 +1,39 @@
using System;
using System.ComponentModel;
using System.Reflection;
namespace Results.Uncertainty
{
public enum DocumentSheets
{
[Description("RADATA")] RADATA,
[Description("DATA")] DATA,
[Description("IC")] IC,
[Description("CERTIFICATE")] CERTIFICATE,
[Description("L")] L,
[Description("REF METER CC")] REF_METER_CC,
[Description("Meter1ALL")] Meter1ALL,
[Description("UNCTABLE")] UNCTABLE,
[Description("CC")] CC,
[Description("CALINPUTS")] CALIMPUTS,
[Description("UNCTEST1")] UNCTEST1,
[Description("UNCTEST2")] UNCTEST2,
[Description("UNCTEST3")] UNCTEST3,
[Description("UNCTEST4")] UNCTEST4,
}
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute = field?.GetCustomAttribute<DescriptionAttribute>();
return attribute?.Description ?? value.ToString();
}
}
}
+325
View File
@@ -0,0 +1,325 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Common;
using Results.Entities;
namespace Results.Uncertainty
{
public class ProcessDataLine
{
public DateTime DateTime;
public int Batch; //"B" //Batch - B
public string TestName; //"C", "Q1 (1/5)", formatStr); //Test Name - C
public int Reports; //"D", 5, formatInt); //Reports
public int RepCyc; //"E", 1, formatInt); //Rep cyc
public string TestMeth; //"F", "FlyingStartMassCollection", formatStr); //Test Meth.
public int TargetVOL; //"G", 1, formatInt); //Target VOL.
public double TargetQMin; //"H", 0.005, formatD4); //Target Q -
public double TargetQPlus; //"I", 0.0055, formatD4); //Target Q +
public int ErrLimitMin; //"J", -2, formatInt); //Err. LIMIT -
public int ErrLimitPlus; //"K", -2, formatInt); //Err. LIMIT +
public int TargetTempFrom; //"L", 15, formatInt); //Target temp from - L
public int TargetTempTo; //"M", 25, formatInt); //Target temp to - M
public int TargetPressFrom; //"N", 0, formatInt); //Target press from - N
public int TargetPressTo; //"O", 16, formatInt); //Target press to - O
public string MIDNumberName; //"P", "I4", formatStr);
public double MIDNumberValue; //"Q", 998.1848d, formatD4); //MID number - PQ
public string COR; //"R", "WT2", formatStr); //COR - R
public double TempAmbM; //"S", 20.0, formatD1); //Temp.Amb M - S
public int PressAmbM; //"T", 1010, formatInt); //Press.Amb M - T
public double HumidAmbM; //"U", 52.7, formatD1); //Humid.Amb M - U
public int PressUpME; //"V", 272, formatInt); //Press. UP ME - V
public int PressDwME; //"W", 277, formatInt); //Press. DW ME - W
public int PressDeME; //"X", 0, formatInt); //Press. DE ME - X
public int PressUpST; //"Y", 272, formatInt); //Press. UP ST - Y
public int PressDwST; //"Z", 277, formatInt); //Press. DW ST - Z
public int PressDES; //"AA", 0, formatInt); //Press. DES - AA
public int PressUpEN; //"AB", 271, formatInt); //Press UP EN - AB
public int PressDwEN; //"AC", 276, formatInt); //Press DW EN
public int PressDEE; //"AD", 0, formatInt); //Press. DEE
public double TempUpME; //"AE", 17.27103, formatD4); //Temp. UP ME
public double TempDwME; //"AF", 17.84066, formatD4); //Temp. DW ME
public double TempDiME; //"AG", 18.25793, formatD4); //Temp. DI ME
public double TempLoME; //"AH", 0, formatD4); //Temp. LO ME
public double TempHiME; //"AI", 0, formatD4); //Temp. HI ME
public double TempUpST; //"AJ", 17.18227, formatD4); //Temp. UP ST
public double TempDwST; //"AK", 17.78378, formatD4); //Temp. DW ST
public double TempDiST; //"AL", 18.1312, formatD4); //Temp. DI ST
public double TempLoST; //"AM", 0, formatD4); //Temp. LO ST
public double TempHiST; //"AN", 0, formatD4); //Temp. HI ST
public double TempUpEN; //"AO", 17.3036, formatD4); //Temp. UP EN
public double TempDwEN; //"AP", 17.88913, formatD4); //Temp. DW EN
public double TempDiEN; //"AQ", 18.35797, formatD4); //Temp. DI EN
public double TempLoEN; //"AR", 0, formatD4); //Temp. LO EN
public double TempHiEN; //"AS", 0, formatD4); //Temp. HI EN
//Mass vakues
public double MassStRaw; // "AT", iRowI, 18.104, formatD3); //Mass ST raw()
public double MassSt; // "AU", iRowI, 18.104, formatD3); //Mass ST ()
public double MassEnRaw; // "AV", iRowI, 19.087, formatD3); //Mass EN raw()
public double MassEn; // "AW", iRowI, 19.087, formatD3); //Mass EN ()
public double Mass; // "AX", iRowI, 0.983, formatD3); //Mass
//calculated values
public double RoWa; // "AY", iRowI, 999.0094727, formatD7); //Ro Wa
public double TempLnME; // "AZ", iRowI, 17.55585, formatD7); //Temp. LN ME
public double RoWat; // "BA", iRowI, 999.2654076, formatD7); //Ro Wat
public double RoAir; // "BB", iRowI, 0, formatD7); // Ro AIR
public double Kbuoyancy; // "BC", iRowI, 1.00103, formatD7); // Kbuoyancy
public int DensityOfSample; // "BD", iRowI, 998, formatInt); //Density of sample
public int TTempRO; // "BE", iRowI, 23, formatInt); //TTemp. RO()
public double QMax; // "BF", iRowI, 0.00539688, formatD7); //Q max ()
public double QMin; // "BG", iRowI, 0.005288206, formatD7); //Q min ()
public double QMean; // "BH", iRowI, 0.005257821, formatD7); //Q mean
public double Qctv; ///< "BI", iRowI, 23, formatD7); //Qctv
public double VolRI; // "BJ", iRowI, 1.00006944444444, formatD7); //Vol. RI
public double DivCorrection; // "BK", iRowI, 0, formatD3); //Div correction
public double T; // "BL", iRowI, 674.242981, formatD3); //T(s)()
public double ERelRef; ///< "BM", iRowI, 1.557125667, formatD7); //E rel.ref. ()
//CellData(worksheet, "BN", iRowI, , formatD7);
public int KMind; ///< "BO", iRowI, 14400, formatInt); //K MID ()
//CellData(worksheet, "BP", iRowI, , formatInt);//Const.MAS
//Additional values
public int DiverterStartTime; //"BQ", iRowI, 84, formatInt); //Diverter start time
public int DiverterEndTime; //"BR", iRowI, 86, formatInt); //Diverter end time
public int DiverterStartValeveOpenTime;//"BS", iRowI, 0, formatInt); // /// BS [ms] Start valve open time
public int DiverterStartValeveCloseTime;//"BT", iRowI, 0, formatInt); // /// BT [ms] Start valve close time
public double TempUpMax; //"BU", iRowI, 17.40029, formatD7); //Temp. UP max
public double TempDwMax; //"BV", iRowI, 17.91978, formatD7); // Temp DW max
public double TempUpMin; //"BW", iRowI, 17.14815, formatD7); //Temp UP min
public double TempDwMin; //"BX", iRowI, 17.74739, formatD7); //Temp DW min
public double TempT10; //"BY", iRowI, 0, formatD7); //10 - T1,2
public double TempAmbEn; //"BZ", iRowI, 20.1, formatD1); //Temp Amb En
public int PressAmbEn; //"CA", iRowI, 1010, formatInt); //Press Amb En
public double HumAmbEn; //"CB", iRowI, 52.8, formatD1); //Hum Amb En
//checking
public int RefPulses; //"CC", iRowI, 14401, formatInt); //Ref pulses()
public int DiverterTestTimeCorrection; //CellData(worksheet, "CD", iRowI, , formatInt); /// CD [ms] Diverter test time correction
public IList<ProcessDataMeterLine> processDataMeterList = new List<ProcessDataMeterLine>();
public void InitDefault()
{
DateTime = DateTime.Now;
Batch = 914;
TestName = "Q1 (1/5)";
Reports = 5;
RepCyc = 1;
TestMeth = "FlyingStartMassCollection";
TargetVOL = 1;
TargetQMin = 0.005;
TargetQPlus = 0.0055;
ErrLimitMin = -2;
ErrLimitPlus = -2;
TargetTempFrom = 15;
TargetTempTo = 25;
TargetPressFrom = 0;
TargetPressTo = 16;
MIDNumberName = "I4";
MIDNumberValue = 998.1848d;
COR = "WT2";
TempAmbM = 20.0;
PressAmbM = 1010;
HumidAmbM = 52.7;
PressUpME = 272;
PressDwME = 277;
PressDeME = 0;
PressUpST = 272;
PressDwST = 277;
PressDES = 0;
PressUpEN = 271;
PressDwEN = 276;
PressDEE = 0;
TempUpME = 17.27103;
TempDwME = 17.84066;
TempDiME = 18.25793;
TempLoME = 0;
TempHiME = 0;
TempUpST = 17.18227;
TempDwST = 17.78378;
TempDiST = 18.1312;
TempLoST = 0;
TempHiST = 0;
TempUpEN = 17.3036;
TempDwEN = 17.88913;
TempDiEN = 18.35797;
TempLoEN = 0;
TempHiEN = 0;
MassStRaw = 18.104;
MassSt = 18.104;
MassEnRaw = 19.087;
MassEn = 19.087;
Mass = 0.983;
RoWa = 999.0094727;
TempLnME = 17.55585;
RoWat = 999.2654076;
RoAir = 0;
Kbuoyancy = 1.00103;
DensityOfSample = 998;
TTempRO = 23;
QMax = 0.00539688;
QMin = 0.005288206;
QMean = 0.005257821;
Qctv = 23;
VolRI = 1.00006944444444;
DivCorrection = 0;
T = 674.242981;
ERelRef = 1.557125667;
KMind = 14400;
DiverterStartTime = 84;
DiverterEndTime = 86;
TempUpMax = 17.40029;
TempDwMax = 17.91978;
TempUpMin = 17.14815;
TempDwMin = 17.74739;
TempT10 = 0;
TempAmbEn = 20.1;
PressAmbEn = 1010;
HumAmbEn = 52.8;
RefPulses = 14401;
DiverterTestTimeCorrection = 0;
for (int i = 0; i < 3; i++)
{
ProcessDataMeterLine meterLine = new ProcessDataMeterLine();
meterLine.InitDefault();
meterLine.val[0] = $"XXXX{i}";
processDataMeterList.Add(meterLine);
}
}
public void Init(Results.Entities.TestRslt tstRslt)
{
bool isPMaxTest = tstRslt.IsPMaxTest();
bool isStartStop = tstRslt.IsStartStop();
bool isDiverter = tstRslt.IsDiverter();
bool isVolumeMethod = tstRslt.IsVolumeMethod();
DateTime =tstRslt.StartTime; /// A
Batch = tstRslt.Batch.BatchNr; /// B
/// Test information, target values, etc.
TestName = tstRslt.Name(); /// C
Reports = tstRslt.Repeats(); /// D
RepCyc = tstRslt.RepetitionNr; /// E
TestMeth = tstRslt.Method(); /// F
TargetVOL = Convert.ToInt32(tstRslt.TargetVolume()); /// G
TargetQMin = tstRslt.Qfrom(); /// H
TargetQPlus = tstRslt.Qto(); /// I
ErrLimitMin = Convert.ToInt32(tstRslt.ErrLimLo() + tstRslt.ErrLimMargin()); /// J
ErrLimitPlus = Convert.ToInt32(tstRslt.ErrLimHi() - tstRslt.ErrLimMargin()); /// K
TargetTempFrom = Convert.ToInt32(Double.Parse(string.Format("{0:F1}", tstRslt.TempLimLo()))); /// L
TargetTempTo = Convert.ToInt32(Double.Parse(string.Format("{0:F1}", tstRslt.TempLimHi()))); /// M
TargetPressFrom = 0; /// N
TargetPressTo = 16; /// O
MIDNumberName = tstRslt.RefFlowmeter(); /// P
MIDNumberValue = Double.Parse(string.Format("{0:F4}", Formulas.DistilledWaterDensityFromTemp(tstRslt.AmbTempMean))); /// Q [kg/m3] hustota vody pri teplote okolia z priemernej teploty okolia bez korekcie na realnu hustotu vody
COR = ((tstRslt.Components != null) ? tstRslt.Components.Scale : string.Empty); /// R
/// Ambient
TempAmbM = Double.Parse(string.Format("{0:F1}", Units.ConvertTo(Unit.C, tstRslt.AmbTempStart))); /// S [°C]
PressAmbM = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", Units.ConvertTo(Unit.mbar, tstRslt.AmbPressStart)))); /// T [mbar]
HumidAmbM = Double.Parse(string.Format("{0:F1}", Units.ConvertTo(Unit.RPct, tstRslt.AmbHumiStart))); /// U [R%]
/// Pressure
PressUpME = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", Units.ConvertTo(Unit.kPa, tstRslt.PressUpMean)))); /// V [kPa]
PressDwME = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", Units.ConvertTo(Unit.kPa, tstRslt.PressDownMean)))); /// W [kPa]
PressDeME = Convert.ToInt32(Double.Parse(string.Format("{0:F1}", Units.ConvertTo(Unit.kPa, tstRslt.PressDeltaMean)))); /// X [kPa]
PressUpST = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", Units.ConvertTo(Unit.kPa, tstRslt.PressUpStart)))); /// Y [kPa]
PressDwST = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", Units.ConvertTo(Unit.kPa, tstRslt.PressDownStart)))); /// Z [kPa]
PressDES = Convert.ToInt32(Double.Parse(string.Format("{0:F1}", Units.ConvertTo(Unit.kPa, tstRslt.PressDeltaStart)))); /// AA [kPa]
PressUpEN = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", Units.ConvertTo(Unit.kPa, tstRslt.PressUpEnd)))); /// AB [kPa]
PressDwEN = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", Units.ConvertTo(Unit.kPa, tstRslt.PressDownEnd)))); /// AC [kPa]
PressDEE = Convert.ToInt32(Double.Parse(string.Format("{0:F1}", Units.ConvertTo(Unit.kPa, tstRslt.PressDeltaEnd)))); /// AD [kPa]
/// Temperature
TempUpME = (Units.ConvertTo(Unit.C, tstRslt.TempUpMean)); /// AE [°C]
TempDwME = (Units.ConvertTo(Unit.C, tstRslt.TempDownMean)); /// AF [°C]
TempDiME = (Units.ConvertTo(Unit.C, tstRslt.TempDivMean)); /// AG [°C]
TempLoME = (Units.ConvertTo(Unit.C, tstRslt.Custom1)); /// AH [°C] T hi mean
TempHiME = (Units.ConvertTo(Unit.C, tstRslt.Custom6)); /// AI [°C] T lo mean
TempUpST = (Units.ConvertTo(Unit.C, tstRslt.TempUpStart)); /// AJ [°C]
TempDwST = (Units.ConvertTo(Unit.C, tstRslt.TempDownStart)); /// AK [°C]
TempDiST = (Units.ConvertTo(Unit.C, tstRslt.TempDivStart)); /// AL [°C]
TempLoST = (Units.ConvertTo(Unit.C, tstRslt.Custom2)); /// AM [°C] T hi start
TempHiST = (Units.ConvertTo(Unit.C, tstRslt.Custom7)); /// AN [°C] T lo start
TempUpEN = (Units.ConvertTo(Unit.C, tstRslt.TempUpEnd)); /// AO [°C]
TempDwEN = (Units.ConvertTo(Unit.C, tstRslt.TempDownEnd)); /// AP [°C]
TempDiEN = (Units.ConvertTo(Unit.C, tstRslt.TempDivEnd)); /// AQ [°C]
TempLoEN = (Units.ConvertTo(Unit.C, tstRslt.Custom3)); /// AR [°C] T hi end
TempHiEN = (Units.ConvertTo(Unit.C, tstRslt.Custom8)); /// AS [°C] T lo end
/// Mass
MassStRaw = (tstRslt.MassStartRaw); /// AT [kg]
MassSt = (tstRslt.MassStart); /// AU [kg]
MassEnRaw = (tstRslt.MassEndRaw); /// AV [kg]
MassEn = (tstRslt.MassEnd); /// AW [kg]
Mass = (tstRslt.MassEnd - tstRslt.MassStart); /// AX [kg]
/// Density and buoyancy
RoWa = (tstRslt.DensityDiv); /// AY [kg/m3]
TempLnME = ((tstRslt.TempUpMean + tstRslt.TempDownMean) / 2); /// AZ [°C] Tline ... priemerna teplota v linii
RoWat = (tstRslt.DensityLine); /// BA [kg/m3]
RoAir = (tstRslt.MassOfEvapWater); /// BB [kg] mass of evaporated water
Kbuoyancy = (tstRslt.Batch.Buoyancy); /// BC Buoyancy: Sheet1 - X9
DensityOfSample = Convert.ToInt32(tstRslt.Batch.SampleDensity); /// BD
TTempRO = Convert.ToInt32(tstRslt.Batch.SampleTemp); /// BE
QMax = (tstRslt.FlowMax); /// BF pipe expansion: teraz vynechat
QMin = (tstRslt.FlowMin); /// BG [kg/h] Qm
QMean = (tstRslt.Flow); /// BH [l/h] Qv
Qctv = (tstRslt.VolumeCTV); /// BI [l] Vet .... komercne prava hodnota objemu - podla vahy
VolRI = (tstRslt.VolumeMaster); /// BJ [l] Velm ... objem podla etalonu (Prolonged: objem do vahy podla impulzov hradlovanych klapkou)
DivCorrection = (tstRslt.TestTimeCorrection); /// BK [s] test time correction (diverter correction)
/// (ori.) BK [l] Vmass .. objem podla druheho etalonu / prietokomeru pred tratou (teraz vynechavame)
T = (tstRslt.TestTime); /// BL [s]
ERelRef = (isVolumeMethod ? Formulas.ErrorFromVolumes(tstRslt.ConstMasterCorr, tstRslt.ConstMasterRaw) : tstRslt.ErrorMaster);
/// BM [%] Eelm .... chyba etalonu voci komercne pravej hodnote
KMind = Convert.ToInt32((tstRslt.ConstMasterRaw != 0) ? (1 / tstRslt.ConstMasterRaw) : 0); /// BO [pls/l] Const.MID .. konstanta etalonu
DiverterStartTime = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", isDiverter ? 1000.0F * tstRslt.DiverterStart : 0))); /// BQ [ms] Diverter start time
DiverterEndTime = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", isDiverter ? 1000.0F * tstRslt.DiverterEnd : 0))); /// BR [ms] Diverter end time
DiverterStartValeveOpenTime = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", isStartStop ? 1000.0F * tstRslt.DiverterStart : 0))); /// BS [ms] Start valve open time
DiverterStartValeveCloseTime = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", isStartStop ? 1000.0F * tstRslt.DiverterEnd : 0))); /// BT [ms] Start valve close time
TempUpMax = (tstRslt.TempUpMax); /// BU [°C]
TempDwMax = (tstRslt.TempDownMax); /// BV [°C]
TempUpMin = (tstRslt.TempUpMin); /// BW [°C]
TempDwMin = (tstRslt.TempDownMin); /// BX [°C]
TempT10 = (isPMaxTest ? tstRslt.TestTime : 0); /// BY [s] Duration of the pressure test
TempAmbEn = Double.Parse(string.Format("{0:F1}", Units.ConvertTo(Unit.C, tstRslt.AmbTempEnd))); /// BZ [°C]
PressAmbEn = Convert.ToInt32(Double.Parse(string.Format("{0:F0}", Units.ConvertTo(Unit.mbar, tstRslt.AmbPressEnd)))); /// CA [mbar]
HumAmbEn = Double.Parse(string.Format("{0:F1}", Units.ConvertTo(Unit.RPct, tstRslt.AmbHumiEnd))); /// CB [R%]
RefPulses = Convert.ToInt32(tstRslt.PulsesMaster); /// CC Celkovy pocet et. pulzov skusky (Prolonged : do vahy)
DiverterTestTimeCorrection = Convert.ToInt32(1000 * tstRslt.TestTimeCorrection); /// CD [ms] Diverter test time correction
BatchResults batchResults = BatchResults.FromBatch(tstRslt.Batch);
for (int i = 0; i < batchResults.WMPositionsCount; i++)
{
if (batchResults.Batch.WaterMeters != null &&
batchResults.Batch.WaterMeters.Count > i &&
batchResults.Batch.WaterMeters[i] != null &&
!batchResults.Batch.WaterMeters[i].Disabled)
{
ProcessDataMeterLine meterLine = new ProcessDataMeterLine(tstRslt, batchResults, i);
processDataMeterList.Add(meterLine);
}
}
}
}
}
+472
View File
@@ -0,0 +1,472 @@
using System;
using ClosedXML.Excel;
using Common;
using Results.Entities;
namespace Results.Uncertainty
{
public class ProcessDataMeterLine
{
public XLCellValue[] val = new XLCellValue[21];
/*public string SerNo; // "Diehl202415687905" , formatStr);//Position - Ser.No. - CE
public int VolMtSt; // 0 , formatInt);//Vol.Mt.st - CF
public int VolMtEn; // 0 , formatInt);//Vol.Mt.en - CG
public double VolMt; // 0.975333560911164 , formatD7);//Vol.Mt. - CH
public double VolRm; // 0.980633088, formatD7);//Vol.rm - CI
public double ERel; // -0.540418981321314 , formatD6); // E rel. - CJ
public int
IPerlCalibrationFactor; // , formatInt); // U - CK // CK iPerl calibration factor used during the test / ...
public int Pulses; // 154 , formatInt); //Pulses() - CL
public int RefPulsesNi; // 14341 , formatInt); //Ref pulses_ni() - CM
public double T; // 671.4207764 , formatD4); //T(s)()_ni -CN
public string Evaluation; // "OK" , formatStr);//evaluation - CO
public double PulsesL; // 157.8947 , formatD4);//Pulses/l - CP
public int ImpL; // 4 , formatInt);//imp/l - CQ
public int Div; // 0 , formatInt);//div - CR
public int VEnd; // 0 , formatInt);//Vend
public int TEnd; // 0 , formatInt);//T end
public string[] SmryItems = new string[5]; // - 0/// CU - 1/// CV - 2/// CW - 3/// CX - 4/// CY
*/
public ProcessDataMeterLine(TestRslt tstRslt, BatchResults batchResults, int wmNr0)
{
var wm = batchResults.Batch.WaterMeters[wmNr0];
var smryItems = DEItem.GetSummaryColumns();
{
if (!wm.Compound() && !wm.HeatMeter())
{
/// If this is a single meter
Results.Entities.MeterTestRslt mtrRslt =
batchResults.GetMeterTestRslt(tstRslt.Name(), wmNr0, CompoundMeterId.Single);
if (mtrRslt != null)
{
bool isCamera = (mtrRslt.RegReaderType == (int)RegisterReaderType.Camera);
val[0] = wm.SerialNr; /// CE WM Ser.No.
val[1] = mtrRslt
.VolumeStart; /// CF WM Vstart - pociatocny stav pri pevnom starte alebo zachyteny pri data streame
val[2] = mtrRslt
.VolumeEnd; /// CG WM Vend - konecny stav pri pevnom starte alebo zachyteny pri data streame
val[3] = mtrRslt.VolumeMeter; /// CH WM Vmer - objem namerany vodomerom
val[4] = mtrRslt.VolumeRef; /// CI WM Vref - objem namerany stanicou
val[5] = mtrRslt.Error; /// CJ WM Emt - chyba vodomerom nameraneho objemu
#if IPERL
val[6] = wm.CalibFactor; /// CK iPerl calibration factor used during the test / ...
#else
val[6] = 0; /// CK nechat prazdne
#endif
val[7] = Convert.ToInt32(mtrRslt
.PulsesMeter); /// CL WM Np met - pocet impulzov zo skusaneho meradla
val[8] = Convert.ToInt32(mtrRslt
.PulsesMaster); /// CM WM Np elm - pocet impulzov etalonu pocas merania pre prislusny vodomer
val[9] = mtrRslt.TestTime; /// CN WM Tmet - cas merania (obmedzany pri synchro skuske)
val[10] = mtrRslt.Passed
? "OK"
: "NOK"; /// CO WM Vysledok (t.j. ci je v hraniciach chyb) - OK/NOK
#if IPERL
val[11] =
mtrRslt.WaterMeter.Q2CorrRL; /// CP iPerl Q2 correction factor used during the test / AN value - hodnota z analogoveho prevodnika
#else
val[11] = mtrRslt.PulsesPerLiter; /// CP Pulses per liter
#endif
val[12] = Convert.ToInt32(isCamera
? mtrRslt.VolumeStart * mtrRslt.PulsesPerLiter /// CQ WM Phi_start (pri hodnotach z kamery)
: wm.WMPosition); /// CQ WMPosition (normalne)
val[13] = Convert.ToInt32(isCamera
? mtrRslt.VolumeEnd * mtrRslt.PulsesPerLiter /// CR WM Phi_end (pri hodnotach z kamery)
: 0); /// CR not used/spare (normalne)
//TODO - Time start is in table as VEnd ??? check it
val[14] = Convert.ToInt32(mtrRslt.TimestampStart); /// CS WM Time_start - ' ' -
val[15] = Convert.ToInt32(mtrRslt.TimestampEnd); /// CT WM Time_end - ' ' -
//sb.Append(";"); sb.Append(isCamera ? mtrRslt.PulsesPerLiter : 0); /// CU camera: WM Degree per liter
val[16] = (smryItems.Count < 1 ? "0" : DEUtils.GetContent(smryItems[0].Content, wm)); /// CU
val[17] = (smryItems.Count < 2 ? "0" : DEUtils.GetContent(smryItems[1].Content, wm)); /// CV
val[18] = (smryItems.Count < 3 ? "0" : DEUtils.GetContent(smryItems[2].Content, wm)); /// CW
val[19] = (smryItems.Count < 4 ? "0" : DEUtils.GetContent(smryItems[3].Content, wm)); /// CX
val[20] = (smryItems.Count < 5 ? "0" : DEUtils.GetContent(smryItems[4].Content, wm)); /// CY
}
}
else if (wm.Compound())
{
/// Else if this is a compound meter
for (byte b = (byte)CompoundMeterId.CompoundMain; b <= (byte)CompoundMeterId.Compound; b++)
{
var mtrRslt = batchResults.GetMeterTestRslt(tstRslt.Name(), wmNr0, (CompoundMeterId)b);
if (mtrRslt != null)
{
int iIndex = 0;
switch ((CompoundMeterId)b)
{
case CompoundMeterId.CompoundMain:
val[0] = wm.SerialNr; /// CE
break;
case CompoundMeterId.CompoundAux:
val[0] = wm.SerialNrAux; /// CE
break;
case CompoundMeterId.Compound:
val[0] = wm.SerialNr; /// CE
break;
}
val[++iIndex] =
mtrRslt
.VolumeStart; /// CF WM Vinit - pri pevnom starte pociatocny stav natukany alebo cez inteligentny system
val[++iIndex] =
mtrRslt
.VolumeEnd; /// CG WM Vfin - pri pevnom starte konecny stav natukany alebo cez inteligentny system
val[++iIndex] = mtrRslt.VolumeMeter; /// CH WM Vmer - objem namerany vodomerom
val[++iIndex] = mtrRslt.VolumeRef; /// CI WM Vet - objem namerany stanicou
val[++iIndex] = mtrRslt.Error; /// CJ WM Emt - chyba vodomerom nameraneho objemu
val[++iIndex] = 0; /// CK WM U - neistota (zatial nechat prazdne)
val[++iIndex] = mtrRslt.PulsesMeter; /// CL WM Np met - pocet impulzov zo skusaneho meradla
val[++iIndex] =
mtrRslt
.PulsesMaster; /// CM WM Np elm - pocet impulzov etalonu pocas merania pre prislusny vodomer
val[++iIndex] =
mtrRslt.TestTime; /// CN WM Tmet - cas merania (obmedzany pri synchro skuske)
val[++iIndex] =
mtrRslt.Passed
? "OK"
: "NOK"; /// CO WM Vysledok (t.j. ci je v hraniciach chyb) - OK/NOK
val[++iIndex] = " "; /// CP WM AN value - hodnota z analogoveho prevodnika (teraz nic)
bool isCamera = mtrRslt.IsCamera();
val[++iIndex] = (isCamera
? mtrRslt.VolumeStart *
mtrRslt.PulsesPerLiter /// CQ WM Phi_start (pri hodnotach z kamery)
: wm.WMPosition); /// CQ WMPosition (normalne)
val[++iIndex] = (isCamera
? mtrRslt.VolumeEnd * mtrRslt.PulsesPerLiter /// CR WM Phi_end (pri hodnotach z kamery)
: 0); /// CR not used/spare (normalne)
val[++iIndex] = (isCamera ? mtrRslt.TimestampStart : 0); /// CS WM Time_start - ' ' -
val[++iIndex] = (isCamera ? mtrRslt.TimestampEnd : 0); /// CT WM Time_end - ' ' -
val[++iIndex] = (isCamera ? mtrRslt.PulsesPerLiter : 0); /// CU WM Degree per liter
val[++iIndex] = "0"; /// CV Analog out 1 (max mA)
val[++iIndex] = "0"; /// CW Analog out 2 (V)
val[++iIndex] = "0"; /// CX Analog out 3 (min mA)
val[++iIndex] = "0"; /// CY Analog out 4 (max Q)
}
}
}
else /// if (ProcessData.BatchRslts.WaterMeters[i].HeatMeter())
{
/// Else this is a heat meter
var volumeMtr =
batchResults.GetMeterTestRslt(tstRslt.Name(), wmNr0, CompoundMeterId.HeatMeterVolume);
var energyMtr =
batchResults.GetMeterTestRslt(tstRslt.Name(), wmNr0, CompoundMeterId.HeatMeterEnergy);
if (volumeMtr != null)
{
int iIndex = 0;
val[iIndex] = wm.SerialNr; /// WM Ser.No.
val[iIndex] =
volumeMtr
.VolumeStart; /// WM Vstart - pociatocny stav pri pevnom starte alebo zachyteny pri data streame
val[iIndex] =
volumeMtr
.VolumeEnd; /// WM Vend - konecny stav pri pevnom starte alebo zachyteny pri data streame
val[iIndex] = volumeMtr.VolumeMeter; /// WM Vmer - objem namerany vodomerom
val[iIndex] = volumeMtr.VolumeRef; /// WM Vref - objem namerany stanicou
val[iIndex] = volumeMtr.Error; /// WM Emt - chyba vodomerom nameraneho objemu
#if IPERL
val[iIndex] = wm.CalibFactor; /// iPerl calibration factor used during the test / ...
#else
val[iIndex] = 0; /// nechat prazdne
#endif
val[iIndex] = volumeMtr.PulsesMeter; /// WM Np met - pocet impulzov zo skusaneho meradla
val[iIndex] =
volumeMtr
.PulsesMaster; /// WM Np elm - pocet impulzov etalonu pocas merania pre prislusny vodomer
val[iIndex] = volumeMtr.TestTime; /// WM Tmet - cas merania (obmedzany pri synchro skuske)
val[iIndex] =
volumeMtr.Passed ? "OK" : "NOK"; /// WM Vysledok (t.j. ci je v hraniciach chyb) - OK/NOK
#if IPERL
val[iIndex] =
(volumeMtr.WaterMeter.Q2CorrRL); /// iPerl Q2 correction factor used during the test / AN value - hodnota z analogoveho prevodnika
#else
val[iIndex] = " "; /// nechat prazdne
#endif
val[iIndex] =
(volumeMtr.VolumeStart); /// WM Volume_start - pri datastreamovych hodnotach (alebo kamera)
val[iIndex] = (volumeMtr.TimestampStart); /// WM Time_start - ' ' -
val[iIndex] = (volumeMtr.VolumeEnd); /// WM Volume_end - ' ' -
val[iIndex] = (volumeMtr.TimestampEnd); /// WM Time_end - ' ' -
}
if (energyMtr != null)
{
int iIndex = 0;
val[iIndex] = (wm.SerialNr); /// WM Ser.No.
val[iIndex] =
(energyMtr
.VolumeStart); /// WM Vstart - pociatocny stav pri pevnom starte alebo zachyteny pri data streame
val[iIndex] =
(energyMtr
.VolumeEnd); /// WM Vend - konecny stav pri pevnom starte alebo zachyteny pri data streame
val[iIndex] = (energyMtr.VolumeMeter); /// WM Vmer - objem namerany vodomerom
val[iIndex] = (energyMtr.VolumeRef); /// WM Vref - objem namerany stanicou
val[iIndex] = (energyMtr.Error); /// WM Emt - chyba vodomerom nameraneho objemu
#if IPERL
val[iIndex] = wm.CalibFactor; /// iPerl calibration factor used during the test / ...
#else
val[iIndex] = " "; /// nechat prazdne
#endif
val[iIndex] = (energyMtr.PulsesMeter); /// WM Np met - pocet impulzov zo skusaneho meradla
val[iIndex] =
(energyMtr
.PulsesMaster); /// WM Np elm - pocet impulzov etalonu pocas merania pre prislusny vodomer
val[iIndex] = (energyMtr.TestTime); /// WM Tmet - cas merania (obmedzany pri synchro skuske)
val[iIndex] =
(energyMtr.Passed ? "OK" : "NOK"); /// WM Vysledok (t.j. ci je v hraniciach chyb) - OK/NOK
#if IPERL
val[iIndex] =
energyMtr.WaterMeter.Q2CorrRL; /// iPerl Q2 correction factor used during the test / AN value - hodnota z analogoveho prevodnika
#else
val[iIndex] = " "; /// nechat prazdne
#endif
val[iIndex] =
energyMtr.VolumeStart; /// WM Volume_start - pri datastreamovych hodnotach (alebo kamera)
val[iIndex] = energyMtr.TimestampStart; /// WM Time_start - ' ' -
val[iIndex] = energyMtr.VolumeEnd; /// WM Volume_end - ' ' -
val[iIndex] = energyMtr.TimestampEnd; /// WM Time_end - ' ' -
}
}
}
}
// public void ProcessDataMeterLine2(TestRslt tstRslt, WaterMeter wm, BatchResults batchResults, int wmNr0)
// {
// var smryItems = DEItem.GetSummaryColumns();
// {
//
//
// if (!wm.Compound() && !wm.HeatMeter())
// {
// /// If this is a single meter
//
// Results.Entities.MeterTestRslt mtrRslt = batchResults.GetMeterTestRslt(tstRslt.Name(), wmNr0, CompoundMeterId.Single);
//
// if (mtrRslt != null)
// {
// bool isCamera = (mtrRslt.RegReaderType == (int)RegisterReaderType.Camera);
//
// SerNo = wm.SerialNr;/// CE WM Ser.No.
// VolMtSt = mtrRslt.VolumeStart; /// CF WM Vstart - pociatocny stav pri pevnom starte alebo zachyteny pri data streame
// VolMtEn = mtrRslt.VolumeEnd; /// CG WM Vend - konecny stav pri pevnom starte alebo zachyteny pri data streame
// VolMt = mtrRslt.VolumeMeter; /// CH WM Vmer - objem namerany vodomerom
// VolRm = mtrRslt.VolumeRef; /// CI WM Vref - objem namerany stanicou
// ERel = mtrRslt.Error; /// CJ WM Emt - chyba vodomerom nameraneho objemu
// #if IPERL
// IPerlCalibrationFactor = wm.CalibFactor; /// CK iPerl calibration factor used during the test / ...
// #else
// IPerlCalibrationFactor = 0; /// CK nechat prazdne
// #endif
// Pulses = Convert.ToInt32(mtrRslt.PulsesMeter); /// CL WM Np met - pocet impulzov zo skusaneho meradla
// RefPulsesNi = Convert.ToInt32(mtrRslt.PulsesMaster); /// CM WM Np elm - pocet impulzov etalonu pocas merania pre prislusny vodomer
// T = mtrRslt.TestTime; /// CN WM Tmet - cas merania (obmedzany pri synchro skuske)
// Evaluation = mtrRslt.Passed ? "OK" : "NOK"; /// CO WM Vysledok (t.j. ci je v hraniciach chyb) - OK/NOK
// #if IPERL
// PulsesL = mtrRslt.WaterMeter.Q2CorrRL; /// CP iPerl Q2 correction factor used during the test / AN value - hodnota z analogoveho prevodnika
// #else
// PulsesL = mtrRslt.PulsesPerLiter; /// CP Pulses per liter
// #endif
// ImpL = Convert.ToInt32(isCamera
// ? mtrRslt.VolumeStart * mtrRslt.PulsesPerLiter /// CQ WM Phi_start (pri hodnotach z kamery)
// : wm.WMPosition); /// CQ WMPosition (normalne)
// Div = Convert.ToInt32(isCamera
// ? mtrRslt.VolumeEnd * mtrRslt.PulsesPerLiter /// CR WM Phi_end (pri hodnotach z kamery)
// : 0); /// CR not used/spare (normalne)
//
// //TODO - Time start is in table as VEnd ??? check it
// VEnd = Convert.ToInt32(mtrRslt.TimestampStart); /// CS WM Time_start - ' ' -
// TEnd = Convert.ToInt32(mtrRslt.TimestampEnd); /// CT WM Time_end - ' ' -
//
// //sb.Append(";"); sb.Append(isCamera ? mtrRslt.PulsesPerLiter : 0); /// CU camera: WM Degree per liter
// SmryItems[0] = (smryItems.Count < 1 ? "0" : DEUtils.GetContent(smryItems[0].Content, wm)); /// CU
// SmryItems[1] = (smryItems.Count < 2 ? "0" : DEUtils.GetContent(smryItems[1].Content, wm)); /// CV
// SmryItems[2] = (smryItems.Count < 3 ? "0" : DEUtils.GetContent(smryItems[2].Content, wm)); /// CW
// SmryItems[3] = (smryItems.Count < 4 ? "0" : DEUtils.GetContent(smryItems[3].Content, wm)); /// CX
// SmryItems[4] = (smryItems.Count < 5 ? "0" : DEUtils.GetContent(smryItems[4].Content, wm)); /// CY
// }
// }
// else if (wm.Compound())
// {
// /// Else if this is a compound meter
//
// for (byte b = (byte)CompoundMeterId.CompoundMain; b <= (byte)CompoundMeterId.Compound; b++)
// {
// var mtrRslt = batchResults.GetMeterTestRslt(tstRslt.Name(), wmNr0, (CompoundMeterId)b);
//
// if (mtrRslt != null)
// {
// switch ((CompoundMeterId)b)
// {
// case CompoundMeterId.CompoundMain:
// SerNo = wm.SerialNr; /// CE
// break;
// case CompoundMeterId.CompoundAux:
// SerNo = wm.SerialNrAux; /// CE
// break;
// case CompoundMeterId.Compound:
// SerNo = wm.SerialNr; /// CE
// break;
// }
// VolMtSt = mtrRslt.VolumeStart; /// CF WM Vinit - pri pevnom starte pociatocny stav natukany alebo cez inteligentny system
// VolMtEn = mtrRslt.VolumeEnd; /// CG WM Vfin - pri pevnom starte konecny stav natukany alebo cez inteligentny system
// VolMt = mtrRslt.VolumeMeter; /// CH WM Vmer - objem namerany vodomerom
// VolRm = mtrRslt.VolumeRef; /// CI WM Vet - objem namerany stanicou
// ERel = mtrRslt.Error; /// CJ WM Emt - chyba vodomerom nameraneho objemu
// IPerlCalibrationFactor = 0; /// CK WM U - neistota (zatial nechat prazdne)
// Pulses = mtrRslt.PulsesMeter; /// CL WM Np met - pocet impulzov zo skusaneho meradla
// RefPulsesNi = mtrRslt.PulsesMaster; /// CM WM Np elm - pocet impulzov etalonu pocas merania pre prislusny vodomer
// T = mtrRslt.TestTime; /// CN WM Tmet - cas merania (obmedzany pri synchro skuske)
// Evaluation = mtrRslt.Passed ? "OK" : "NOK"; /// CO WM Vysledok (t.j. ci je v hraniciach chyb) - OK/NOK
// PulsesL = 0;//" " /// CP WM AN value - hodnota z analogoveho prevodnika (teraz nic)
//
// bool isCamera = mtrRslt.IsCamera();
// ImpL = (isCamera
// ? mtrRslt.VolumeStart * mtrRslt.PulsesPerLiter /// CQ WM Phi_start (pri hodnotach z kamery)
// : wm.WMPosition); /// CQ WMPosition (normalne)
// Div = (isCamera
// ? mtrRslt.VolumeEnd * mtrRslt.PulsesPerLiter /// CR WM Phi_end (pri hodnotach z kamery)
// : 0); /// CR not used/spare (normalne)
// VEnd = (isCamera ? mtrRslt.TimestampStart : 0); /// CS WM Time_start - ' ' -
// TEnd = (isCamera ? mtrRslt.TimestampEnd : 0); /// CT WM Time_end - ' ' -
// SmryItems[0] = (isCamera ? mtrRslt.PulsesPerLiter : 0); /// CU WM Degree per liter
//
// SmryItems[1] = "0"; /// CV Analog out 1 (max mA)
// SmryItems[2] = "0"; /// CW Analog out 2 (V)
// SmryItems[3] = "0"; /// CX Analog out 3 (min mA)
// SmryItems[4] = "0"; /// CY Analog out 4 (max Q)
// }
// }
// }
// else /// if (ProcessData.BatchRslts.WaterMeters[i].HeatMeter())
// {
// /// Else this is a heat meter
//
// var volumeMtr = batchResults.GetMeterTestRslt(tstRslt.Name(), wmNr0, CompoundMeterId.HeatMeterVolume);
// var energyMtr = batchResults.GetMeterTestRslt(tstRslt.Name(), wmNr0, CompoundMeterId.HeatMeterEnergy);
//
// if (volumeMtr != null)
// {
// SerNo = wm.SerialNr; /// WM Ser.No.
// VolMtSt = volumeMtr.VolumeStart; /// WM Vstart - pociatocny stav pri pevnom starte alebo zachyteny pri data streame
// VolMtEn = volumeMtr.VolumeEnd; /// WM Vend - konecny stav pri pevnom starte alebo zachyteny pri data streame
// VolMt = volumeMtr.VolumeMeter; /// WM Vmer - objem namerany vodomerom
// VolRm = volumeMtr.VolumeRef; /// WM Vref - objem namerany stanicou
// ERel = volumeMtr.Error; /// WM Emt - chyba vodomerom nameraneho objemu
// #if IPERL
// IPerlCalibrationFactor = wm.CalibFactor; /// iPerl calibration factor used during the test / ...
// #else
// IPerlCalibrationFactor = 0; /// nechat prazdne
// #endif
// Pulses = volumeMtr.PulsesMeter; /// WM Np met - pocet impulzov zo skusaneho meradla
// RefPulsesNi = volumeMtr.PulsesMaster; /// WM Np elm - pocet impulzov etalonu pocas merania pre prislusny vodomer
// T = volumeMtr.TestTime; /// WM Tmet - cas merania (obmedzany pri synchro skuske)
// Evaluation = volumeMtr.Passed ? "OK" : "NOK"); /// WM Vysledok (t.j. ci je v hraniciach chyb) - OK/NOK
// #if IPERL
// ImpL = (volumeMtr.WaterMeter.Q2CorrRL); /// iPerl Q2 correction factor used during the test / AN value - hodnota z analogoveho prevodnika
// #else
// ImpL = 0; //(" "); /// nechat prazdne
// #endif
// ImpL = (volumeMtr.VolumeStart); /// WM Volume_start - pri datastreamovych hodnotach (alebo kamera)
// VEnd = (volumeMtr.TimestampStart); /// WM Time_start - ' ' -
// VolMtEn = (volumeMtr.VolumeEnd); /// WM Volume_end - ' ' -
// TEnd = (volumeMtr.TimestampEnd); /// WM Time_end - ' ' -
// }
//
// if (energyMtr != null)
// {
// SerNo = (wm.SerialNr); /// WM Ser.No.
// VolMtSt = (energyMtr.VolumeStart); /// WM Vstart - pociatocny stav pri pevnom starte alebo zachyteny pri data streame
// VolMtEn = (energyMtr.VolumeEnd); /// WM Vend - konecny stav pri pevnom starte alebo zachyteny pri data streame
// VolMt = (energyMtr.VolumeMeter); /// WM Vmer - objem namerany vodomerom
// VolRm = (energyMtr.VolumeRef); /// WM Vref - objem namerany stanicou
// ERel = (energyMtr.Error); /// WM Emt - chyba vodomerom nameraneho objemu
// #if IPERL
// IPerlCalibrationFactor = wm.CalibFactor; /// iPerl calibration factor used during the test / ...
// #else
// IPerlCalibrationFactor = 0;//(" "); /// nechat prazdne
// #endif
// Pulses = (energyMtr.PulsesMeter); /// WM Np met - pocet impulzov zo skusaneho meradla
// RefPulsesNi = (energyMtr.PulsesMaster); /// WM Np elm - pocet impulzov etalonu pocas merania pre prislusny vodomer
// T = (energyMtr.TestTime); /// WM Tmet - cas merania (obmedzany pri synchro skuske)
// Evaluation = (energyMtr.Passed ? "OK" : "NOK"); /// WM Vysledok (t.j. ci je v hraniciach chyb) - OK/NOK
// #if IPERL
// sb.Append(";"); sb.Append(energyMtr.WaterMeter.Q2CorrRL); /// iPerl Q2 correction factor used during the test / AN value - hodnota z analogoveho prevodnika
// #else
// sb.Append(";"); sb.Append(" "); /// nechat prazdne
// #endif
// VolMtSt = (energyMtr.VolumeStart); /// WM Volume_start - pri datastreamovych hodnotach (alebo kamera)
// VEnd = (energyMtr.TimestampStart); /// WM Time_start - ' ' -
// VolMtEn = (energyMtr.VolumeEnd); /// WM Volume_end - ' ' -
// TEnd = (energyMtr.TimestampEnd); /// WM Time_end - ' ' -
// }
// }
// }
// }
public ProcessDataMeterLine()
{
}
/* public void InitDefault()
{
SerNo = "Diehl202415687905"; // , formatStr);//Position - Ser.No. - CE
VolMtSt = 0; // , formatInt);//Vol.Mt.st - CF
VolMtEn = 0; // , formatInt);//Vol.Mt.en - CG
VolMt = 0.975333560911164; // , formatD7);//Vol.Mt. - CH
VolRm = 0.980633088; //, formatD7);//Vol.rm - CI
ERel = -0.540418981321314; // , formatD6); // E rel. - CJ
// , formatInt); // U - CK
Pulses = 154; // , formatInt); //Pulses() -
RefPulsesNi = 14341; // , formatInt); //Ref pulses_ni()
T = 671.4207764; // , formatD4); //T(s)()_ni
Evaluation = "OK"; // , formatStr);//evaluation
PulsesL = 157.8947; // , formatD4);//Pulses/l - CP
ImpL = 4; // , formatInt);//imp/l
Div = 0; // , formatInt);//div
VEnd = 0; // , formatInt);//Vend
TEnd = 0; // , formatInt);//T end
}*/
public void InitDefault()
{
val[0] = "Diehl202415687905"; // , formatStr);//Position - Ser.No. - CE
val[1] = 0; // , formatInt);//Vol.Mt.st - CF
val[2] = 0; // , formatInt);//Vol.Mt.en - CG
val[3] = 0.975333560911164; // , formatD7);//Vol.Mt. - CH
val[4] = 0.980633088; //, formatD7);//Vol.rm - CI
val[5] = -0.540418981321314; // , formatD6); // E rel. - CJ
// , formatInt); // U - CK
val[6] = 154; // , formatInt); //Pulses() -
val[7] = 14341; // , formatInt); //Ref pulses_ni()
val[8] = 671.4207764; // , formatD4); //T(s)()_ni
val[9] = "OK"; // , formatStr);//evaluation
val[10] = 157.8947; // , formatD4);//Pulses/l - CP
val[11] = 4; // , formatInt);//imp/l
val[12] = 0; // , formatInt);//div
val[13] = 0; // , formatInt);//Vend
val[14] = 0; // , formatInt);//T end
}
}
}
+10
View File
@@ -577,6 +577,16 @@ namespace Results
{
return FormatInt(f, w.Batch.Counter10);
}));
AllItems.Add(new WMeterRsltItemSpec(ItemID.Uncertainty_DIV1, "Uncertainty DIV1", Quantity.Uncertainty, ItemCategory.BenchData, (w,t,u,f,p) => string.IsNullOrEmpty(f) ? "0.1" : string.Format(f, 5)));
AllItems.Add(new WMeterRsltItemSpec(ItemID.Uncertainty_DIV2, "Uncertainty DIV2", Quantity.Uncertainty, ItemCategory.BenchData, (w,t,u,f,p) => string.IsNullOrEmpty(f) ? "0.2" : string.Format(f, 5)));
AllItems.Add(new WMeterRsltItemSpec(ItemID.Uncertainty_DIV3, "Uncertainty DIV3", Quantity.Uncertainty, ItemCategory.BenchData, (w,t,u,f,p) => string.IsNullOrEmpty(f) ? "0.3" : string.Format(f, 5)));
AllItems.Add(new WMeterRsltItemSpec(ItemID.Uncertainty_DIV4, "Uncertainty DIV4", Quantity.Uncertainty, ItemCategory.BenchData, (w,t,u,f,p) => string.IsNullOrEmpty(f) ? "0.4" : string.Format(f, 5)));
AllItems.Add(new WMeterRsltItemSpec(ItemID.Uncertainty_DIV5, "Uncertainty DIV5", Quantity.Uncertainty, ItemCategory.BenchData, (w,t,u,f,p) => string.IsNullOrEmpty(f) ? "0.5" : string.Format(f, 5)));
AllItems.Add(new WMeterRsltItemSpec(ItemID.Uncertainty_TEMP1, "Uncertainty TEMP1", Quantity.Uncertainty, ItemCategory.BenchData, (w,t,u,f,p) => string.IsNullOrEmpty(f) ? "0.5" : string.Format(f, 5)));
}
/// To be updated by Output.FileWriter or Output.Printer
+16
View File
@@ -1,4 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ClosedXML" version="0.105.0-rc" targetFramework="net472" />
<package id="ClosedXML.Parser" version="2.0.0-preview1" targetFramework="net472" />
<package id="SixLabors.Fonts" version="1.0.0" targetFramework="net472" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.1.1" targetFramework="net472" />
<package id="DocumentFormat.OpenXml" version="3.1.1" targetFramework="net472" />
<package id="DocumentFormat.OpenXml.Framework" version="3.1.1" targetFramework="net472" />
<package id="EPPlus.Interfaces" version="8.0.0" targetFramework="net472" />
<package id="ExcelNumberFormat" version="1.1.0" targetFramework="net472" />
<package id="Microsoft.Bcl.HashCode" version="1.1.1" targetFramework="net472" />
<package id="Microsoft.IO.RecyclableMemoryStream" version="3.0.1" targetFramework="net472" />
<package id="RBush.Signed" version="4.0.0" targetFramework="net472" />
<package id="System.Buffers" version="4.6.1" targetFramework="net472" />
<package id="System.ComponentModel.Annotations" version="5.0.0" targetFramework="net472" />
<package id="System.Memory" version="4.6.2" targetFramework="net472" />
<package id="System.Numerics.Vectors" version="4.6.1" targetFramework="net472" />
<package id="System.Security.Cryptography.Xml" version="8.0.2" targetFramework="net472" />
<package id="log4net" version="2.0.15" targetFramework="net472" />
</packages>
+1 -41
View File
@@ -378,40 +378,6 @@ namespace SchematicDrawing
Properties.Resources.Valve_XL_closed,
Properties.Resources.Valve_XL_vacuum,
Properties.Resources.Valve_XL_open_dry);
/// ValveSw
Shapes[DrShIx(Shape.ValveSw, Sz.S)] = new DrawingShape(Shape.ValveSw, Sz.S, 2, 2,
new Node[] { new Node(0, 1, Orient.L), new Node(2, 1, Orient.R) },
new Edge[] { new Edge(0, 1, 20, RouteCouple.OpenWhen1), new Edge(1, 0, 20, RouteCouple.OpenWhen1) },
0, 0, 20, 20,
Properties.Resources.ValveSw_S_open,
Properties.Resources.ValveSw_S_closed,
Properties.Resources.ValveSw_S_vacuum,
Properties.Resources.ValveSw_S_open_dry);
Shapes[DrShIx(Shape.ValveSw, Sz.M)] = new DrawingShape(Shape.ValveSw, Sz.M, 3, 4,
new Node[] { new Node(0, 2, Orient.L), new Node(3, 2, Orient.R) },
new Edge[] { new Edge(0, 1, 30, RouteCouple.OpenWhen1), new Edge(1, 0, 30, RouteCouple.OpenWhen1) },
0, 5, 30, 30,
Properties.Resources.ValveSw_M_open,
Properties.Resources.ValveSw_M_closed,
Properties.Resources.ValveSw_M_vacuum,
Properties.Resources.ValveSw_M_open_dry);
Shapes[DrShIx(Shape.ValveSw, Sz.L)] = new DrawingShape(Shape.ValveSw, Sz.L, 4, 4,
new Node[] { new Node(0, 2, Orient.L), new Node(4, 2, Orient.R) },
new Edge[] { new Edge(0, 1, 40, RouteCouple.OpenWhen1), new Edge(1, 0, 40, RouteCouple.OpenWhen1) },
0, 0, 40, 40,
Properties.Resources.ValveSw_L_open,
Properties.Resources.ValveSw_L_closed,
Properties.Resources.ValveSw_L_vacuum,
Properties.Resources.ValveSw_L_open_dry);
Shapes[DrShIx(Shape.ValveSw, Sz.XL)] = new DrawingShape(Shape.ValveSw, Sz.XL, 5, 6,
new Node[] { new Node(0, 3, Orient.L), new Node(5, 3, Orient.R) },
new Edge[] { new Edge(0, 1, 50, RouteCouple.OpenWhen1), new Edge(1, 0, 50, RouteCouple.OpenWhen1) },
0, 5, 50, 50,
Properties.Resources.ValveSw_XL_open,
Properties.Resources.ValveSw_XL_closed,
Properties.Resources.ValveSw_XL_vacuum,
Properties.Resources.ValveSw_XL_open_dry);
/// Diverter
Shapes[DrShIx(Shape.Div, Sz.S)] = new DrawingShape(Shape.Div, Sz.S, 2, 2,
new Node[] { new Node(2, 0, Orient.Up), new Node(1, 2, Orient.Dn), new Node(3, 2, Orient.Dn) },
@@ -557,18 +523,12 @@ namespace SchematicDrawing
Shapes[DrShIx(Shape.Scale, Sz.L)] = new DrawingShape(Shape.Scale, Sz.L, 12, 11, new Node[] { new Node(6, 11, Orient.Dn) }, null, 0, 0, 120, 110, Properties.Resources.Scale_L);
Shapes[DrShIx(Shape.Scale, Sz.XL)] = new DrawingShape(Shape.Scale, Sz.XL, 16, 13, new Node[] { new Node(8, 13, Orient.Dn) }, null, 0, 0, 160, 130, Properties.Resources.Scale_XL);
/// Tank uni
/// Tank
Shapes[DrShIx(Shape.Tank, Sz.S)] = new DrawingShape(Shape.Tank, Sz.S, 10, 8, new Node[] { new Node(0, 6, Orient.L) }, null, 0, 0, 100, 80, Properties.Resources.Tank_S);
Shapes[DrShIx(Shape.Tank, Sz.M)] = new DrawingShape(Shape.Tank, Sz.M, 12, 9, new Node[] { new Node(0, 7, Orient.L) }, null, 0, 0, 120, 90, Properties.Resources.Tank_M);
Shapes[DrShIx(Shape.Tank, Sz.L)] = new DrawingShape(Shape.Tank, Sz.L, 15, 11, new Node[] { new Node(0, 9, Orient.L) }, null, 0, 0, 150, 110, Properties.Resources.Tank_L);
Shapes[DrShIx(Shape.Tank, Sz.XL)] = new DrawingShape(Shape.Tank, Sz.XL, 20, 13, new Node[] { new Node(0, 11, Orient.L) }, null, 0, 0, 200, 130, Properties.Resources.Tank_XL);
/// Tank hot
Shapes[DrShIx(Shape.TankHot, Sz.S)] = new DrawingShape(Shape.TankHot, Sz.S, 10, 8, new Node[] { new Node(0, 6, Orient.L) }, null, 0, 0, 100, 80, Properties.Resources.Tank_S_hot);
Shapes[DrShIx(Shape.TankHot, Sz.M)] = new DrawingShape(Shape.TankHot, Sz.M, 12, 9, new Node[] { new Node(0, 7, Orient.L) }, null, 0, 0, 120, 90, Properties.Resources.Tank_M_hot);
Shapes[DrShIx(Shape.TankHot, Sz.L)] = new DrawingShape(Shape.TankHot, Sz.L, 15, 11, new Node[] { new Node(0, 9, Orient.L) }, null, 0, 0, 150, 110, Properties.Resources.Tank_L_hot);
Shapes[DrShIx(Shape.TankHot, Sz.XL)] = new DrawingShape(Shape.TankHot, Sz.XL, 20, 13, new Node[] { new Node(0, 11, Orient.L) }, null, 0, 0, 200, 130, Properties.Resources.Tank_XL_hot);
/// Junction
Shapes[DrShIx(Shape.Junction, Sz.None)] = new DrawingShape(Shape.Junction, Sz.None, 0, 0, new Node[] { new Node(0, 0, Orient.R) });
Shapes[DrShIx(Shape.Junction, Sz.S)] = new DrawingShape(Shape.Junction, Sz.S, 2, 2,
-2
View File
@@ -45,13 +45,11 @@ namespace SchematicDrawing
Scale,
Sink,
Tank,
TankHot,
Tee,
TempM,
UniCB,
Vacuum,
Valve,
ValveSw,
WaterM,
ElectricM,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 842 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 768 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 746 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 894 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1018 B

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