Compare commits

...

8 Commits

Author SHA1 Message Date
347a8798b8 Enhance Q3 calibration logic by refining PrepareSlotQ3Calibration and WriteSlotQ3Calibration methods, improving handling of TestRsltCalibFactor storage across multiple channels, and extending exception handling and debug logging for Genesis operations. 2026-05-28 14:29:02 +02:00
3cd488fc76 Increment assembly version to 3.9.3121.1, add FailedPrepare error constant and handling in iPerlCommunicationForm, enhance PrepareSlotQ3Calibration and WriteSlotQ3Calibration with exception handling and logging, introduce IsCalibFactorValid property and mappings for calibration logic, and extend debug logging across Genesis operations. 2026-05-27 14:00:40 +02:00
e88e441875 Refactor preadjustmenActionsViewButton to preadjustmentActionsViewButton, add Q3Channel property to entities and mappings, implement schema migrations for Q3Channel, update GenesisSmartReader Q3Channel logic, replace file paths for clarity, upgrade projects to .NET Framework 4.8, and extend debug logging. 2026-05-25 09:21:32 +02:00
89cfcb75e8 Merge branch 'develop/SLM-PT50_genesisDirectDecode' into develop/SLM-PT50_genesisDirectDecode_special
# Conflicts:
#	GenesisCordonelInterface/UI/LaatzenAPI_CordonelPreadjustmentUI/FrmCordonelPreadjustmentUI.cs
#	TBF/TBF.csproj
2026-05-22 12:58:48 +02:00
9700ba7900 Develop - GciBridge -> GCI -> PreadjustmentUI functions 3 2026-05-22 08:52:40 +02:00
bc72130d09 Develop - GciBridge -> GCI -> PreadjustmentUI functions 2 2026-05-21 08:16:02 +02:00
ad208f9633 Develop - GciBridge -> GCI -> PreadjustmentUI functions 2026-05-18 19:20:10 +02:00
ad2bfd3639 Upgrade (develop) - GCI - GciBridge - improved Disconnect 2026-05-14 13:05:21 +02:00
140 changed files with 4035 additions and 789 deletions

View File

@ -8,7 +8,7 @@
<OutputType>WinExe</OutputType>
<RootNamespace>AppDiagnostic</RootNamespace>
<AssemblyName>AppDiagnostic</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
@ -102,4 +102,4 @@
<None Include="Resources\TBF_icon.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Common</RootNamespace>
<AssemblyName>Common</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -114,4 +114,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Config</RootNamespace>
<AssemblyName>Config</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -150,4 +150,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DataMatrix4Net</RootNamespace>
<AssemblyName>DataMatrix4Net</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -58,4 +58,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DataStreamInterface</RootNamespace>
<AssemblyName>DataStreamInterface</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -61,4 +61,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Decrypt</RootNamespace>
<AssemblyName>Decrypt</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -63,4 +63,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DeviceTest</RootNamespace>
<AssemblyName>DeviceTest</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -114,4 +114,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Dirichlet.Numerics</RootNamespace>
<AssemblyName>Dirichlet.Numerics</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
@ -51,4 +51,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Encrypt</RootNamespace>
<AssemblyName>Encrypt</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -63,4 +63,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>EventViewer</RootNamespace>
<AssemblyName>EventViewer</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -142,4 +142,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>FeatureVectorCalculator</RootNamespace>
<AssemblyName>FeatureVectorCalculator</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -97,4 +97,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<ProjectType>Local</ProjectType>
@ -28,7 +28,7 @@
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
@ -180,4 +180,4 @@
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="14.0">
<PropertyGroup>
<ProjectType>Local</ProjectType>
@ -35,7 +35,7 @@
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<OldToolsVersion>2.0</OldToolsVersion>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
@ -146,4 +146,4 @@
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>GenericTest</RootNamespace>
<AssemblyName>GenericTest</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -160,4 +160,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,9 +1,15 @@
using GenesisCordonelInterface.Core.Threading;
using CordonelPreadjustmentUi;
using CordonelPreadjustmentUi.Processes;
using CordonelPreadjustmentUi.Processes.Actions;
using CordonelPreadjustmentUi.Processes.Itinerary;
using GenesisCordonelInterface.Core.Threading;
using GenesisCordonelInterface.UI.LaatzenAPI_CordonelPreadjustmentUI;
using NLog;
using NLog.Fluent;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Reflection;
@ -16,7 +22,9 @@ using Xylem.Common.Hardware.Interfaces.Ports.PortCore.EventArguments;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore;
using Xylem.Common.Hardware.WaterMeter.Genesis.Registers;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore.Consts;
using Xylem.Common.Hardware.WaterMeter.WaterMeterRegisters;
using Xylem.Common.Ui.CordonelPreadjustmentUi;
using static GenesisCordonelInterface.API.PublicModels;
using static Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.GenesisMeter;
using static Xylem.Common.Hardware.WaterMeter.Genesis.Registers.Register;
@ -30,8 +38,14 @@ namespace GenesisCordonelInterface.API
//private static readonly Lazy<ILogger> Logger = new Lazy<ILogger>(() => LogManager.GetLogger("GCI"));
private static readonly NLog.ILogger Logger = NLog.LogManager.GetLogger("GenesisCordonelInterface");
//GenesisToolBox
private readonly MeterBatch _meterBatch = new MeterBatch();
//Preadjustment
public PreAdjustmentSettingsContainer _settings = new PreAdjustmentSettingsContainer();
public List<MeterStateControl> _meterControls = new List<MeterStateControl>();
public List<MeterStateControl> _tempMeterControls = new List<MeterStateControl>();
// Protects all access to _meterBatch.ListOfMeters
private readonly object _meterBatchLock = new object();
private static readonly object _setupGenesisMeterLock = new object();
@ -75,16 +89,19 @@ namespace GenesisCordonelInterface.API
#endregion
#region ================================== MeterBatch Debug ==================================
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<MeterBatchDebugStatus> GetMeterBatchDebugStatuses()
{
List<GenesisMeter> meters;
List<ZeroFlowGenesisMeter> meters;
//just snapshot of list under lock
lock (_meterBatchLock)
{
meters = _meterBatch.ListOfMeters
.OfType<GenesisMeter>()
.OfType<ZeroFlowGenesisMeter>()
.ToList();
}
@ -152,7 +169,7 @@ namespace GenesisCordonelInterface.API
lock (_meterBatchLock)
{
return _meterBatch.ListOfMeters
.OfType<GenesisMeter>()
.OfType<ZeroFlowGenesisMeter>()
.FirstOrDefault(m => m.Slot == slot);
}
}
@ -193,7 +210,7 @@ namespace GenesisCordonelInterface.API
{
lock (_meterBatchLock)
{
foreach (var meter in _meterBatch.ListOfMeters.OfType<GenesisMeter>())
foreach (var meter in _meterBatch.ListOfMeters.OfType<ZeroFlowGenesisMeter>())
{
meter.DisposeMeter();
}
@ -228,6 +245,16 @@ namespace GenesisCordonelInterface.API
return string.IsNullOrWhiteSpace(port) ? "<empty>" : port;
}
public ConcurrentDictionary<RegisterDefinition, Byte[]> GetRegistersDicForSlot(int slot)
{
var meter = GetMeterThreadSafe(slot);
if (meter == null)
throw new Exception($"Slot {slot} not initialized.");
return meter.GetRegistersDic();
}
#endregion
#region ================================== INIT/UPDATE ==================================
@ -345,7 +372,7 @@ namespace GenesisCordonelInterface.API
PortConfig? req,
PortConfig? str)
{
GenesisMeter meter = new GenesisMeter();
ZeroFlowGenesisMeter meter = new ZeroFlowGenesisMeter(0, 3, !(_meterControls is TempMeterStateControl), useForPreadjustmentUI: false);
meter.Slot = slot;
@ -354,7 +381,8 @@ namespace GenesisCordonelInterface.API
meter.requestPortConfig = req;
meter.streamingPortConfig = str;
//meter.SetupGenesisMeter(slot, req, str, true);
meter.onlineOperation = false;
lock (_meterBatchLock)
{
_meterBatch.AddMeter2(meter);
@ -942,9 +970,17 @@ namespace GenesisCordonelInterface.API
var meter = GetMeterThreadSafe(slot);
meter.Logout();
bool logoutSuccess = meter.Logout();
meter.Disconnect();
if (meter.IsLoggedOn)
{
meter.MarkLoggedOut();
meter.LastLogoutStatus = logoutSuccess
? "Successfully logged out"
: "Logout failed, but connection was closed";
}
bool success = !meter.IsConnected && !meter.IsLoggedOn;
if (success)
@ -1370,5 +1406,812 @@ namespace GenesisCordonelInterface.API
}
#endregion
// GCI to PreadjustmentUI - MANUAL - Laatzen GUI
#region ================================== PreAdjustmentUI form call ==================================
private FrmCordonelPreadjustmentUI _preadjustmentForm;
private readonly object _formLock = new object();
public event EventHandler PreadjustmentFormClosedByUser;
/// <summary>
/// Shows singleton instance of preadjustment form.
///
/// Behavior:
///
/// ShowPreadjustmentForm()
/// ↓
/// create form instance if necessary
/// ↓
/// user works with form
/// ↓
/// user clicks X
/// ↓
/// FormClosing
/// ↓
/// Cancel closing
/// ↓
/// Hide()
/// ↓
/// PreadjustmentFormClosedByUser
/// ↓
/// external workflow continues
///
/// Notes:
/// - form instance is reused
/// - form is hidden instead of disposed
/// - event notification is non-blocking
/// - repeated calls bring existing form to front
/// - actual disposal happens only during application shutdown
///
/// Typical usage:
///
/// _bridge.PreadjustmentFormClosedByUser += (s,e)=>
/// {
/// ContinueWorkflow();
/// };
///
/// _bridge.ShowPreadjustmentForm(this);
///
/// </summary>
public void ShowPreadjustmentForm(IWin32Window owner)
{
lock (_formLock)
{
// Create form only if it does not exist
// or has already been disposed
if (_preadjustmentForm == null || _preadjustmentForm.IsDisposed)
{
_preadjustmentForm = new FrmCordonelPreadjustmentUI(_meterBatch);
_preadjustmentForm.FormClosing += (s, e) =>
{
// Hide the form instead of destroying it
// when user clicks the close button
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
_preadjustmentForm.Hide();
// Notify outside code that the form was closed by user
PreadjustmentFormClosedByUser?.Invoke(
this,
EventArgs.Empty);
}
};
}
// If already visible, bring it to front
if (_preadjustmentForm.Visible)
{
_preadjustmentForm.Activate();
_preadjustmentForm.BringToFront();
return;
}
// Show existing form instance
_preadjustmentForm.Show(owner);
}
}
#endregion
#region ================================== Create context for PreAdjustmentUI ==================================
/*public interface IGciToolContext
{
IReadOnlyList<int> GetEnabledSlots();
string GetPcbId(int slot);
string GetSerialNumber(int slot);
bool Login(int slot);
bool Logout(int slot);
bool ReadRegister(int slot, int address, out string value);
bool WriteRegister(int slot, int address, string value);
void LogInfo(string message);
void LogError(string message);
event EventHandler<GciMeterChangedEventArgs> MeterChanged;
}*/
#endregion
// GCI to PreadjustmentUI - AUTOMATIC - STANDALONE - Laatzen GUI
#region ================================== PreAdjustmentUI DETECT process ==================================
public Task<PreadjustmentDetectResult> Preadjustment_DetectAsync(
CancellationToken token = default)
{
return Task.Run(() => Preadjustment_DetectCore(token), token);
}
private PreadjustmentDetectResult Preadjustment_DetectCore(
CancellationToken token)
{
const string operation = nameof(Preadjustment_DetectCore);
try
{
MeterBatch globalMeterBatch = new MeterBatch();
MeterBatch thermoMeterBatch = new MeterBatch();
if (_settings == null)
throw new ArgumentNullException(nameof(_settings));
if (_meterControls == null)
throw new ArgumentNullException(nameof(_meterControls));
if (_tempMeterControls == null)
_tempMeterControls = new List<MeterStateControl>();
if (globalMeterBatch.ListOfMeters.Any())
globalMeterBatch.RemoveAllMeters();
if (thermoMeterBatch.ListOfMeters.Any())
thermoMeterBatch.RemoveAllMeters();
globalMeterBatch = _meterBatch;
if (!_settings.GetTempUseTempFlansh())
_tempMeterControls.Clear();
var allMeterControls = new List<MeterStateControl>();
allMeterControls.AddRange(_meterControls);
allMeterControls.AddRange(_tempMeterControls);
CreateZeroFlowMeters(
globalMeterBatch,
thermoMeterBatch,
allMeterControls,
token);
SetEnableOpeningState(allMeterControls);
if (!_meterControls.Any(a => a.EnableOpening))
{
return new PreadjustmentDetectResult
{
Success = false,
DetectedMeterCount = 0,
DetectedThermometerCount = _tempMeterControls.Count(t => t.IsEnabled),
ErrorMessage = "No enabled meter found."
};
}
SetUnknownStatus(allMeterControls);
CheckTemperatureMeters(
_settings,
_tempMeterControls,
token);
return new PreadjustmentDetectResult
{
Success = true,
DetectedMeterCount = _meterControls.Count(m => m.IsEnabled),
DetectedThermometerCount = _tempMeterControls.Count(t => t.IsEnabled)
};
}
catch (Exception ex)
{
return new PreadjustmentDetectResult
{
Success = false,
ErrorMessage = ex.Message
};
}
}
private void CreateZeroFlowMeters(
MeterBatch globalMeterBatch,
MeterBatch thermoMeterBatch,
List<MeterStateControl> allMeterControls,
CancellationToken token)
{
foreach (var meterStateCtl in allMeterControls)
{
token.ThrowIfCancellationRequested();
if (!(meterStateCtl.IsEnabled ||
meterStateCtl is TempMeterStateControl))
{
continue;
}
if (meterStateCtl.Slot == -1)
continue;
ZeroFlowGenesisMeter currentMeter = new ZeroFlowGenesisMeter(meterStateCtl.Slot, 3, !(meterStateCtl is TempMeterStateControl));
var convertedMeter = GetMeterThreadSafe(meterStateCtl.Slot);
if (convertedMeter != null)
{
convertedMeter.CopySafeStateTo(currentMeter);
}
currentMeter.LogOnEnable = true;
currentMeter.LoginFailed = false;
currentMeter.PreparationFailed = false;
currentMeter.AmplitudeFailed = false;
currentMeter.ZeroFlowOffsetFailed = false;
currentMeter.CompletionFailed = false;
currentMeter.Ok = false;
currentMeter.EmptyPipeCheckEnable = false;
currentMeter.EmptyPipeCheckFailed = false;
if (meterStateCtl is TempMeterStateControl)
{
thermoMeterBatch.AddMeter(currentMeter);
meterStateCtl.IsEnabled = true;
}
else
{
if (currentMeter.useConfigSource != ConfigSource.InterfaceInputConfig)
globalMeterBatch.AddMeter(currentMeter);
else
globalMeterBatch.AddMeter2(currentMeter);
}
meterStateCtl.Meter = currentMeter;
}
}
private void SetEnableOpeningState(
List<MeterStateControl> allMeterControls)
{
foreach (var meterState in allMeterControls)
{
meterState.EnableOpening =
meterState.IsEnabled;
}
}
private void SetUnknownStatus(
List<MeterStateControl> allMeterControls)
{
foreach (var meterState in allMeterControls)
{
meterState.SetToUnknownStatus =
!meterState.EnableOpening;
}
}
private void CheckNormalMeters(
List<MeterStateControl> meterControls,
CancellationToken token)
{
foreach (var meterCtl in meterControls)
{
token.ThrowIfCancellationRequested();
if (meterCtl != null && meterCtl.IsEnabled)
{
meterCtl.Ok =
meterCtl.Meter.CheckRequestPort() &&
meterCtl.Meter.CheckStreamingPort();
}
}
}
private void CheckTemperatureMeters(
PreAdjustmentSettingsContainer settings,
List<MeterStateControl> tempMeterControls,
CancellationToken token)
{
if (settings.GetTempUseManualInput())
return;
foreach (var meterCtl in tempMeterControls)
{
token.ThrowIfCancellationRequested();
if (meterCtl != null && meterCtl.IsEnabled)
{
meterCtl.Ok =
meterCtl.Meter.CheckStreamingPort();
}
}
}
#endregion
#region ================================== PreAdjustmentUI PREPARATION process ==================================
public Task<PreadjustmentProcessResult> Preadjustment_PreparationAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return GetWorker(slot).RunAsync(
() => Preadjustment_Preparation(slot, pp),
token);
}
/// <summary>
/// Executes standalone preparation process.
/// </summary>
public PreadjustmentProcessResult Preadjustment_Preparation(
int slot,
ProcessProgress pp)
{
const string operation = nameof(Preadjustment_Preparation);
try
{
LogInfo(operation, $"Start. Slot={slot}");
var meter = GetMeterThreadSafe(slot);
EnsureConnected(meter);
BaseProcess process =
CreatePreparationProcess(pp);
bool success =
ExecuteProcess(process, pp);
var result =
new PreadjustmentProcessResult
{
Success = success,
Slot = slot,
ProcessName = process.ProcessName,
ErrorMessage = success
? null
: process.FailedMessage
};
LogInfo(operation, result.ToString());
return result;
}
catch (Exception ex)
{
LogError(operation, ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Preparation",
ErrorMessage = ex.Message
};
}
}
/// <summary>
/// Creates preparation process instance based on current configuration.
/// </summary>
/// <param name="pp">Current process progress context</param>
/// <returns>Configured preparation process</returns>
private BaseProcess CreatePreparationProcess(ProcessProgress pp)
{
if (pp.Setting.NumberOfPaths == 1)
{
return new SPPreparationProcess(
"Preparation Single",
PreAdjustmentControl.StatusPanelItems.Prepare,
PreAdjustmentControl.PredefinedMessages.WaitUntilPreparationFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.PreparationFailed(pp.Setting.Culture),
60);
}
return new PreparationProcess(
"Preparation",
PreAdjustmentControl.StatusPanelItems.Prepare,
PreAdjustmentControl.PredefinedMessages.WaitUntilPreparationFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.PreparationFailed(pp.Setting.Culture),
60);
}
#endregion
#region ================================== PreAdjustmentUI AMPLITUDE TEST process ==================================
public Task<PreadjustmentProcessResult> Preadjustment_AmplitudeTestAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return GetWorker(slot).RunAsync(
() => Preadjustment_AmplitudeTest(slot, pp),
token);
}
public PreadjustmentProcessResult Preadjustment_AmplitudeTest(
int slot,
ProcessProgress pp)
{
const string operation = nameof(Preadjustment_AmplitudeTest);
try
{
LogInfo(operation, $"Start. Slot={slot}");
var meter = GetMeterThreadSafe(slot);
EnsureConnected(meter);
if (pp.Setting.TempOnly)
{
return new PreadjustmentProcessResult
{
Success = true,
Slot = slot,
ProcessName = "Amplitude Test"
};
}
BaseProcess process = CreateAmplitudeTestProcess(pp);
bool success = ExecuteProcess(process, pp);
LogInfo(operation, $"Finished. Slot={slot}, Success={success}");
return new PreadjustmentProcessResult
{
Success = success,
Slot = slot,
ProcessName = process.ProcessName,
ErrorMessage = success ? null : process.FailedMessage
};
}
catch (Exception ex)
{
LogError(operation, ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Amplitude Test",
ErrorMessage = ex.Message
};
}
}
/// <summary>
/// Creates amplitude test process instance based on current configuration.
/// </summary>
/// <param name="pp">Current process progress context</param>
/// <returns>Configured amplitude test process</returns>
private BaseProcess CreateAmplitudeTestProcess(ProcessProgress pp)
{
if (pp.Setting.NumberOfPaths == 1)
{
return new SPAmplitudeTestProcess(
"Amplitude Test Single",
PreAdjustmentControl.StatusPanelItems.Amplitude,
PreAdjustmentControl.PredefinedMessages.WaitUntilAmplitudeTestFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.AmplitudeFailed(pp.Setting.Culture),
4 * 60);
}
return new AmplitudeTestProcess(
"Amplitude Test",
PreAdjustmentControl.StatusPanelItems.Amplitude,
PreAdjustmentControl.PredefinedMessages.WaitUntilAmplitudeTestFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.AmplitudeFailed(pp.Setting.Culture),
4 * 60);
}
#endregion
#region ================================== PreAdjustmentUI TEMPERATURE CALIBRATION process ==================================
public Task<PreadjustmentProcessResult> Preadjustment_TemperatureCalibrationAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return GetWorker(slot).RunAsync(
() => Preadjustment_TemperatureCalibration(slot, pp),
token);
}
public PreadjustmentProcessResult Preadjustment_TemperatureCalibration(
int slot,
ProcessProgress pp)
{
const string operation =
nameof(Preadjustment_TemperatureCalibration);
try
{
LogInfo(operation, $"Start. Slot={slot}");
var meter =
GetMeterThreadSafe(slot);
EnsureConnected(meter);
BaseProcess process =
CreateTemperatureCalibrationProcess(pp);
bool success =
ExecuteProcess(process, pp);
var result =
new PreadjustmentProcessResult
{
Success = success,
Slot = slot,
ProcessName = process.ProcessName,
ErrorMessage = success
? null
: process.FailedMessage
};
LogInfo(operation, result.ToString());
return result;
}
catch (Exception ex)
{
LogError(operation, ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Temperature Calibration",
ErrorMessage = ex.Message
};
}
}
/// <summary>
/// Creates temperature calibration process instance based on current configuration.
/// </summary>
/// <param name="pp">Current process progress context</param>
/// <returns>Configured temperature calibration process</returns>
private BaseProcess CreateTemperatureCalibrationProcess(ProcessProgress pp)
{
if (pp.Setting.NumberOfPaths == 1)
{
return new SPTemperatureCalibrationProcess(
"Temperature Calibration Single",
PreAdjustmentControl.StatusPanelItems.TempCal,
PreAdjustmentControl.PredefinedMessages.WaitUntilTemperatureCalibrationFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.TempCalFailed(pp.Setting.Culture),
2 * 60);
}
return new TemperatureCalibrationProcess(
"Temperature Calibration",
PreAdjustmentControl.StatusPanelItems.TempCal,
PreAdjustmentControl.PredefinedMessages.WaitUntilTemperatureCalibrationFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.TempCalFailed(pp.Setting.Culture),
2 * 60);
}
#endregion
#region ================================== PreAdjustmentUI OFFSET TEST process ==================================
public Task<PreadjustmentProcessResult> Preadjustment_OffsetTestAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return GetWorker(slot).RunAsync(
() => Preadjustment_OffsetTest(slot, pp),
token);
}
public PreadjustmentProcessResult Preadjustment_OffsetTest(
int slot,
ProcessProgress pp)
{
const string operation =
nameof(Preadjustment_OffsetTest);
try
{
LogInfo(operation, $"Start. Slot={slot}");
var meter =
GetMeterThreadSafe(slot);
EnsureConnected(meter);
if (pp.Setting.TempOnly)
{
return new PreadjustmentProcessResult
{
Success = true,
Slot = slot,
ProcessName = "Offset Test"
};
}
BaseProcess process =
CreateOffsetTestProcess(pp);
bool success =
ExecuteProcess(process, pp);
var result =
new PreadjustmentProcessResult
{
Success = success,
Slot = slot,
ProcessName = process.ProcessName,
ErrorMessage = success
? null
: process.FailedMessage
};
LogInfo(operation, result.ToString());
return result;
}
catch (Exception ex)
{
LogError(operation, ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Offset Test",
ErrorMessage = ex.Message
};
}
}
/// <summary>
/// Creates offset test process instance based on current configuration.
/// </summary>
/// <param name="pp">Current process progress context</param>
/// <returns>Configured offset test process</returns>
private BaseProcess CreateOffsetTestProcess(ProcessProgress pp)
{
if (pp.Setting.NumberOfPaths == 1)
{
return new SPOffsetTestProcess(
"Offset Test Single",
PreAdjustmentControl.StatusPanelItems.Offset,
PreAdjustmentControl.PredefinedMessages.WaitUntilZeroflowOffsetTestFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.ZeroflowOffsetTestFailed(pp.Setting.Culture),
18 * 60);
}
return new OffsetTestProcess(
"Offset Test",
PreAdjustmentControl.StatusPanelItems.Offset,
PreAdjustmentControl.PredefinedMessages.WaitUntilZeroflowOffsetTestFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.ZeroflowOffsetTestFailed(pp.Setting.Culture),
18 * 60);
}
#endregion
#region ================================== PreAdjustmentUI COMPLETION process ==================================
public Task<PreadjustmentProcessResult> Preadjustment_CompletionAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return GetWorker(slot).RunAsync(
() => Preadjustment_Completion(slot, pp),
token);
}
public PreadjustmentProcessResult Preadjustment_Completion(
int slot,
ProcessProgress pp)
{
const string operation =
nameof(Preadjustment_Completion);
try
{
LogInfo(operation, $"Start. Slot={slot}");
var meter =
GetMeterThreadSafe(slot);
EnsureConnected(meter);
BaseProcess process =
CreateCompletionProcess(pp);
bool success =
ExecuteProcess(process, pp);
var result =
new PreadjustmentProcessResult
{
Success = success,
Slot = slot,
ProcessName = process.ProcessName,
ErrorMessage = success
? null
: process.FailedMessage
};
LogInfo(operation, result.ToString());
return result;
}
catch (Exception ex)
{
LogError(operation, ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Completion",
ErrorMessage = ex.Message
};
}
}
/// <summary>
/// Creates completion process instance based on current configuration.
/// </summary>
/// <param name="pp">Current process progress context</param>
/// <returns>Configured completion process</returns>
private BaseProcess CreateCompletionProcess(ProcessProgress pp)
{
if (pp.Setting.NumberOfPaths == 1)
{
return new SPCompletionProcess(
"Completion Single",
PreAdjustmentControl.StatusPanelItems.Completion,
PreAdjustmentControl.PredefinedMessages.WaitUntilCompletionFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.CompletionFailed(pp.Setting.Culture),
1 * 60);
}
return new CompletionProcess(
"Completion",
PreAdjustmentControl.StatusPanelItems.Completion,
PreAdjustmentControl.PredefinedMessages.WaitUntilCompletionFinished(pp.Setting.Culture),
PreAdjustmentControl.PredefinedMessages.CompletionFailed(pp.Setting.Culture),
1 * 60);
}
#endregion
#region ================================== PreAdjustmentUI ExecuteProcess ==================================
private bool ExecuteProcess(
BaseProcess process,
ProcessProgress pp)
{
pp.IsBusy = true;
process.StartProcess(
pp,
_meterControls,
_tempMeterControls);
while (pp.IsBusy && !pp.StopSequence)
{
Thread.Sleep(50);
}
foreach (var meterCtrl in _meterControls)
{
if (meterCtrl.IsEnabled && meterCtrl.Failed)
{
pp.GenerateReturnNote(process.FailedMessage, meterCtrl);
meterCtrl.IsEnabled = false;
}
}
if (pp.StopSequence)
return false;
return _meterControls.Any(m => m.IsEnabled && !m.Failed);
}
#endregion
}
}

View File

@ -1,8 +1,12 @@
using System;
using CordonelPreadjustmentUi;
using CordonelPreadjustmentUi.Processes.Itinerary;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
using Xylem.Common.Ui.CordonelPreadjustmentUi;
using static GenesisCordonelInterface.API.PublicModels;
namespace GenesisCordonelInterface.API
@ -22,6 +26,8 @@ namespace GenesisCordonelInterface.API
_innerMeterAPI = new InterfaceGCIToLaatzen();
}
//
#region ================================== PORT DETECTION ==================================
public PortDetectionResult DetectStreamingPort(int slot)
@ -424,7 +430,6 @@ namespace GenesisCordonelInterface.API
#endregion
#region ================================== METER BATCH SETUP ==================================
// ----------------------------------------------------
public void ReloadSlotSetup()
{
@ -438,12 +443,63 @@ namespace GenesisCordonelInterface.API
RaiseMeterBatchStatusChanged();
}
// ----------------------------------------------------
#endregion
#region ================================== Register names ==================================
public List<string> GetAllRegisterNames()
{
return _innerMeterAPI.GetAllRegisterNames();
}
#endregion
// Preadjustment
public Task<PreadjustmentDetectResult> Preadjustment_DetectAsync(
CancellationToken token = default)
{
return _innerMeterAPI.Preadjustment_DetectAsync(token);
}
public Task<PreadjustmentProcessResult> Preadjustment_PreparationAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return _innerMeterAPI.Preadjustment_PreparationAsync(slot, pp, token);
}
public Task<PreadjustmentProcessResult> Preadjustment_AmplitudeTestAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return _innerMeterAPI.Preadjustment_AmplitudeTestAsync(slot, pp, token);
}
public Task<PreadjustmentProcessResult> Preadjustment_TemperatureCalibrationAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return _innerMeterAPI.Preadjustment_TemperatureCalibrationAsync(slot, pp, token);
}
public Task<PreadjustmentProcessResult> Preadjustment_OffsetTestAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return _innerMeterAPI.Preadjustment_OffsetTestAsync(slot, pp, token);
}
public Task<PreadjustmentProcessResult> Preadjustment_CompletionAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
return _innerMeterAPI.Preadjustment_CompletionAsync(slot, pp, token);
}
}
}

View File

@ -440,6 +440,42 @@ namespace GenesisCordonelInterface.API
Message);
}
}
public class PreadjustmentProcessResult
{
public bool Success { get; set; }
public int Slot { get; set; }
public string ProcessName { get; set; }
public string ErrorMessage { get; set; }
/// <inheritdoc />
public override string ToString()
{
return
$"Success={Success}, " +
$"Slot={Slot}, " +
$"Process={ProcessName}, " +
$"Error={ErrorMessage ?? "None"}";
}
}
public class PreadjustmentDetectResult
{
public bool Success { get; set; }
public int DetectedMeterCount { get; set; }
public int DetectedThermometerCount { get; set; }
public string ErrorMessage { get; set; }
/// <inheritdoc />
public override string ToString()
{
return
$"Success={Success}, " +
$"Meters={DetectedMeterCount}, " +
$"Thermometers={DetectedThermometerCount}, " +
$"Error={ErrorMessage ?? "None"}";
}
}
#endregion
}
}

View File

@ -25,6 +25,15 @@ namespace GenesisCordonelInterface.Core.Threading
public static class RetryWorker
{
/// <summary>
/// Executes an asynchronous operation with retry and timeout protection.
///
/// Important:
/// The timeout here protects the caller from waiting forever, but it does not forcibly abort
/// the underlying hardware operation. Because hardware/COM calls may continue running after
/// the timeout signal, this method waits for the original action to finish before starting
/// the next retry. This prevents overlapping COM requests on the same device.
/// </summary>
public static async Task<RetryResult<T>> RunWithRetryAsync<T>(
Func<Task<T>> action,
Func<T, bool> isSuccess,
@ -41,21 +50,53 @@ namespace GenesisCordonelInterface.Core.Threading
for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
var actionTask = action();
var timeoutTask = Task.Delay(timeoutMs);
Task<T> actionTask = null;
var completedTask = await Task.WhenAny(actionTask, timeoutTask);
if (completedTask == timeoutTask)
try
{
timedOut = true;
log?.Invoke($"{operationName} timeout attempt {attempt}/{maxAttempts}");
}
else
{
lastResult = await actionTask;
log?.Invoke($"{operationName} started. Attempt {attempt}/{maxAttempts}");
if (isSuccess(lastResult))
// Start real operation, for example Connect/GetPcbId/Login.
actionTask = action();
// Start independent timeout timer.
var timeoutTask = Task.Delay(timeoutMs);
// Wait until either operation completes or timeout expires.
var completedTask = await Task.WhenAny(actionTask, timeoutTask)
.ConfigureAwait(false);
if (completedTask == timeoutTask)
{
timedOut = true;
log?.Invoke(
$"{operationName} timed out. Attempt {attempt}/{maxAttempts}. " +
"Waiting for the running operation to finish before retry.");
// Critical part:
// Do NOT immediately start another retry.
// The hardware operation may still be active in ApiWorker.
// Starting another attempt immediately could corrupt communication.
try
{
lastResult = await actionTask.ConfigureAwait(false);
}
catch (Exception ex)
{
log?.Invoke(
$"{operationName} finished after timeout with exception: " +
$"{ex.GetType().Name}: {ex.Message}");
}
}
else
{
// Operation completed before timeout.
lastResult = await actionTask.ConfigureAwait(false);
}
// Decide whether the returned result means success.
if (lastResult != null && isSuccess(lastResult))
{
return new RetryResult<T>
{
@ -63,15 +104,29 @@ namespace GenesisCordonelInterface.Core.Threading
Success = true,
Attempts = attempt,
Duration = DateTime.Now - started,
TimedOut = false
TimedOut = timedOut
};
}
logResult?.Invoke($"{operationName} failed attempt {attempt}/{maxAttempts}", lastResult);
logResult?.Invoke(
$"{operationName} failed. Attempt {attempt}/{maxAttempts}",
lastResult);
}
catch (Exception ex)
{
// Covers exceptions thrown before timeout handling or by action startup.
log?.Invoke(
$"{operationName} exception on attempt {attempt}/{maxAttempts}: " +
$"{ex.GetType().Name}: {ex.Message}");
}
// Delay before next retry, except after the final attempt.
if (attempt < maxAttempts)
await Task.Delay(delayMs);
{
log?.Invoke($"{operationName} waiting {delayMs} ms before retry.");
await Task.Delay(delayMs).ConfigureAwait(false);
}
}
return new RetryResult<T>

View File

@ -81,9 +81,6 @@
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.Registers">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.Registers.dll</HintPath>
</Reference>
@ -250,6 +247,10 @@
<WCFMetadata Include="Connected Services\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ExternalProjects\Laatzen\Genesis\Common\Hardware\WaterMeter\Genesis\GenesisCore\GenesisCore.csproj">
<Project>{04201E95-90A0-4B73-A72F-379739B2A3AE}</Project>
<Name>GenesisCore</Name>
</ProjectReference>
<ProjectReference Include="..\ExternalProjects\Laatzen\Genesis\Common\CordonelPreadjustmentUi\CordonelPreadjustmentUi.csproj">
<Project>{D0C8D887-ED52-40AB-A069-90BCE0E801E2}</Project>
<Name>CordonelPreadjustmentUi</Name>

View File

@ -4,21 +4,33 @@ using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xylem.Common.CommonCore.Consts;
using Xylem.Common.Hardware.Interfaces.Ports.PortCore;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
using Xylem.Common.Ui.CordonelPreadjustmentUi;
using CordonelPreadjustmentUi;
using static Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.GenesisMeter;
using System.Linq;//...MF
namespace GenesisCordonelInterface.UI.LaatzenAPI_CordonelPreadjustmentUI
{
public partial class FrmCordonelPreadjustmentUI : Form
{
private PreAdjustmentControl preadjustCtl;
public PreAdjustmentControl preadjustCtl;//...MF
private PreAdjustmentSettingsContainer mainSettings = new PreAdjustmentSettingsContainer();
public MeterBatch _externMetersBatch;
public FrmCordonelPreadjustmentUI()
{
}
public FrmCordonelPreadjustmentUI(MeterBatch externMetersBatch)
{
_externMetersBatch = externMetersBatch;
InitializeComponent();
}
@ -26,7 +38,7 @@ namespace GenesisCordonelInterface.UI.LaatzenAPI_CordonelPreadjustmentUI
{
preadjustCtl = new PreAdjustmentControl(mainSettings);
preadjustCtl = new PreAdjustmentControl(mainSettings, _externMetersBatch);
tab_ZeroFlowCal.Controls.Add(preadjustCtl);
@ -68,7 +80,7 @@ namespace GenesisCordonelInterface.UI.LaatzenAPI_CordonelPreadjustmentUI
{
if (e.TabPage.Name == tab_ZeroFlowCal.Name)
{
try
/*try
{
var _serialConfigFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Genesis", ProgramConfig.SerialConfigFileName);
@ -96,11 +108,81 @@ namespace GenesisCordonelInterface.UI.LaatzenAPI_CordonelPreadjustmentUI
catch (Exception ex)
{
MessageBox.Show($"use default meters because of {ex.Message}");
}*/
try //...MF
{
mainSettings.Meters = new List<int>();
mainSettings.TempMeters = new List<int>();
// ==========================================
// Try loading configuration from GCI meters
// ==========================================
bool loadedFromInterface = false;
if (_externMetersBatch != null &&
_externMetersBatch.ListOfMeters.Any())
{
foreach (GenesisMeter meter in _externMetersBatch.ListOfMeters)
{
// Skip meters that should use file configuration
if (meter.useConfigSource != ConfigSource.InterfaceInputConfig)
continue;
loadedFromInterface = true;
// Split normal and temperature meters
//if (meter.Type == SlotType.TemperatureMeter)
//{
// mainSettings.TempMeters.Add(meter.Slot);
//}
//else
//{
mainSettings.Meters.Add(meter.Slot);
//}
}
}
// ==========================================
// Fallback to configuration file
// ==========================================
if (!loadedFromInterface)
{
var _serialConfigFile =
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Genesis",
ProgramConfig.SerialConfigFileName);
SlotConfig[] meterConfigList;
using (var tr = new StreamReader(_serialConfigFile))
{
var _fileString = tr.ReadToEnd();
meterConfigList =
JsonConvert.DeserializeObject<SlotConfig[]>(_fileString);
}
foreach (var item in meterConfigList)
{
if (item.Type != SlotType.TemperatureMeter)
{
mainSettings.Meters.Add(item.Slot);
}
else
{
mainSettings.TempMeters.Add(item.Slot);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Use default meters because of {ex.Message}");
}
mainSettings.NumberOfPaths = cB_SinglePath.Checked ? 1 : 3;
mainSettings.LowerTempLimit = (double)nUD_SettingsTempMonitorLowerValue.Value;
@ -153,7 +235,7 @@ namespace GenesisCordonelInterface.UI.LaatzenAPI_CordonelPreadjustmentUI
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
/*private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (preadjustCtl != null)
{
@ -174,7 +256,68 @@ namespace GenesisCordonelInterface.UI.LaatzenAPI_CordonelPreadjustmentUI
}
}*/
/// <summary>
/// Raised when user closes the preadjustment window
/// using the window close button (X).
///
/// Note:
/// Form is hidden, not disposed.
/// This event allows external code to continue
/// workflow asynchronously.
/// </summary>
public event EventHandler OnUserClosed;
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
// User clicked X button - hide form only
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
this.Hide();
OnUserClosed?.Invoke(this, EventArgs.Empty);
return;
}
// Real application shutdown / dispose
DisposeResources();
}
/// <summary>
/// Dispose all internal resources that should
/// only be released during real application shutdown.
///
/// Do not call when form is hidden.
/// </summary>
private void DisposeResources()
{
if (preadjustCtl != null)
{
preadjustCtl.CloseConnections();
preadjustCtl.Dispose();
preadjustCtl = null;
}
if (ThermoMeterBatch != null)
{
ThermoMeterBatch.Dispose();
ThermoMeterBatch = null;
}
if (TempMeterStateCtls != null)
{
foreach (var item in TempMeterStateCtls)
{
item.Dispose();
}
TempMeterStateCtls.Clear();
TempMeterStateCtls = null;
}
}
private MeterBatch ThermoMeterBatch = new MeterBatch();
private List<MeterStateControl> TempMeterStateCtls = new List<MeterStateControl>();
private void tmpStart(int slot, bool RaspiMode = false)

View File

@ -1,4 +1,5 @@
using CordonelPreadjustmentUi.Processes;
using CordonelPreadjustmentUi;
using CordonelPreadjustmentUi.Processes;
using CordonelPreadjustmentUi.Processes.Actions;
using CordonelPreadjustmentUi.Processes.Itinerary;
using System;
@ -6,16 +7,18 @@ using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore.Consts;
using Xylem.Common.Logic.ProductionOrderCore.OrderData;
using Xylem.Common.Ui.CordonelPreadjustmentUi;
using Xylem.Common.Ui.CordonelPreadjustmentUi.Parameters;
using CordonelPreadjustmentUi;
using static Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.GenesisMeter;
namespace GenesisCordonelInterface.UI
{
@ -41,11 +44,18 @@ namespace GenesisCordonelInterface.UI
private Boolean abortIndicator = false;
public Boolean AbortIndicator { get { return abortIndicator; } set { abortIndicator = value; } }
public int TestRunNumber;
public PreAdjustmentControl(PreAdjustmentSettingsContainer Settings = null)
public PreAdjustmentControl(PreAdjustmentSettingsContainer Settings = null, MeterBatch externalMetersBatch = null)//...MF
{
InitializeComponent();
SetSettings(Settings);
rTB_ZeroFlowCal.AutoSize = true;
//...MF
// Use external batch only if supplied
if (externalMetersBatch != null)
{
GlobalMeterBatch = externalMetersBatch;
}
}
public void SetSettings(PreAdjustmentSettingsContainer Settings = null)
{
@ -120,6 +130,49 @@ namespace GenesisCordonelInterface.UI
}
cb_Metersize.SelectedItem = setM;
//...MF
// Create UI controls for configured meter slots.
//
// Flow:
//
// settings.Meters
// ↓
// create MeterStateControl
// ↓
// position control in UI
// ↓
// check whether slot exists in externally supplied MeterBatch
// ↓
// automatically enable corresponding checkbox
// ↓
// register UI events
// ↓
// add control into internal collection and group box
//
// Notes:
// - allows external GCI workflow to preselect meters
// - keeps UI synchronized with externally injected MeterBatch
// - slots contained in GlobalMeterBatch are automatically checked
//
foreach (var Meter in settings.Meters)
{
var ctl = new MeterStateControl(Meter);
ctl.Location = new Point(5 + ((tmpI - 1) * ctl.Width), 15);
// Check meter if it exists in external MeterBatch
if (GlobalMeterBatch != null &&
GlobalMeterBatch.ListOfMeters != null &&
GlobalMeterBatch.ListOfMeters.Any(m => m.Slot == Meter))
{
ctl.SetChecked(true);
}
MeterStateCtls.Add(ctl);
gB_Meters.Controls.Add(ctl);
ctl.OnRequestDetails += Ctl_MouseEnter;
tmpI = tmpI + 1;
}
}
}
@ -1694,13 +1747,46 @@ namespace GenesisCordonelInterface.UI
List<IProcess> listOfProgrammParts = new List<IProcess>();
//...MF
bool requiresInternalLoginFlow = true;
requiresInternalLoginFlow =
GlobalMeterBatch.ListOfMeters.All(
m =>
{
var meter = m as GenesisMeter;
return meter == null ||
meter.usePasswordSource !=
PasswordSource.InterfaceInputPassword;
});
listOfProgrammParts.Add(new PrepareTestProcess("PrepareTest", CordonelPreadjustmentUi.PreAdjustmentControl.StatusPanelItems.Detect, string.Empty, string.Empty, 1 * 60));
//...MF
bool requiresInternalConfigFlow = true;
requiresInternalConfigFlow =
GlobalMeterBatch.ListOfMeters.All(
m =>
{
var meter = m as GenesisMeter;
listOfProgrammParts.Add(new LoginProcess("Login", CordonelPreadjustmentUi.PreAdjustmentControl.StatusPanelItems.Detect, PredefinedMessages.WaitUntilLoginFinished(pp.Setting.Culture), PredefinedMessages.LoginFailed(pp.Setting.Culture), 1 * 60));
return meter == null ||
meter.useConfigSource !=
ConfigSource.InterfaceInputConfig;
});
listOfProgrammParts.Add(new FlushProcess("First Flush", CordonelPreadjustmentUi.PreAdjustmentControl.StatusPanelItems.Detect, PredefinedMessages.WaitUntilFlushFinished(pp.Setting.Culture), string.Empty, 2 * 60));
if (requiresInternalConfigFlow)//...MF
{
listOfProgrammParts.Add(new PrepareTestProcess("PrepareTest", CordonelPreadjustmentUi.PreAdjustmentControl.StatusPanelItems.Detect, string.Empty, string.Empty, 1 * 60));
}
if (requiresInternalLoginFlow)//...MF
{
listOfProgrammParts.Add(new LoginProcess("Login", CordonelPreadjustmentUi.PreAdjustmentControl.StatusPanelItems.Detect, PredefinedMessages.WaitUntilLoginFinished(pp.Setting.Culture), PredefinedMessages.LoginFailed(pp.Setting.Culture), 1 * 60));
}
if (requiresInternalConfigFlow)//...MF
{
listOfProgrammParts.Add(new FlushProcess("First Flush", CordonelPreadjustmentUi.PreAdjustmentControl.StatusPanelItems.Detect, PredefinedMessages.WaitUntilFlushFinished(pp.Setting.Culture), string.Empty, 2 * 60));
}
//listOfProgrammParts.Add(new PressureTestProcess("PreussureTest", StatusPanelItems.Prepare, PredefinedMessages.WaitUntilPreparationFinished(pp.Setting.Culture), PredefinedMessages.PreparationFailed(pp.Setting.Culture), 1 * 60));

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ClassLibrary1</RootNamespace>
<AssemblyName>GraphLib</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
@ -115,4 +115,4 @@
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LabelPrinting</RootNamespace>
<AssemblyName>LabelPrinting</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -174,4 +174,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MergeResultsDBs</RootNamespace>
<AssemblyName>MergeResultsDBs</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -82,4 +82,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OrderManagement</RootNamespace>
<AssemblyName>OrderManagement</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -179,4 +179,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ProductionTracing</RootNamespace>
<AssemblyName>ProductionTracing</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -204,4 +204,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RecordProcessing</RootNamespace>
<AssemblyName>RFPowerCommon</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -81,4 +81,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ResetBatchNr</RootNamespace>
<AssemblyName>ResetBatchNr</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -66,4 +66,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?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>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RestClient</RootNamespace>
<AssemblyName>RestClient</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -56,4 +56,4 @@
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
</Project>

View File

@ -108,7 +108,11 @@ namespace Results
throw new Exception("Connection string was not specified");
}
if (SessionFactory == null) SessionFactory = CreateSessionFactory();
if (SessionFactory == null)
{
DatabaseMigrationHelper.EnsureSchema(dbType, connectionString);
SessionFactory = CreateSessionFactory();
}
return SessionFactory.OpenSession();
}
@ -303,38 +307,45 @@ namespace Results
{
bool hasCalibrationFactors = false;
foreach (var tstRslt in batch.TestRslts)
try
{
if (tstRslt.CalibFactorResultsToSave != null &&
tstRslt.CalibFactorResultsToSave.Count > 0)
{
hasCalibrationFactors = true;
break;
}
}
if (hasCalibrationFactors)
{
TestRsltCalibFactorHelper.CreateTableIfNotExists(session);
foreach (var tstRslt in batch.TestRslts)
{
if (tstRslt.CalibFactorResultsToSave == null ||
tstRslt.CalibFactorResultsToSave.Count == 0)
if (tstRslt.CalibFactorResultsToSave != null &&
tstRslt.CalibFactorResultsToSave.Count > 0)
{
continue;
}
TestRsltCalibFactorHelper.DeleteByTestRsltIdNoTransaction(session, tstRslt.Id);
foreach (var calib in tstRslt.CalibFactorResultsToSave)
{
calib.TestRslt = tstRslt;
calib.ErrorStr = TestRsltCalibFactorHelper.Truncate(calib.ErrorStr, 240);
session.SaveOrUpdate(calib);
hasCalibrationFactors = true;
break;
}
}
if (hasCalibrationFactors)
{
TestRsltCalibFactorHelper.CreateTableIfNotExists(session);
foreach (var tstRslt in batch.TestRslts)
{
if (tstRslt.CalibFactorResultsToSave == null ||
tstRslt.CalibFactorResultsToSave.Count == 0)
{
continue;
}
TestRsltCalibFactorHelper.DeleteByTestRsltIdNoTransaction(session, tstRslt.Id);
foreach (var calib in tstRslt.CalibFactorResultsToSave)
{
calib.TestRslt = tstRslt;
calib.ErrorStr = TestRsltCalibFactorHelper.Truncate(calib.ErrorStr, 240);
session.SaveOrUpdate(calib);
}
}
}
}catch(Exception exc)
{
log.ErrorFormat("DB - Cannot save calibration factors: {0}", exc.Message);
}
}

View File

@ -58,7 +58,11 @@ namespace Results.Entities
#endif
public virtual WaterMeter WaterMeter { get; set; } /// reference to the WaterMeter entity
public virtual TestRslt TestRslt { get; set; } /// reference to the TestRslt entity
public virtual TestRslt TestRslt { get; set; }
/// reference to the TestRslt entity
public virtual int Q3Channel { get; set; }
/// Wrappers
public virtual string Name() { return TestRslt.Name(); }
@ -97,6 +101,7 @@ namespace Results.Entities
public virtual WaterMeterData WaterMeterData() { return WaterMeter.WaterMeterData; }
public virtual Batch Batch() { return WaterMeter.Batch; }
public virtual bool IsPilotRslt()
{

View File

@ -8,6 +8,8 @@ namespace Results.Entities
public virtual int CalibFactorIndex { get; set; } // 1, 2, 3
public virtual bool IsCalibFactorValid { get; set; }
public virtual int BaseCalibFactor { get; set; }
public virtual int CalculatedCalibFactor { get; set; }
@ -29,6 +31,7 @@ namespace Results.Entities
{
Stored = false;
ErrorStr = string.Empty;
IsCalibFactorValid = false;
}
}
}

View File

@ -110,6 +110,9 @@ namespace Results.Entities
public virtual string Workflow { get; set; } /// Not mapped to DB !!! Production tracing workflow name
public virtual bool LastRecordIsNok { get; set; } /// Not mapped to DB !!! Previous record verification result
public virtual bool PrintLabel { get; set; } /// Not mapped to DB !!!
/// mapped to DB !!! Q3 channel number
public virtual int Q3Channel { get; set; }
public virtual WaterMeterData WaterMeterData { get; set; }
public virtual Batch Batch { get; set; }
@ -493,6 +496,7 @@ namespace Results.Entities
FWVersion = string.Empty;
#endif
PrintLabel = true;
Q3Channel = 0; //No Q3 calibration by default
}
@ -556,7 +560,8 @@ namespace Results.Entities
Workflow = src.Workflow; /// Not mapped to DB
LastRecordIsNok = src.LastRecordIsNok; /// Not mapped to DB
PrintLabel = src.PrintLabel; /// Not mapped to DB
Q3Channel = src.Q3Channel; /// Mapped to DB
foreach (var mtr in MeterTestRslts)
{
MeterTestRslt srcMtr = src.GetMeterTestRslt(mtr.Name(), (CompoundMeterId)mtr.CompoundMeterId);
@ -771,6 +776,10 @@ namespace Results.Entities
{
MeterTestRslts[i].WriteBinary(writer);
}
//New Q3 calibration adds
writer.Write(2);//version number
writer.Write(Q3Channel);
}
public virtual void ReadBinary(BinaryReader reader, IList<WaterMeterData> wmDatasRetrievedSoFar, IList<TestRslt> testRslts)
@ -879,6 +888,13 @@ namespace Results.Entities
mtr.ReadBinary(reader, testRslts);
MeterTestRslts.Add(mtr);
}
//New Q3 calibration adds
int version = reader.ReadInt32();
if (version == 2)
{
Q3Channel = reader.ReadInt32();
}
}
}
}

View File

@ -51,6 +51,7 @@ namespace Results.Entities
public virtual bool Compound { get; set; }
public virtual bool HeatMeter { get; set; }
public virtual int WMTypeId { get; set; } /// Mapped to DB only when ORACLE_DB is defined
public virtual int Q3Channel { get; set; } /// Q3 Channel = 0 no set > 0 is Q3 calibration
/// <summary>
/// Default constructor, safe values
@ -59,6 +60,7 @@ namespace Results.Entities
{
PulsesPerLtr = 1;
PulsesPerLtrAux = 1;
Q3Channel = 0;
}
/// <summary>
@ -101,6 +103,7 @@ namespace Results.Entities
Compound = oriWMData.Compound;
HeatMeter = oriWMData.HeatMeter;
WMTypeId = oriWMData.WMTypeId;
Q3Channel = oriWMData.Q3Channel;
}
@ -146,6 +149,7 @@ namespace Results.Entities
if (Compound != wmd.Compound) return false;
if (HeatMeter != wmd.HeatMeter) return false;
if (WMTypeId != wmd.WMTypeId) return false;
if (Q3Channel != wmd.Q3Channel) return false;
return true;
}
@ -206,6 +210,8 @@ namespace Results.Entities
writer.Write(Compound);
writer.Write(HeatMeter);
writer.Write(WMTypeId);
writer.Write(2); //Version of the binary format
writer.Write(Q3Channel);
}
public virtual void ReadBinary(BinaryReader reader)
@ -246,6 +252,15 @@ namespace Results.Entities
Compound = reader.ReadBoolean();
HeatMeter = reader.ReadBoolean();
WMTypeId = reader.ReadInt32();
//Version 2 of the binary format introduced Q3Channel
int Version = 0;
Q3Channel = 0;
try { Version = reader.ReadInt32(); }catch(Exception) { Version = 0; }
if (Version == 2)
{
try { Q3Channel = reader.ReadInt32(); } catch (Exception) { Q3Channel = 0; }
}
}
}
}

View File

@ -0,0 +1,134 @@
using System;
using MySql.Data.MySqlClient;
using Common;
namespace Results.Entities.helpers
{
public static class DatabaseMigrationHelper
{
public static void EnsureSchema(DBType dbType, string connectionString)
{
switch (dbType)
{
case DBType.MySql:
EnsureMySqlSchema(connectionString);
break;
case DBType.SQLite:
EnsureSQLiteSchema(connectionString);
break;
}
}
private static void EnsureMySqlSchema(string connectionString)
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
EnsureColumnMySql(conn, "WaterMeterData", "Q3Channel", "INT NOT NULL DEFAULT 0");
EnsureColumnMySql(conn, "WaterMeter", "Q3Channel", "INT NOT NULL DEFAULT 0");
EnsureColumnMySql(conn, "MeterTestRslt", "Q3Channel", "INT NOT NULL DEFAULT 0");
}
}
private static void EnsureColumnMySql(
MySqlConnection conn,
string tableName,
string columnName,
string columnDefinition)
{
using (var transaction = conn.BeginTransaction())
{
try
{
bool exists;
using (var cmd = conn.CreateCommand())
{
cmd.Transaction = transaction;
cmd.CommandText = @"
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = @tableName
AND COLUMN_NAME = @columnName";
cmd.Parameters.AddWithValue("@tableName", tableName);
cmd.Parameters.AddWithValue("@columnName", columnName);
exists = Convert.ToInt32(cmd.ExecuteScalar()) > 0;
}
if (!exists)
{
using (var alter = conn.CreateCommand())
{
alter.Transaction = transaction;
alter.CommandText = "ALTER TABLE `" + tableName + "` ADD COLUMN `" + columnName + "` " + columnDefinition;
alter.ExecuteNonQuery();
}
}
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
private static void EnsureSQLiteSchema(string databaseFile)
{
using (var conn = new System.Data.SQLite.SQLiteConnection("Data Source=" + databaseFile))
{
conn.Open();
EnsureColumnSQLite(conn, "WaterMeterData", "Q3Channel", "INTEGER NOT NULL DEFAULT 0");
EnsureColumnSQLite(conn, "WaterMeter", "Q3Channel", "INTEGER NOT NULL DEFAULT 0");
EnsureColumnSQLite(conn, "MeterTestRslt", "Q3Channel", "INTEGER NOT NULL DEFAULT 0");
}
}
private static void EnsureColumnSQLite(
System.Data.SQLite.SQLiteConnection conn,
string tableName,
string columnName,
string columnDefinition)
{
bool exists = false;
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "PRAGMA table_info(" + tableName + ")";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (string.Equals(reader["name"].ToString(), columnName, StringComparison.OrdinalIgnoreCase))
{
exists = true;
break;
}
}
}
}
if (!exists)
{
using (var alter = conn.CreateCommand())
{
alter.CommandText =
"ALTER TABLE " + tableName + " ADD COLUMN " + columnName + " " + columnDefinition;
alter.ExecuteNonQuery();
}
}
}
}
}

View File

@ -1,10 +1,14 @@
using System.Collections.Generic;
using log4net;
using NHibernate;
namespace Results.Entities.helpers
{
public static class TestRsltCalibFactorHelper
{
private static readonly ILog log = LogManager.GetLogger(typeof(TestRsltCalibFactorHelper));
public static bool TableExists(ISession session)
{
try
@ -24,6 +28,7 @@ namespace Results.Entities.helpers
ISession session,
int testRsltId)
{
log.DebugFormat("Deleting TestRsltCalibFactor records for TestRsltId: {0}", testRsltId);
session.CreateSQLQuery(@" DELETE FROM TestRsltCalibFactor WHERE TestRsltId = :testRsltId")
.SetParameter("testRsltId", testRsltId)
.ExecuteUpdate();
@ -65,6 +70,7 @@ CREATE TABLE IF NOT EXISTS TestRsltCalibFactor (
CalibFactorIndex INT NOT NULL,
BaseCalibFactor INT NOT NULL,
CalculatedCalibFactor INT NOT NULL,
IsCalibFactorValid BIT NOT NULL,
Stored BIT NOT NULL,
ErrorStr VARCHAR(240) NULL,
TimeStart DOUBLE NOT NULL,
@ -90,6 +96,7 @@ CREATE TABLE IF NOT EXISTS TestRsltCalibFactor (
CalibFactorIndex INTEGER NOT NULL,
BaseCalibFactor INTEGER NOT NULL,
CalculatedCalibFactor INTEGER NOT NULL,
IsCalibFactorValid INTEGER NOT NULL,
Stored INTEGER NOT NULL,
ErrorStr VARCHAR(240) NULL,
TimeStart DOUBLE NOT NULL,
@ -103,6 +110,7 @@ CREATE TABLE IF NOT EXISTS TestRsltCalibFactor (
);";
}
log.InfoFormat("Creating TestRsltCalibFactor table: {0}", sql);
session.CreateSQLQuery(sql).ExecuteUpdate();
}
}

View File

@ -49,6 +49,7 @@ namespace Results.Mappings
#endif
References(x => x.WaterMeter);
References(x => x.TestRslt);
Map(x => x.Q3Channel);
}
}
}

View File

@ -14,6 +14,7 @@ namespace Results.Mappings
.Not.Nullable();
Map(x => x.CalibFactorIndex).Not.Nullable();
Map(x => x.IsCalibFactorValid).Not.Nullable();
Map(x => x.BaseCalibFactor).Not.Nullable();
Map(x => x.CalculatedCalibFactor).Not.Nullable();

View File

@ -58,6 +58,8 @@ namespace Results.Mappings
#if ORACLE_DB
Map(x => x.WMTypeId);
#endif
}
Map(x => x.Q3Channel);
}
}
}

View File

@ -65,6 +65,7 @@ namespace Results.Mappings
Map(x => x.Pruefindex);
Map(x => x.HydrPruefung);
#endif
Map(x => x.Q3Channel);// Genesis meter identification
References(x => x.WaterMeterData);
References(x => x.Batch);
HasMany(x => x.MeterTestRslts)

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Results</RootNamespace>
<AssemblyName>Results</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -53,6 +53,9 @@
<Reference Include="NHibernate">
<HintPath>..\packages\NHibernate.4.0.4.4000\lib\net40\NHibernate.dll</HintPath>
</Reference>
<Reference Include="System.Data.SQLite, Version=2.0.3.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\System.Data.SQLite.2.0.3\lib\net471\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
@ -69,6 +72,7 @@
<Compile Include="DBase.cs" />
<Compile Include="Entities\Batch.cs" />
<Compile Include="Entities\Components.cs" />
<Compile Include="Entities\helpers\DatabaseMigrationHelper.cs" />
<Compile Include="Entities\helpers\TestRsltCalibFactorHelper.cs" />
<Compile Include="Entities\MeterTestCalibFactorRslt.cs" />
<Compile Include="Entities\MeterTestRslt.cs" />
@ -271,4 +275,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ResultsBrowser</RootNamespace>
<AssemblyName>ResultsBrowser</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -327,4 +327,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>S640TestApp</RootNamespace>
<AssemblyName>S640TestApp</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SchematicDrawing</RootNamespace>
<AssemblyName>SchematicDrawing</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -217,4 +217,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SharedDatabase</RootNamespace>
<AssemblyName>SharedDatabase</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
@ -232,4 +232,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Statistics</RootNamespace>
<AssemblyName>Statistics</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -146,4 +146,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// Build Number
// Revision
//
[assembly: AssemblyVersion("3.9.3109.1")]
[assembly: AssemblyFileVersion("3.9.3109.1")]
[assembly: AssemblyVersion("3.9.3121.1")]
[assembly: AssemblyFileVersion("3.9.3121.1")]

View File

@ -1,4 +1,7 @@
using GenesisCordonelInterface.API;
using CordonelPreadjustmentUi;
using CordonelPreadjustmentUi.Processes.Itinerary;
using GenesisCordonelInterface.API;
using GenesisCordonelInterface.Core.Threading;
using log4net;
///
/// Copyright (c) 2015-2021 Sensus Slovensko a.s.
@ -13,6 +16,9 @@ using TBF.Rig.BridgeComponents.GciBridge.UI;
using TBF.Rig.Generic;
using TBF.Rig.Input.DataStorage.UniDataStorageReader;
using TBF.Rig.Input.DataStorage.UniDataStorageReader.Searching.Database;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
using Xylem.Common.Ui.CordonelPreadjustmentUi;
using static GenesisCordonelInterface.API.PublicModels;
using static TBF.Rig.BridgeComponents.GciBridge.Interfaces.PublicModels;
using GciGUIType = GenesisCordonelInterface.UI.MainView;
using GciPublicModels = GenesisCordonelInterface.API.PublicModels;
@ -20,7 +26,6 @@ using GciType = GenesisCordonelInterface.API.InterfaceOutsideToGCI;
using UdsReaderType = TBF.Rig.Input.DataStorage.UniDataStorageReader.Reader;
using UDSRPublicModels = TBF.Rig.Input.DataStorage.UniDataStorageReader.Interfaces.PublicModels;
using UdsWriterType = TBF.Rig.Output.DataStorage.UniDataStorageWriter.Writer;
using GenesisCordonelInterface.Core.Threading;
namespace TBF.Rig.BridgeComponents.GciBridge
{
@ -47,8 +52,8 @@ namespace TBF.Rig.BridgeComponents.GciBridge
Form gciGuiHostForm;
//diag GUI for GciBridge
public UserControl gciBridgeGUI;
public MainForm gciBridgeGuiForm;
public UserControl gciBridgeGUIUserControl;
public UI.MainForm gciBridgeGuiForm;
public GciType gciExternalInterface;
@ -119,7 +124,7 @@ namespace TBF.Rig.BridgeComponents.GciBridge
if (gciBridgeGuiForm != null && !gciBridgeGuiForm.IsDisposed)
return;
gciBridgeGuiForm = new MainForm(this);
gciBridgeGuiForm = new UI.MainForm(this);
gciBridgeGuiForm.Text = "Gci Bridge GUI";
gciBridgeGuiForm.Width = 1300;
gciBridgeGuiForm.Height = 600;
@ -1453,6 +1458,334 @@ namespace TBF.Rig.BridgeComponents.GciBridge
#endregion
// Preadjustment API:
#region ================================== Preadjustment DETECT bridge ==================================
public async Task<PreadjustmentDetectResult> Preadjustment_DetectAsync(
CancellationToken token = default)
{
const string operation = nameof(Preadjustment_DetectAsync);
try
{
EnsureExternalInterface();
log.InfoFormat("{0}: {1} Start.", Name, operation);
PreadjustmentDetectResult result =
await gciExternalInterface
.Preadjustment_DetectAsync(token)
.ConfigureAwait(false);
log.InfoFormat(
"{0}: {1} Finish. {2}",
Name,
operation,
result);
return result;
}
catch (Exception ex)
{
log.Error(
string.Format("{0}: {1} failed.", Name, operation),
ex);
return new PreadjustmentDetectResult
{
Success = false,
ErrorMessage = ex.Message
};
}
}
#endregion
#region ================================== PreAdjustment PREPARATION bridge ==================================
public async Task<PreadjustmentProcessResult> Preadjustment_PreparationAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
const string operation = nameof(Preadjustment_PreparationAsync);
try
{
EnsureExternalInterface();
if (pp == null)
throw new ArgumentNullException(nameof(pp));
log.InfoFormat(
"{0}: {1} Start. Slot={2}",
Name,
operation,
slot);
PreadjustmentProcessResult result =
await gciExternalInterface
.Preadjustment_PreparationAsync(
slot,
pp,
token)
.ConfigureAwait(false);
log.InfoFormat(
"{0}: {1} Finish. {2}",
Name,
operation,
result);
return result;
}
catch (Exception ex)
{
log.Error(
string.Format("{0}: {1} failed.", Name, operation),
ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Preparation",
ErrorMessage = ex.Message
};
}
}
#endregion
#region ================================== PreAdjustment AMPLITUDE TEST bridge ==================================
public async Task<PreadjustmentProcessResult> Preadjustment_AmplitudeTestAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
const string operation = nameof(Preadjustment_AmplitudeTestAsync);
try
{
EnsureExternalInterface();
if (pp == null)
throw new ArgumentNullException(nameof(pp));
log.InfoFormat(
"{0}: {1} Start. Slot={2}",
Name,
operation,
slot);
PreadjustmentProcessResult result =
await gciExternalInterface
.Preadjustment_AmplitudeTestAsync(
slot,
pp,
token)
.ConfigureAwait(false);
log.InfoFormat(
"{0}: {1} Finish. {2}",
Name,
operation,
result);
return result;
}
catch (Exception ex)
{
log.Error(
string.Format("{0}: {1} failed.", Name, operation),
ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Amplitude Test",
ErrorMessage = ex.Message
};
}
}
#endregion
#region ================================== PreAdjustment TEMPERATURE CALIBRATION bridge ==================================
public async Task<PreadjustmentProcessResult> Preadjustment_TemperatureCalibrationAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
const string operation = nameof(Preadjustment_TemperatureCalibrationAsync);
try
{
EnsureExternalInterface();
if (pp == null)
throw new ArgumentNullException(nameof(pp));
log.InfoFormat(
"{0}: {1} Start. Slot={2}",
Name,
operation,
slot);
PreadjustmentProcessResult result =
await gciExternalInterface
.Preadjustment_TemperatureCalibrationAsync(
slot,
pp,
token)
.ConfigureAwait(false);
log.InfoFormat(
"{0}: {1} Finish. {2}",
Name,
operation,
result);
return result;
}
catch (Exception ex)
{
log.Error(
string.Format("{0}: {1} failed.", Name, operation),
ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Temperature Calibration",
ErrorMessage = ex.Message
};
}
}
#endregion
#region ================================== PreAdjustment OFFSET TEST bridge ==================================
public async Task<PreadjustmentProcessResult> Preadjustment_OffsetTestAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
const string operation = nameof(Preadjustment_OffsetTestAsync);
try
{
EnsureExternalInterface();
if (pp == null)
throw new ArgumentNullException(nameof(pp));
log.InfoFormat(
"{0}: {1} Start. Slot={2}",
Name,
operation,
slot);
PreadjustmentProcessResult result =
await gciExternalInterface
.Preadjustment_OffsetTestAsync(
slot,
pp,
token)
.ConfigureAwait(false);
log.InfoFormat(
"{0}: {1} Finish. {2}",
Name,
operation,
result);
return result;
}
catch (Exception ex)
{
log.Error(
string.Format("{0}: {1} failed.", Name, operation),
ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Offset Test",
ErrorMessage = ex.Message
};
}
}
#endregion
#region ================================== PreAdjustment COMPLETION bridge ==================================
public async Task<PreadjustmentProcessResult> Preadjustment_CompletionAsync(
int slot,
ProcessProgress pp,
CancellationToken token = default)
{
const string operation = nameof(Preadjustment_CompletionAsync);
try
{
EnsureExternalInterface();
if (pp == null)
throw new ArgumentNullException(nameof(pp));
log.InfoFormat(
"{0}: {1} Start. Slot={2}",
Name,
operation,
slot);
PreadjustmentProcessResult result =
await gciExternalInterface
.Preadjustment_CompletionAsync(
slot,
pp,
token)
.ConfigureAwait(false);
log.InfoFormat(
"{0}: {1} Finish. {2}",
Name,
operation,
result);
return result;
}
catch (Exception ex)
{
log.Error(
string.Format("{0}: {1} failed.", Name, operation),
ex);
return new PreadjustmentProcessResult
{
Success = false,
Slot = slot,
ProcessName = "Completion",
ErrorMessage = ex.Message
};
}
}
#endregion
#region ======================================= Helpers =======================================
private UDSRPublicModels.DataQuery CreatePasswordQuery(string pcbId)
{

View File

@ -15,6 +15,7 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.Debug
private MainForm _mainform;
private MainView _mainView;
public Grid.MeterGridManager _gridManager;
public event Action GetMeterRegistersClicked;
private bool isRefreshing;
private List<string> comPorts = new List<string>();
@ -36,6 +37,9 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.Debug
_mainView._gciApi.MeterBatchStatusChanged += Api_MeterBatchStatusChanged; //global event of table
grid.CellContentClick += grid_CellContentClick;
UpdateGrid(_api.GetMeterBatchDebugStatuses());
}
@ -267,8 +271,16 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.Debug
if (columnName == "Selected")
{
bool selected = Convert.ToBoolean(grid.Rows[e.RowIndex].Cells["Selected"].Value);
bool selected =
Convert.ToBoolean(
grid.Rows[e.RowIndex]
.Cells["Selected"]
.Value);
_api.SetSlotSelected(slot, selected);
//SelectedSlotsChanged?.Invoke();
return;
}
@ -302,13 +314,14 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.Debug
if (columnName == "DetectRequest")
{
await DetectRequestPortAsync(slot);
//await DetectRequestPortAsync(slot);
GetMeterRegistersClicked?.Invoke();
return;
}
if (columnName == "DetectStreaming")
{
await DetectStreamingPortAsync(slot);
//await DetectStreamingPortAsync(slot);
return;
}
}

View File

@ -1,4 +1,5 @@
using System;
using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

View File

@ -25,7 +25,7 @@
private System.Windows.Forms.Button btnRegisterStore;
private System.Windows.Forms.Button btnPulseSetup;
private System.Windows.Forms.Button preadjustmentButton;
private System.Windows.Forms.Button btnMetersAction;
private System.Windows.Forms.Button slotsComPortsRegistersActionsViewButton;
private System.Windows.Forms.SplitContainer splitWorkArea;
private System.Windows.Forms.Panel pnlGciViewHost;
@ -43,9 +43,11 @@
this.btnRegisterStore = new System.Windows.Forms.Button();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.btnMetersAction = new System.Windows.Forms.Button();
this.storageActionButton = new System.Windows.Forms.Button();
this.combinedActionButton = new System.Windows.Forms.Button();
this.ScenariousViewButton = new System.Windows.Forms.Button();
this.preadjustmentActionsViewButton = new System.Windows.Forms.Button();
this.slotsComPortsRegistersActionsViewButton = new System.Windows.Forms.Button();
this.uniDataSorageActionsViewButton = new System.Windows.Forms.Button();
this.combinedActionsViewButton = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.btnDiagTablesConfigurationButton = new System.Windows.Forms.Button();
this.pnlMain = new System.Windows.Forms.Panel();
@ -104,7 +106,6 @@
//
this.tabPage1.Controls.Add(this.groupBox2);
this.tabPage1.Controls.Add(this.groupBox1);
this.tabPage1.Enabled = false;
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
@ -189,45 +190,66 @@
//
// groupBox5
//
this.groupBox5.Controls.Add(this.btnMetersAction);
this.groupBox5.Controls.Add(this.storageActionButton);
this.groupBox5.Controls.Add(this.combinedActionButton);
this.groupBox5.Controls.Add(this.ScenariousViewButton);
this.groupBox5.Controls.Add(this.preadjustmentActionsViewButton);
this.groupBox5.Controls.Add(this.slotsComPortsRegistersActionsViewButton);
this.groupBox5.Controls.Add(this.uniDataSorageActionsViewButton);
this.groupBox5.Controls.Add(this.combinedActionsViewButton);
this.groupBox5.Location = new System.Drawing.Point(6, 85);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(166, 131);
this.groupBox5.Size = new System.Drawing.Size(166, 202);
this.groupBox5.TabIndex = 3;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Interface";
this.groupBox5.Text = "Interface testing";
//
// btnMetersAction
// ScenariousViewButton
//
this.btnMetersAction.Location = new System.Drawing.Point(6, 19);
this.btnMetersAction.Name = "btnMetersAction";
this.btnMetersAction.Size = new System.Drawing.Size(150, 30);
this.btnMetersAction.TabIndex = 1;
this.btnMetersAction.Text = "GenesisCordonelInterface";
this.btnMetersAction.UseVisualStyleBackColor = true;
this.btnMetersAction.Click += new System.EventHandler(this.btnMetersAction_Click);
this.ScenariousViewButton.Location = new System.Drawing.Point(6, 163);
this.ScenariousViewButton.Name = "ScenariousViewButton";
this.ScenariousViewButton.Size = new System.Drawing.Size(150, 30);
this.ScenariousViewButton.TabIndex = 3;
this.ScenariousViewButton.Text = "Scenarious";
this.ScenariousViewButton.UseVisualStyleBackColor = true;
//
// storageActionButton
// preadjustmentActionsViewButton
//
this.storageActionButton.Location = new System.Drawing.Point(6, 55);
this.storageActionButton.Name = "storageActionButton";
this.storageActionButton.Size = new System.Drawing.Size(150, 30);
this.storageActionButton.TabIndex = 0;
this.storageActionButton.Text = "UniDataStorageReader";
this.storageActionButton.UseVisualStyleBackColor = true;
this.storageActionButton.Click += new System.EventHandler(this.button1_Click_1);
this.preadjustmentActionsViewButton.Location = new System.Drawing.Point(6, 127);
this.preadjustmentActionsViewButton.Name = "preadjustmentActionsViewButton";
this.preadjustmentActionsViewButton.Size = new System.Drawing.Size(150, 30);
this.preadjustmentActionsViewButton.TabIndex = 2;
this.preadjustmentActionsViewButton.Text = "Preadjustment";
this.preadjustmentActionsViewButton.UseVisualStyleBackColor = true;
this.preadjustmentActionsViewButton.Click += new System.EventHandler(this.preadjustmentActionsViewButton_Click);
//
// combinedActionButton
// slotsComPortsRegistersActionsViewButton
//
this.combinedActionButton.Location = new System.Drawing.Point(6, 91);
this.combinedActionButton.Name = "combinedActionButton";
this.combinedActionButton.Size = new System.Drawing.Size(150, 30);
this.combinedActionButton.TabIndex = 0;
this.combinedActionButton.Text = "Combined Action";
this.combinedActionButton.UseVisualStyleBackColor = true;
this.combinedActionButton.Click += new System.EventHandler(this.button2_Click);
this.slotsComPortsRegistersActionsViewButton.Location = new System.Drawing.Point(6, 19);
this.slotsComPortsRegistersActionsViewButton.Name = "slotsComPortsRegistersActionsViewButton";
this.slotsComPortsRegistersActionsViewButton.Size = new System.Drawing.Size(150, 30);
this.slotsComPortsRegistersActionsViewButton.TabIndex = 1;
this.slotsComPortsRegistersActionsViewButton.Text = "Slots, ComPorts, Registers";
this.slotsComPortsRegistersActionsViewButton.UseVisualStyleBackColor = true;
this.slotsComPortsRegistersActionsViewButton.Click += new System.EventHandler(this.btnMetersAction_Click);
//
// uniDataSorageActionsViewButton
//
this.uniDataSorageActionsViewButton.Location = new System.Drawing.Point(6, 55);
this.uniDataSorageActionsViewButton.Name = "uniDataSorageActionsViewButton";
this.uniDataSorageActionsViewButton.Size = new System.Drawing.Size(150, 30);
this.uniDataSorageActionsViewButton.TabIndex = 0;
this.uniDataSorageActionsViewButton.Text = "UniDataStorageReader";
this.uniDataSorageActionsViewButton.UseVisualStyleBackColor = true;
this.uniDataSorageActionsViewButton.Click += new System.EventHandler(this.button1_Click_1);
//
// combinedActionsViewButton
//
this.combinedActionsViewButton.Location = new System.Drawing.Point(6, 91);
this.combinedActionsViewButton.Name = "combinedActionsViewButton";
this.combinedActionsViewButton.Size = new System.Drawing.Size(150, 30);
this.combinedActionsViewButton.TabIndex = 0;
this.combinedActionsViewButton.Text = "Combined actions";
this.combinedActionsViewButton.UseVisualStyleBackColor = true;
this.combinedActionsViewButton.Click += new System.EventHandler(this.button2_Click);
//
// groupBox3
//
@ -386,9 +408,11 @@
this.ResumeLayout(false);
}
private System.Windows.Forms.Button storageActionButton;
private System.Windows.Forms.Button uniDataSorageActionsViewButton;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Button combinedActionButton;
private System.Windows.Forms.Button combinedActionsViewButton;
private System.Windows.Forms.Button btnDiagTablesConfigurationButton;
private System.Windows.Forms.Button preadjustmentActionsViewButton;
private System.Windows.Forms.Button ScenariousViewButton;
}
}

View File

@ -72,58 +72,11 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI
_uiLogFlushTimer.Interval = 250;
_uiLogFlushTimer.Tick += UiLogFlushTimer_Tick;
_uiLogFlushTimer.Start();
preadjustmentButton.Enabled = true;
groupBox2.Enabled = true;
}
/// <summary>
/// Periodically flushes buffered log messages into RichTextBox.
///
/// Runs on the UI thread because WinForms Timer executes on UI thread.
/// Processes messages in batches to reduce UI overhead.
/// </summary>
/// Plynule pridavanie do mema
/*private void UiLogFlushTimer_Tick(object sender, EventArgs e)
{
if (IsDisposed || !IsHandleCreated)
return;
List<string> messages = new List<string>();
lock (_uiLogLock)
{
while (_pendingUiLogs.Count > 0 && messages.Count < 500)
{
messages.Add(_pendingUiLogs.Dequeue());
}
}
if (messages.Count == 0)
return;
rtbMainLog.SuspendLayout();
try
{
foreach (string msg in messages)
{
AppendLogMessage(msg);
}
const int maxTextLength = 200000;
if (rtbMainLog.TextLength > maxTextLength)
{
rtbMainLog.Select(0, rtbMainLog.TextLength - maxTextLength);
rtbMainLog.SelectedText = "";
}
rtbMainLog.SelectionStart = rtbMainLog.TextLength;
rtbMainLog.ScrollToCaret();
}
finally
{
rtbMainLog.ResumeLayout();
}
}*/
private void UiLogFlushTimer_Tick(object sender, EventArgs e)
{
@ -277,153 +230,6 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI
base.Dispose(disposing);
}
private IWin32Window DialogOwner
{
get
{
Form owner = FindForm();
return owner ?? (IWin32Window)this;
}
}
private void ShowGciView(Control view)
{
pnlGciViewHost.Controls.Clear();
view.Dock = DockStyle.Fill;
pnlGciViewHost.Controls.Add(view);
}
/// <summary>
/// Saves current slot configuration from the grid into backend storage.
/// </summary>
public void SaveSlots()
{
var data = _batchPanel.GetGridData();
_laatzenApi.SaveSlotSetup(data);
}
/// <summary>
/// Switches currently displayed GCI view inside the host panel.
/// </summary>
private void button2_Click(object sender, EventArgs e)
{
SwitchGciView(
"CombinedInterfaceView",
new CombinedInterfaceView(this, _bridge));
}
private void button1_Click_1(object sender, EventArgs e)
{
SwitchGciView(
"StorageAction",
new UniDataStorageReaderInterfaceView(this, _bridge));
}
#region BUTTONS
private void btnMetersAction_Click(object sender, EventArgs e)
{
SwitchGciView(
"SlotsMetersAction",
new GenesisCordonelInterfaceView(this, _bridge, AddSlotRow, SaveSlots));
}
private void btnSetup_Click(object sender, EventArgs e)
{
/*Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: Setup open");
using (FrmSetup frm = new FrmSetup())
{
frm.ShowDialog(DialogOwner);
}
Logger.Trace("FORM: Setup closed.");*/
}
private void btnRegisterStore_Click(object sender, EventArgs e)
{
/*Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: Register Store open.");
using (FrmRegisterStore frm = new FrmRegisterStore())
{
frm.ShowDialog(DialogOwner);
}
Logger.Trace("FORM: Register Store closed.");*/
}
private void btnPulseSetup_Click(object sender, EventArgs e)
{
/*Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: Pulse Setup open.");
using (FrmConfigurations frm = new FrmConfigurations())
{
frm.ShowDialog(DialogOwner);
}
Logger.Trace("FORM: Pulse Setup closed.");*/
}
private void preadjustmentButton_Click(object sender, EventArgs e)
{
/*Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: Preadjustment open.");
using (FrmCordonelPreadjustmentUI frm = new FrmCordonelPreadjustmentUI())
{
frm.ShowDialog(DialogOwner);
}
Logger.Trace("FORM: Preadjustment closed.");*/
}
private void button1_Click(object sender, EventArgs e)
{
Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: GciBridge GUI open.");
using (var frm = new FrmGCIAPI(_gciApi))
{
frm.ShowDialog(this);
}
Logger.Trace("FORM: GciBridge closed.");
}
private void SwitchGciView(string name, Control view)
{
Logger.Trace("FORM: ---------------------------------");
Logger.Trace($"FORM: GciBridge VIEW -> {name} OPEN");
pnlGciViewHost.Controls.Clear();
view.Dock = DockStyle.Fill;
pnlGciViewHost.Controls.Add(view);
view.BringToFront();
Logger.Trace($"FORM: GciBridge VIEW -> {name} LOADED");
}
private void btnMeterInit_Click(object sender, EventArgs e)
{
SwitchGciView(
"MeterInit",
new MeterInitView(_gciApi, AddSlotRow, SaveSlots));
}
/// <summary>
/// Clears the main UI log window.
/// </summary>
public void ClearLog()
{
rtbMainLog.Clear();
Logger.Trace("Log cleared.");
}
#endregion
#region GLOBAL LOGGING to memo in this view
@ -545,11 +351,164 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI
#endregion
private IWin32Window DialogOwner
{
get
{
Form owner = FindForm();
return owner ?? (IWin32Window)this;
}
}
private void ShowGciView(Control view)
{
pnlGciViewHost.Controls.Clear();
view.Dock = DockStyle.Fill;
pnlGciViewHost.Controls.Add(view);
}
/// <summary>
/// Saves current slot configuration from the grid into backend storage.
/// </summary>
public void SaveSlots()
{
var data = _batchPanel.GetGridData();
_laatzenApi.SaveSlotSetup(data);
}
#region BUTTONS
private void btnSetup_Click(object sender, EventArgs e)
{
/*Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: Setup open");
using (FrmSetup frm = new FrmSetup())
{
frm.ShowDialog(DialogOwner);
}
Logger.Trace("FORM: Setup closed.");*/
}
private void btnRegisterStore_Click(object sender, EventArgs e)
{
/*Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: Register Store open.");
using (FrmRegisterStore frm = new FrmRegisterStore())
{
frm.ShowDialog(DialogOwner);
}
Logger.Trace("FORM: Register Store closed.");*/
}
private void btnPulseSetup_Click(object sender, EventArgs e)
{
/*Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: Pulse Setup open.");
using (FrmConfigurations frm = new FrmConfigurations())
{
frm.ShowDialog(DialogOwner);
}
Logger.Trace("FORM: Pulse Setup closed.");*/
}
private void preadjustmentButton_Click(object sender, EventArgs e)
{
Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: Preadjustment open.");
_laatzenApi.ShowPreadjustmentForm(DialogOwner);
Logger.Trace("FORM: Preadjustment shown.");
}
private void button1_Click(object sender, EventArgs e)
{
Logger.Trace("FORM: ---------------------------------");
Logger.Trace("FORM: GciBridge GUI open.");
using (var frm = new FrmGCIAPI(_gciApi))
{
frm.ShowDialog(this);
}
Logger.Trace("FORM: GciBridge closed.");
}
private void SwitchGciView(string name, Control view)
{
Logger.Trace("FORM: ---------------------------------");
Logger.Trace($"FORM: GciBridge VIEW -> {name} OPEN");
pnlGciViewHost.Controls.Clear();
view.Dock = DockStyle.Fill;
pnlGciViewHost.Controls.Add(view);
view.BringToFront();
Logger.Trace($"FORM: GciBridge VIEW -> {name} LOADED");
}
private void btnMeterInit_Click(object sender, EventArgs e)
{
SwitchGciView(
"MeterInit",
new MeterInitView(_gciApi, AddSlotRow, SaveSlots));
}
/// <summary>
/// Clears the main UI log window.
/// </summary>
public void ClearLog()
{
rtbMainLog.Clear();
Logger.Trace("Log cleared.");
}
/// <summary>
/// Switches currently displayed GCI view inside the host panel.
/// </summary>
private void button2_Click(object sender, EventArgs e)
{
SwitchGciView(
"CombinedActionsView",
new CombinedActionsView(this, _bridge));
}
private void button1_Click_1(object sender, EventArgs e)
{
SwitchGciView(
"UniDataSorageActionsView",
new UniDataSorageActionsView(this, _bridge));
}
private void btnMetersAction_Click(object sender, EventArgs e)
{
SwitchGciView(
"SlotsComPortsRegistersActionsView",
new SlotsComPortsRegistersActionsView(this, _bridge, AddSlotRow, SaveSlots));
}
private void btnMeterInit_Click_1(object sender, EventArgs e)
{
SwitchGciView(
"ConfigurationView",
new ConfigurationView(this));
}
private void preadjustmentActionsViewButton_Click(object sender, EventArgs e)
{
SwitchGciView(
"PreadjustmentActionsView",
new PreadjustmentActionsView(this, _bridge, AddSlotRow, SaveSlots));
}
}
#endregion
}

View File

@ -1,6 +1,6 @@
namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
{
partial class CombinedInterfaceView
partial class CombinedActionsView
{
private System.ComponentModel.IContainer components = null;

View File

@ -10,7 +10,7 @@ using TBF.Rig.BridgeComponents.GciBridge.Interfaces;
namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
{
public partial class CombinedInterfaceView : UserControl
public partial class CombinedActionsView : UserControl
{
private readonly MainView _mainView;
private readonly GciBridge _bridge;
@ -19,7 +19,7 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
private readonly Dictionary<int, string> _pcbBySlot = new Dictionary<int, string>();
private readonly Dictionary<int, string> _passwordBySlot = new Dictionary<int, string>();
public CombinedInterfaceView(MainView mainView, GciBridge bridge)
public CombinedActionsView(MainView mainView, GciBridge bridge)
{
_mainView = mainView ?? throw new ArgumentNullException(nameof(mainView));
_bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));

View File

@ -0,0 +1,250 @@
namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
{
partial class PreadjustmentActionsView
{
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.GroupBox grpSlots;
private System.Windows.Forms.Button preparationActionButton;
private System.Windows.Forms.Button detectActionButton;
private System.Windows.Forms.Button temperatureCalibrationActionButton;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.TextBox txtLog;
protected override void Dispose(bool disposing)
{
if (disposing && components != null)
components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.grpSlots = new System.Windows.Forms.GroupBox();
this.completionActionButton = new System.Windows.Forms.Button();
this.offsetTestActionButton = new System.Windows.Forms.Button();
this.preparationActionButton = new System.Windows.Forms.Button();
this.detectActionButton = new System.Windows.Forms.Button();
this.temperatureCalibrationActionButton = new System.Windows.Forms.Button();
this.amplitudeTestActionButton = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.txtLog = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.grpSlots.SuspendLayout();
this.SuspendLayout();
//
// grpSlots
//
this.grpSlots.Controls.Add(this.label7);
this.grpSlots.Controls.Add(this.label6);
this.grpSlots.Controls.Add(this.label5);
this.grpSlots.Controls.Add(this.label4);
this.grpSlots.Controls.Add(this.label3);
this.grpSlots.Controls.Add(this.label2);
this.grpSlots.Controls.Add(this.label1);
this.grpSlots.Controls.Add(this.button1);
this.grpSlots.Controls.Add(this.completionActionButton);
this.grpSlots.Controls.Add(this.offsetTestActionButton);
this.grpSlots.Controls.Add(this.preparationActionButton);
this.grpSlots.Controls.Add(this.detectActionButton);
this.grpSlots.Controls.Add(this.temperatureCalibrationActionButton);
this.grpSlots.Controls.Add(this.amplitudeTestActionButton);
this.grpSlots.Location = new System.Drawing.Point(10, 10);
this.grpSlots.Name = "grpSlots";
this.grpSlots.Size = new System.Drawing.Size(689, 304);
this.grpSlots.TabIndex = 2;
this.grpSlots.TabStop = false;
this.grpSlots.Text = "Slots by selection in the table";
this.grpSlots.Enter += new System.EventHandler(this.grpSlots_Enter);
//
// completionActionButton
//
this.completionActionButton.Location = new System.Drawing.Point(390, 249);
this.completionActionButton.Name = "completionActionButton";
this.completionActionButton.Size = new System.Drawing.Size(150, 28);
this.completionActionButton.TabIndex = 3;
this.completionActionButton.Text = "Completition";
//
// offsetTestActionButton
//
this.offsetTestActionButton.Location = new System.Drawing.Point(334, 215);
this.offsetTestActionButton.Name = "offsetTestActionButton";
this.offsetTestActionButton.Size = new System.Drawing.Size(150, 28);
this.offsetTestActionButton.TabIndex = 5;
this.offsetTestActionButton.Text = "Offset test";
//
// preparationActionButton
//
this.preparationActionButton.Location = new System.Drawing.Point(203, 113);
this.preparationActionButton.Name = "preparationActionButton";
this.preparationActionButton.Size = new System.Drawing.Size(150, 28);
this.preparationActionButton.TabIndex = 0;
this.preparationActionButton.Text = "Preparation";
this.preparationActionButton.Click += new System.EventHandler(this.preparationActionButton_Click);
//
// detectActionButton
//
this.detectActionButton.Location = new System.Drawing.Point(171, 79);
this.detectActionButton.Name = "detectActionButton";
this.detectActionButton.Size = new System.Drawing.Size(150, 28);
this.detectActionButton.TabIndex = 1;
this.detectActionButton.Text = "Detect";
this.detectActionButton.Click += new System.EventHandler(this.detectActionButton_Click);
//
// temperatureCalibrationActionButton
//
this.temperatureCalibrationActionButton.Location = new System.Drawing.Point(285, 181);
this.temperatureCalibrationActionButton.Name = "temperatureCalibrationActionButton";
this.temperatureCalibrationActionButton.Size = new System.Drawing.Size(150, 28);
this.temperatureCalibrationActionButton.TabIndex = 2;
this.temperatureCalibrationActionButton.Text = "Temperature calibration";
this.temperatureCalibrationActionButton.Click += new System.EventHandler(this.amplitudeTestActionButton_Click);
//
// amplitudeTestActionButton
//
this.amplitudeTestActionButton.Location = new System.Drawing.Point(246, 147);
this.amplitudeTestActionButton.Name = "amplitudeTestActionButton";
this.amplitudeTestActionButton.Size = new System.Drawing.Size(150, 28);
this.amplitudeTestActionButton.TabIndex = 18;
this.amplitudeTestActionButton.Text = "Amplitude test";
//
// btnCancel
//
this.btnCancel.Enabled = false;
this.btnCancel.Location = new System.Drawing.Point(519, 320);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(180, 30);
this.btnCancel.TabIndex = 4;
this.btnCancel.Text = "Cancel task";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// txtLog
//
this.txtLog.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.txtLog.Location = new System.Drawing.Point(10, 356);
this.txtLog.Multiline = true;
this.txtLog.Name = "txtLog";
this.txtLog.ReadOnly = true;
this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtLog.Size = new System.Drawing.Size(689, 232);
this.txtLog.TabIndex = 5;
this.txtLog.WordWrap = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(17, 28);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(150, 28);
this.button1.TabIndex = 108;
this.button1.Text = "Preadjustment init";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(176, 121);
this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(22, 13);
this.label1.TabIndex = 109;
this.label1.Text = "--->";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(219, 155);
this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(22, 13);
this.label2.TabIndex = 110;
this.label2.Text = "--->";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(258, 189);
this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(22, 13);
this.label3.TabIndex = 111;
this.label3.Text = "--->";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(307, 223);
this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(22, 13);
this.label4.TabIndex = 112;
this.label4.Text = "--->";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(363, 257);
this.label5.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(22, 13);
this.label5.TabIndex = 113;
this.label5.Text = "--->";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(14, 87);
this.label6.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(117, 13);
this.label6.TabIndex = 114;
this.label6.Text = "Preadjustment process:";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(144, 87);
this.label7.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(22, 13);
this.label7.TabIndex = 115;
this.label7.Text = "--->";
//
// PreadjustmentActionsView
//
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.grpSlots);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.txtLog);
this.Name = "PreadjustmentActionsView";
this.Size = new System.Drawing.Size(719, 603);
this.grpSlots.ResumeLayout(false);
this.grpSlots.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.Button completionActionButton;
private System.Windows.Forms.Button offsetTestActionButton;
private System.Windows.Forms.Button amplitudeTestActionButton;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
}
}

View File

@ -0,0 +1,405 @@
using CordonelPreadjustmentUi;
using CordonelPreadjustmentUi.Processes.Itinerary;
using GenesisCordonelInterface.API;
using GenesisCordonelInterface.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
using Xylem.Common.Ui.CordonelPreadjustmentUi;
using static GenesisCordonelInterface.API.PublicModels;
using static Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.PreadjustmentMeter;
using GciPublicModels = GenesisCordonelInterface.API.PublicModels;
namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
{
public partial class PreadjustmentActionsView : UserControl
{
private readonly GciBridge _bridge;
private readonly MainView _mainView;
private CancellationTokenSource _cts;
private readonly Action _addSlotAction;
private readonly Action _saveAction;
public PreadjustmentActionsView(
MainView mainview,
GciBridge bridge,
Action addSlotAction,
Action saveAction)
{
_mainView = mainview ?? throw new ArgumentNullException(nameof(mainview));
_bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));
_addSlotAction = addSlotAction;
_saveAction = saveAction;
InitializeComponent();
LoadRegisterComboBoxes();
}
private void AddSlot()
{
_addSlotAction?.Invoke();
}
private void SaveSlots()
{
_saveAction?.Invoke();
}
private List<GciPublicModels.MeterBatchDebugStatus> GetSelectedSlots()
{
if (_mainView == null || _mainView._batchPanel == null)
throw new Exception("Meter batch grid is not available.");
var slots = _mainView._batchPanel.GetSelectedGridData();
if (slots.Count == 0)
throw new Exception("No selected slots in grid.");
return slots;
}
private void RefreshGrid(int? removedSlot = null)
{
if (removedSlot.HasValue)
{
_mainView?._gciApi.SetSlotSelected(removedSlot.Value, false);
_mainView?._batchPanel?.RemoveSlotRow(removedSlot.Value);
}
if (_bridge?.gciExternalInterface != null)
_bridge.gciExternalInterface.RaiseMeterBatchStatusChanged();
}
private void btnCancel_Click(object sender, EventArgs e)
{
_cts?.Cancel();
Log("Cancel requested.");
}
private async void ExecuteAsync(Func<CancellationToken, Task> action)
{
try
{
SetBusy(true);
_cts = new CancellationTokenSource();
await action(_cts.Token);
}
catch (OperationCanceledException)
{
Log("Operation canceled.");
}
catch (Exception ex)
{
Log("ERROR: " + ex);
MessageBox.Show(
ex.Message,
"GciBridge API call failed",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
_cts?.Dispose();
_cts = null;
SetBusy(false);
}
}
private void SetBusy(bool busy)
{
Cursor = busy ? Cursors.WaitCursor : Cursors.Default;
preparationActionButton.Enabled = !busy;
detectActionButton.Enabled = !busy;
temperatureCalibrationActionButton.Enabled = !busy;
offsetTestActionButton.Enabled = !busy;
completionActionButton.Enabled = !busy;
amplitudeTestActionButton.Enabled = !busy;
amplitudeTestActionButton.Enabled = !busy;
temperatureCalibrationActionButton.Enabled = !busy;
offsetTestActionButton.Enabled = !busy;
completionActionButton.Enabled = !busy;
btnCancel.Enabled = busy;
}
private void LogResult(string methodName, object result)
{
Log(methodName + " result:");
Log(result == null ? "<null>" : result.ToString());
}
private void Log(string message)
{
txtLog.AppendText(
DateTime.Now.ToString("HH:mm:ss.fff") +
" " +
message +
Environment.NewLine);
}
private void LoadRegisterComboBoxes()
{
}
private void grpSlots_Enter(object sender, EventArgs e)
{
}
private void preparationActionButton_Click(
object sender,
EventArgs e)
{
ExecuteAsync(async token =>
{
await ExecutePreadjustmentForSelectedSlotsAsync(
_bridge.Preadjustment_PreparationAsync,
"Preparation",
token);
});
}
private void amplitudeTestActionButton_Click(
object sender,
EventArgs e)
{
ExecuteAsync(async token =>
{
await ExecutePreadjustmentForSelectedSlotsAsync(
_bridge.Preadjustment_AmplitudeTestAsync,
"Amplitude Test",
token);
});
}
private void temperatureCalibrationActionButton_Click(
object sender,
EventArgs e)
{
ExecuteAsync(async token =>
{
await ExecutePreadjustmentForSelectedSlotsAsync(
_bridge.Preadjustment_TemperatureCalibrationAsync,
"Temperature Calibration",
token);
});
}
private void offsetTestActionButton_Click(
object sender,
EventArgs e)
{
ExecuteAsync(async token =>
{
await ExecutePreadjustmentForSelectedSlotsAsync(
_bridge.Preadjustment_OffsetTestAsync,
"Offset Test",
token);
});
}
private void completionActionButton_Click(
object sender,
EventArgs e)
{
ExecuteAsync(async token =>
{
await ExecutePreadjustmentForSelectedSlotsAsync(
_bridge.Preadjustment_CompletionAsync,
"Completion",
token);
});
}
private void detectActionButton_Click(
object sender,
EventArgs e)
{
ExecuteAsync(async token =>
{
var selectedSlots =
_mainView._batchPanel.GetSelectedGridData();
if (!selectedSlots.Any())
{
Log("Detect: no selected slots.");
return;
}
_mainView._laatzenApi._settings =
CreatePreAdjustmentSettings(selectedSlots);
_mainView._laatzenApi._meterControls =
CreateMeterControls(selectedSlots);
PreadjustmentDetectResult result =
await _bridge.Preadjustment_DetectAsync(token);
Log(
result.Success
? "Detect completed. " + result
: "Detect failed. " + result);
RefreshGrid();
});
}
private ProcessProgress CreatePreparationProgress()
{
return new ProcessProgress
{
Setting = new PreAdjustmentSettingsContainer
{
TempOnly = false,
Culture =
Thread.CurrentThread.CurrentCulture
},
IsAutomaticMode = true
};
}
private List<MeterStateControl> CreateMeterControls(IEnumerable<GciPublicModels.MeterBatchDebugStatus> slots)
{
var controls =
new List<MeterStateControl>();
foreach (var slot in slots)
{
var ctl = new MeterStateControl(slot.Slot);
ctl.SetChecked(true);
ctl.IsEnabled = true;
controls.Add(ctl);
}
return controls;
}
private PreAdjustmentSettingsContainer CreatePreAdjustmentSettings(IEnumerable<GciPublicModels.MeterBatchDebugStatus> slots)
{
var settings =
new PreAdjustmentSettingsContainer();
settings.Meters =
slots.Select(s => s.Slot).ToList();
settings.TempMeters =
new List<int>();
settings.NumberOfPaths = 2;
settings.TempOnly = false;
settings.Culture =
Thread.CurrentThread.CurrentCulture;
return settings;
}
private void writeRegisterButton_Click(object sender, EventArgs e)
{
/*ExecuteAsync(async token =>
{
string registerName = Convert.ToString(writeRegisterNameComboBox.Text).Trim();
string valueText = writeRegisterValueTextBox.Text.Trim();
if (string.IsNullOrWhiteSpace(registerName))
throw new Exception("Write register name is empty.");
if (string.IsNullOrWhiteSpace(valueText))
throw new Exception("Write register value is empty.");
object value;
if (registerName == "GENESISFLOW_LedMode")
{
value = byte.Parse(valueText);
}
else
{
value = valueText;
}
var tasks = GetSelectedSlots()
.Select(async slot =>
{
//var result = await _bridge.WriteRegisterAsync(slot.Slot, registerName, value, false, false, token);
//var result = await _bridge.WriteRegisterWithRetryAsync(slot.Slot, registerName, value, false, false, token);
var result = Xylem.Common.Ui.CordonelPreadjustmentUi. Processes.WriteRegisterSafe(meter, "Calibration factor1", Register.Genesisflow.CalFactor1, setting.CalFactor1);
Processes
return new
{
Slot = slot.Slot,
Result = result
};
})
.ToList();
var results = await Task.WhenAll(tasks);
foreach (var item in results.OrderBy(x => x.Slot))
{
LogResult(
$"WriteRegisterAsync slot {item.Slot}, register {registerName}, value {value}",
item.Result);
}
RefreshGrid();
});*/
}
private async Task ExecutePreadjustmentForSelectedSlotsAsync(
Func<int, ProcessProgress, CancellationToken, Task<PreadjustmentProcessResult>> action,
string processName,
CancellationToken token)
{
var selectedSlots =
_mainView._batchPanel.GetSelectedGridData();
if (!selectedSlots.Any())
{
Log(processName + ": no selected slots.");
return;
}
var pp =
CreatePreparationProgress();
foreach (var selectedSlot in selectedSlots)
{
PreadjustmentProcessResult result =
await action(
selectedSlot.Slot,
pp,
token);
Log(result.Success
? processName + " completed. " + result
: processName + " failed. " + result);
if (!result.Success)
break;
}
RefreshGrid();
}
}
}

View File

@ -1,6 +1,6 @@
namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
{
partial class GenesisCordonelInterfaceView
partial class SlotsComPortsRegistersActionsView
{
private System.ComponentModel.IContainer components = null;
@ -42,6 +42,7 @@
this.btnGetSlot = new System.Windows.Forms.Button();
this.btnCleanAllSlots = new System.Windows.Forms.Button();
this.btnCleanSlot = new System.Windows.Forms.Button();
this.writeRegisterValueTypeLabel = new System.Windows.Forms.Label();
this.btnCancel = new System.Windows.Forms.Button();
this.txtLog = new System.Windows.Forms.TextBox();
this.grpSlots.SuspendLayout();
@ -49,6 +50,9 @@
//
// grpSlots
//
this.grpSlots.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.grpSlots.Controls.Add(this.writeRegisterNameComboBox);
this.grpSlots.Controls.Add(this.readRegisterNameComboBox);
this.grpSlots.Controls.Add(this.label4);
@ -66,9 +70,10 @@
this.grpSlots.Controls.Add(this.btnGetSlot);
this.grpSlots.Controls.Add(this.btnCleanAllSlots);
this.grpSlots.Controls.Add(this.btnCleanSlot);
this.grpSlots.Controls.Add(this.writeRegisterValueTypeLabel);
this.grpSlots.Location = new System.Drawing.Point(10, 10);
this.grpSlots.Name = "grpSlots";
this.grpSlots.Size = new System.Drawing.Size(689, 304);
this.grpSlots.Size = new System.Drawing.Size(726, 304);
this.grpSlots.TabIndex = 2;
this.grpSlots.TabStop = false;
this.grpSlots.Text = "Slots by selection in the table";
@ -103,7 +108,7 @@
//
this.writeRegisterValueTextBox.Location = new System.Drawing.Point(555, 264);
this.writeRegisterValueTextBox.Name = "writeRegisterValueTextBox";
this.writeRegisterValueTextBox.Size = new System.Drawing.Size(117, 20);
this.writeRegisterValueTextBox.Size = new System.Drawing.Size(85, 20);
this.writeRegisterValueTextBox.TabIndex = 12;
//
// label3
@ -223,6 +228,15 @@
this.btnCleanSlot.Text = "CleanSlot(slot)";
this.btnCleanSlot.Click += new System.EventHandler(this.btnCleanSlot_Click);
//
// writeRegisterValueTypeLabel
//
this.writeRegisterValueTypeLabel.AutoSize = true;
this.writeRegisterValueTypeLabel.Location = new System.Drawing.Point(646, 267);
this.writeRegisterValueTypeLabel.Name = "writeRegisterValueTypeLabel";
this.writeRegisterValueTypeLabel.Size = new System.Drawing.Size(36, 13);
this.writeRegisterValueTypeLabel.TabIndex = 19;
this.writeRegisterValueTypeLabel.Text = "type: -";
//
// btnCancel
//
this.btnCancel.Enabled = false;
@ -243,18 +257,18 @@
this.txtLog.Name = "txtLog";
this.txtLog.ReadOnly = true;
this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtLog.Size = new System.Drawing.Size(689, 232);
this.txtLog.Size = new System.Drawing.Size(726, 232);
this.txtLog.TabIndex = 5;
this.txtLog.WordWrap = false;
//
// GenesisCordonelInterfaceView
// SlotsComPortsRegistersActionsView
//
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.grpSlots);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.txtLog);
this.Name = "GenesisCordonelInterfaceView";
this.Size = new System.Drawing.Size(719, 603);
this.Name = "SlotsComPortsRegistersActionsView";
this.Size = new System.Drawing.Size(756, 603);
this.grpSlots.ResumeLayout(false);
this.grpSlots.PerformLayout();
this.ResumeLayout(false);
@ -275,5 +289,6 @@
private System.Windows.Forms.ComboBox readRegisterNameComboBox;
private System.Windows.Forms.Button btnLogin;
private System.Windows.Forms.Button btnCleanSlot;
private System.Windows.Forms.Label writeRegisterValueTypeLabel;
}
}

View File

@ -10,15 +10,17 @@ using GciPublicModels = GenesisCordonelInterface.API.PublicModels;
namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
{
public partial class GenesisCordonelInterfaceView : UserControl
public partial class SlotsComPortsRegistersActionsView : UserControl
{
private readonly GciBridge _bridge;
private readonly MainView _mainView;
private CancellationTokenSource _cts;
private readonly Action _addSlotAction;
private readonly Action _saveAction;
private readonly Dictionary<string, Type> _registerTypes =
new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
public GenesisCordonelInterfaceView(
public SlotsComPortsRegistersActionsView(
MainView mainview,
GciBridge bridge,
Action addSlotAction,
@ -33,6 +35,13 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
InitializeComponent();
LoadRegisterComboBoxes();
_mainView._batchPanel.GetMeterRegistersClicked -= LoadRegisterComboBoxes;
_mainView._batchPanel.GetMeterRegistersClicked += LoadRegisterComboBoxes;
writeRegisterNameComboBox.SelectedIndexChanged -= writeRegisterNameComboBox_SelectedIndexChanged;
writeRegisterNameComboBox.SelectedIndexChanged += writeRegisterNameComboBox_SelectedIndexChanged;
writeRegisterNameComboBox.TextChanged -= writeRegisterNameComboBox_SelectedIndexChanged;
writeRegisterNameComboBox.TextChanged += writeRegisterNameComboBox_SelectedIndexChanged;
}
private void AddSlot()
@ -48,14 +57,14 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
private List<GciPublicModels.MeterBatchDebugStatus> GetSelectedSlots()
{
if (_mainView == null || _mainView._batchPanel == null)
throw new Exception("Meter batch grid is not available.");
{
Log("Meter batch grid is not available.");
var slots = _mainView._batchPanel.GetSelectedGridData();
return new List<GciPublicModels.MeterBatchDebugStatus>();
}
if (slots.Count == 0)
throw new Exception("No selected slots in grid.");
return slots;
return _mainView._batchPanel.GetSelectedGridData()
?? new List<GciPublicModels.MeterBatchDebugStatus>();
}
private void RefreshGrid(int? removedSlot = null)
@ -414,16 +423,7 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
if (string.IsNullOrWhiteSpace(valueText))
throw new Exception("Write register value is empty.");
object value;
if (registerName == "GENESISFLOW_LedMode")
{
value = byte.Parse(valueText);
}
else
{
value = valueText;
}
object value = ConvertTextToRegisterValue(registerName, valueText);
var tasks = GetSelectedSlots()
.Select(async slot =>
@ -530,18 +530,162 @@ namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
private void LoadRegisterComboBoxes()
{
var registers = _bridge.GetAllRegisterNames();
_registerTypes.Clear();
readRegisterNameComboBox.Items.Clear();
writeRegisterNameComboBox.Items.Clear();
readRegisterNameComboBox.Items.AddRange(registers.ToArray());
writeRegisterNameComboBox.Items.AddRange(registers.ToArray());
var selectedSlots = GetSelectedSlots();
if (selectedSlots.Count == 0)
{
Log("No selected slot.");
return;
}
int slot = selectedSlots
.OrderBy(x => x.Slot)
.First()
.Slot;
var registers = _mainView._laatzenApi.GetRegistersDicForSlot(slot);
var uniqueRegisters = registers
.GroupBy(x => x.Key.GetIdent())
.Select(g => g.First())
.OrderBy(x => x.Key.GetIdent())
.ToList();
foreach (var item in uniqueRegisters)
{
string registerName = item.Key.GetIdent();
Type dataType = item.Key.DataType;
_registerTypes[registerName] = dataType;
readRegisterNameComboBox.Items.Add(registerName);
writeRegisterNameComboBox.Items.Add(registerName);
}
Log($"Loaded {uniqueRegisters.Count} unique registers from slot {slot}");
}
private void grpSlots_Enter(object sender, EventArgs e)
{
}
private void writeRegisterNameComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string registerName = Convert.ToString(writeRegisterNameComboBox.Text).Trim();
if (_registerTypes.TryGetValue(registerName, out var type))
{
writeRegisterValueTypeLabel.Text = $"type: {type.Name}";
}
else
{
writeRegisterValueTypeLabel.Text = "type: -";
}
}
private object ConvertTextToRegisterValue(
string registerName,
string valueText)
{
if (!_registerTypes.TryGetValue(
registerName,
out var targetType))
{
throw new Exception(
$"Unknown register type for register '{registerName}'.");
}
return ConvertTextToType(
valueText,
targetType,
registerName);
}
private object ConvertTextToType(
string valueText,
Type targetType,
string registerName)
{
if (targetType == typeof(string))
return valueText;
if (targetType.IsEnum)
{
return Enum.Parse(
targetType,
valueText,
true);
}
if (targetType == typeof(byte[]))
{
return ParseByteArray(valueText);
}
if (targetType.Name == "Enum8")
{
return byte.Parse(valueText);
}
try
{
return Convert.ChangeType(
valueText,
targetType,
System.Globalization.CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
throw new Exception(
$"Value '{valueText}' cannot be converted to '{targetType.Name}' for register '{registerName}'.",
ex);
}
}
private byte[] ParseByteArray(string valueText)
{
valueText = valueText.Trim();
if (valueText.Contains("-") ||
valueText.Contains(" "))
{
return valueText
.Split(
new[] { '-', ' ', ',', ';' },
StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Replace("0x", ""))
.Select(x => Convert.ToByte(x, 16))
.ToArray();
}
valueText =
valueText.Replace("0x", "");
if (valueText.Length % 2 != 0)
{
throw new Exception(
"Hex string length must be even.");
}
byte[] result =
new byte[valueText.Length / 2];
for (int i = 0; i < result.Length; i++)
{
string hex =
valueText.Substring(i * 2, 2);
result[i] =
Convert.ToByte(hex, 16);
}
return result;
}
}
}

View File

@ -1,12 +1,10 @@
namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
{
partial class UniDataStorageReaderInterfaceView
partial class UniDataSorageActionsView
{
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.GroupBox grpStorage;
private System.Windows.Forms.Label lblPcbId;
private System.Windows.Forms.TextBox txtPcbId;
private System.Windows.Forms.Button btnGetPasswordByPcb;
private System.Windows.Forms.Button btnCancel;
@ -23,11 +21,11 @@
private void InitializeComponent()
{
this.grpStorage = new System.Windows.Forms.GroupBox();
this.lblPcbId = new System.Windows.Forms.Label();
this.txtPcbId = new System.Windows.Forms.TextBox();
this.btnGetPasswordByPcb = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.txtLog = new System.Windows.Forms.TextBox();
this.lblPcbId = new System.Windows.Forms.Label();
this.txtPcbId = new System.Windows.Forms.TextBox();
this.grpStorage.SuspendLayout();
this.SuspendLayout();
//
@ -38,27 +36,11 @@
this.grpStorage.Controls.Add(this.btnGetPasswordByPcb);
this.grpStorage.Location = new System.Drawing.Point(10, 37);
this.grpStorage.Name = "grpStorage";
this.grpStorage.Size = new System.Drawing.Size(200, 120);
this.grpStorage.Size = new System.Drawing.Size(200, 261);
this.grpStorage.TabIndex = 0;
this.grpStorage.TabStop = false;
this.grpStorage.Text = "UniDataStorageReader for GCI";
//
// lblPcbId
//
this.lblPcbId.AutoSize = true;
this.lblPcbId.Location = new System.Drawing.Point(10, 25);
this.lblPcbId.Name = "lblPcbId";
this.lblPcbId.Size = new System.Drawing.Size(45, 13);
this.lblPcbId.TabIndex = 0;
this.lblPcbId.Text = "PCB ID:";
//
// txtPcbId
//
this.txtPcbId.Location = new System.Drawing.Point(65, 22);
this.txtPcbId.Name = "txtPcbId";
this.txtPcbId.Size = new System.Drawing.Size(120, 20);
this.txtPcbId.TabIndex = 1;
//
// btnGetPasswordByPcb
//
this.btnGetPasswordByPcb.Location = new System.Drawing.Point(10, 55);
@ -91,12 +73,28 @@
this.txtLog.TabIndex = 4;
this.txtLog.WordWrap = false;
//
// UniDataStorageReaderInterfaceView
// lblPcbId
//
this.lblPcbId.AutoSize = true;
this.lblPcbId.Location = new System.Drawing.Point(10, 25);
this.lblPcbId.Name = "lblPcbId";
this.lblPcbId.Size = new System.Drawing.Size(45, 13);
this.lblPcbId.TabIndex = 0;
this.lblPcbId.Text = "PCB ID:";
//
// txtPcbId
//
this.txtPcbId.Location = new System.Drawing.Point(65, 22);
this.txtPcbId.Name = "txtPcbId";
this.txtPcbId.Size = new System.Drawing.Size(120, 20);
this.txtPcbId.TabIndex = 1;
//
// UniDataSorageActionsView
//
this.Controls.Add(this.grpStorage);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.txtLog);
this.Name = "UniDataStorageReaderInterfaceView";
this.Name = "UniDataSorageActionsView";
this.Size = new System.Drawing.Size(740, 370);
this.grpStorage.ResumeLayout(false);
this.grpStorage.PerformLayout();
@ -104,5 +102,8 @@
this.PerformLayout();
}
private System.Windows.Forms.Label lblPcbId;
private System.Windows.Forms.TextBox txtPcbId;
}
}

View File

@ -5,13 +5,13 @@ using System.Windows.Forms;
namespace TBF.Rig.BridgeComponents.GciBridge.UI.StaraTuraAPI_GciBridge
{
public partial class UniDataStorageReaderInterfaceView : UserControl
public partial class UniDataSorageActionsView : UserControl
{
private readonly MainView _mainView;
private readonly GciBridge _bridge;
private CancellationTokenSource _cts;
public UniDataStorageReaderInterfaceView(MainView mainView, GciBridge bridge)
public UniDataSorageActionsView(MainView mainView, GciBridge bridge)
{
_mainView = mainView ?? throw new ArgumentNullException(nameof(mainView));
_bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));

View File

@ -0,0 +1,120 @@
<?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>

View File

@ -380,6 +380,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.communication
if (pcbResult.IsValidPcb)
{
log.Debug($"Setting PCB: {pcbResult.PcbId} for Head: {genesisHead.Name}");
genesisHead.SerialNr = pcbResult.PcbId;
if (genesisHead.ConfigStruct != null)
{
@ -474,6 +475,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.communication
if (pbcReadBuildAsync.Success && !string.IsNullOrEmpty(pbcReadBuildAsync.PcbId))
{
log.Debug($"Setting PCB: {pbcReadBuildAsync.PcbId} for Head: {genesisHead.Name}");
genesisHead.SerialNr = pbcReadBuildAsync.PcbId;
}
@ -1330,6 +1332,16 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.communication
BridgeComponents.GciBridge.Interfaces.PublicModels.GciFullLoginResult connectFullPassLoginWithRetryAsync = await genesisSmartReader.CommInterfaceBridge.ConnectFullPassLoginWithRetryAsync(genesisSmartReader.GetSlotNr, token);
log.Debug($"GroupedLoginSlot_Async( Slot: {genesisSmartReader.GetSlotNr}) - Result: " + connectFullPassLoginWithRetryAsync);
if (connectFullPassLoginWithRetryAsync?.PcbResult?.Success == true)
{
log.Debug($"Setting PCB: {connectFullPassLoginWithRetryAsync?.PcbResult?.Result?.PcbId} for Head: {genesisSmartReader.Name}");
genesisSmartReader.SerialNr = connectFullPassLoginWithRetryAsync?.PcbResult?.Result?.PcbId;
if (genesisSmartReader.ConfigStruct != null)
{
genesisSmartReader.ConfigStruct.PCBNumberString = genesisSmartReader.SerialNr;
}
}
return connectFullPassLoginWithRetryAsync;
}
catch (Exception ex)
@ -1447,30 +1459,107 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.communication
}
}
public string WriteQ3Calibration()
public string WriteQ3Calibration(TestMethodCfg cfg, Test test, WaterMeter wm)
{
if (genesisHead != null && genesisHead.DebugLevel == DebugMode.Simulate)
{
log.Debug("Connect() - Simulated response");
log.Debug("WriteQ3Calibration() - Simulated response - Config: " + cfg.ToString() + " Test: " + test.ToString() + " WaterMeter: " + wm.ToString());
try
{
Results.Entities.TestRslt tstRslt = ProcessData.BatchRslts.GetTestRslt(test.Name, test.Part);
if (tstRslt.CalibFactorResultsToSave.Count == 0)
{
for (int i = 0; i < genesisHead.ChannelsCount; i++)
{
tstRslt.CalibFactorResultsToSave.Add(new TestRsltCalibFactor()
{
Stored = true,
CalibFactorIndex = i,
CalculatedCalibFactor = 15655,
}
);
}
}
else
{
for (int i = 0; i < genesisHead.ChannelsCount; i++)
{
tstRslt.CalibFactorResultsToSave[i].CalculatedCalibFactor = 15655;
tstRslt.CalibFactorResultsToSave[i].Stored = true;
}
}
}catch(Exception ex)
{
log.Error($"WriteQ3Calibration_Async() - DB Exception: {ex.Message}");
}
return ResultOk; //"Simulated Connect";
}
return Task.Run(() => WriteQ3Calibration_Async(genesisHead))
if (cfg == null)
{
log.Error("WriteQ3Calibration() - Missing TestMethodCfg");
return "Missing TestMethodCfg";
}
if (test == null)
{
log.Error("WriteQ3Calibration() - Missing Test");
return "Missing Test";
}
return Task.Run(() => WriteQ3Calibration_Async(genesisHead, cfg, test, wm))
.GetAwaiter()
.GetResult();
}
private async Task<string> WriteQ3Calibration_Async(GenesisSmartReader genesisSmartReader)
private async Task<string> WriteQ3Calibration_Async(GenesisSmartReader genesisSmartReader,
TestMethodCfg cfg,
Test test, WaterMeter wm)
{
try
{
log.Debug("WriteQ3Calibration_Async called for iHead: " + genesisHead);
log.Debug("WriteQ3Calibration_Async called for iHead: " + genesisHead?.Name + " , cfg: " + cfg?.Name + " , test: " + test?.Name);
if (genesisHead == null) return string.Empty;
if (string.IsNullOrEmpty(genesisHead.CommInterface)) return string.Empty;
if (genesisHead == null)
{
log.Error("WriteQ3Calibration_Async() - Missing GenesisSmartReader");
return string.Empty;
}
if (string.IsNullOrEmpty(genesisHead.CommInterface))
{
log.Error("WriteQ3Calibration_Async() - Missing CommInterface");
return string.Empty;
}
GciBridge gciBridge = genesisHead.CommInterfaceBridge;
if (gciBridge == null) return string.Empty;
if (gciBridge == null)
{
log.Error("WriteQ3Calibration_Async() - Missing GciBridge");
return string.Empty;
}
Results.Entities.TestRslt tstRslt = ProcessData.BatchRslts.GetTestRslt(test.Name, test.Part);
log.Debug($"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Test: {test.Name} - Part: {test.Part} - IsTestRslt: {(tstRslt==null?true:false)}");
try
{
if (tstRslt.CalibFactorResultsToSave.Count == 0)
{
for (int i = 0; i < genesisSmartReader.ChannelsCount; i++)
{
tstRslt.CalibFactorResultsToSave.Add(new TestRsltCalibFactor()
{
Stored = false,
CalibFactorIndex = i
}
);
}
}
}catch(Exception ex)
{
log.Error($"WriteQ3Calibration_Async() - DB Exception: {ex.Message}");
}
CancellationToken token = default;
@ -1481,45 +1570,123 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.communication
return "CalculateQ3Calibration Initialised Data not valid";
}
StoreCalibrationValuesResults(tstRslt, genesisSmartReader);
if (!genesisSmartReader.Q3CalibValid)
{
log.Error("WriteQ3Calibration_Async() - Q3Calibration not valid");
return "Q3Calibration not valid";
log.Error("WriteQ3Calibration_Async() - Q3Channel not valid");
return "Q3Channel not valid";
}
//Get Activity Status
LedState ledMode = LedState.inactive; // swich on LED
byte valueLed = (ledMode == LedState.active) ? (byte)6 : (byte)0;
UInt16 calibFactor1 = Convert.ToUInt16(genesisSmartReader.Q3Calib_Ch1Value);
UInt16 calibFactor2 = Convert.ToUInt16(genesisSmartReader.Q3Calib_Ch2Value);
UInt16 calibFactor3 = Convert.ToUInt16(genesisSmartReader.Q3Calib_Ch3Value);
UInt16 valueSampleRate = 2;
UInt16 ResetAccumulatorsValue = 0;
UInt16 ForwardArrowValue = 0;
UInt16 StoreCalibrationValue = 1;
log.Debug( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start - Set Led Mode: {valueLed}");
log.Debug( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start");
log.Debug( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start - Set CalFactor1: {calibFactor1}");
var CalFactor1AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor1, calibFactor1, false, false, token);
if (CalFactor1AsyncResult == null || !CalFactor1AsyncResult.Success)
{
log.Error( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - CalFactor1AsyncResult failed. Result: {CalFactor1AsyncResult}");
return "Failed to set CalFactor1";
}
wm.OrigCalibFactor = calibFactor1;
if (genesisSmartReader.Q3CalibDiffPercentageValue.Length == 3)
wm.Q2ErrWOCorrection = genesisSmartReader.Q3CalibDiffPercentageValue[0];
//CH3 to DB
try
{
if (tstRslt != null &&
tstRslt?.CalibFactorResultsToSave?.Count == 3 &&
tstRslt?.CalibFactorResultsToSave?[0] != null)
{
tstRslt.CalibFactorResultsToSave[0].CalculatedCalibFactor = Convert.ToInt32(calibFactor1);
tstRslt.CalibFactorResultsToSave[0].Stored = true;
tstRslt.CalibFactorResultsToSave[0].IsCalibFactorValid = true;
tstRslt.CalibFactorResultsToSave[0].Error = genesisSmartReader.Q3CalibDiffPercentageValue[0];
}
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB Stored tstRslt:{tstRslt.Name()} - CalFactor3: {calibFactor1}");
}
catch (Exception ex)
{
log.Error($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB CH1 Exception:", ex);
}
log.Debug( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start - Set CalFactor2: {calibFactor2}");
var CalFactor2AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor2, calibFactor2, false, false, token);
if (CalFactor2AsyncResult == null || !CalFactor2AsyncResult.Success)
{
log.Error( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - CalFactor2AsyncResult failed. Result: {CalFactor2AsyncResult}");
return "Failed to set CalFactor2";
}
wm.CalibFactorLNA = calibFactor2;
if (genesisSmartReader.Q3CalibDiffPercentageValue.Length == 3)
wm.OrigCalibFactorLNA = genesisSmartReader.Q3CalibDiffPercentageValue[1];
//CH3 to DB
try
{
if (tstRslt != null &&
tstRslt?.CalibFactorResultsToSave?.Count == 3 &&
tstRslt?.CalibFactorResultsToSave?[1] != null)
{
tstRslt.CalibFactorResultsToSave[1].CalculatedCalibFactor = Convert.ToInt32(calibFactor2);
tstRslt.CalibFactorResultsToSave[1].Stored = true;
tstRslt.CalibFactorResultsToSave[1].IsCalibFactorValid = true;
tstRslt.CalibFactorResultsToSave[1].Error = genesisSmartReader.Q3CalibDiffPercentageValue[1];
}
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB Stored tstRslt:{tstRslt.Name()} - CalFactor3: {calibFactor2}");
}
catch (Exception ex)
{
log.Error($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB CH2 Exception:", ex);
}
log.Debug( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start - Set CalFactor3: {calibFactor3}");
var CalFactor3AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor3, calibFactor3, false, false, token);
if (CalFactor3AsyncResult == null || !CalFactor3AsyncResult.Success)
{
log.Error( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - CalFactor3AsyncResult failed. Result: {CalFactor3AsyncResult}");
return "Failed to set CalFactor3";
}
wm.CalibFactor = calibFactor3;
if (genesisSmartReader.Q3CalibDiffPercentageValue.Length == 3)
wm.Diff2Hz8Hz = genesisSmartReader.Q3CalibDiffPercentageValue[2];
//CH3 to DB
try
{
if (tstRslt != null &&
tstRslt?.CalibFactorResultsToSave?.Count == 3 &&
tstRslt?.CalibFactorResultsToSave?[2] != null)
{
tstRslt.CalibFactorResultsToSave[2].CalculatedCalibFactor = Convert.ToInt32(calibFactor3);
tstRslt.CalibFactorResultsToSave[2].Stored = true;
tstRslt.CalibFactorResultsToSave[2].IsCalibFactorValid = true;
tstRslt.CalibFactorResultsToSave[2].Error = genesisSmartReader.Q3CalibDiffPercentageValue[2];
}
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB Stored tstRslt:{tstRslt.Name()} - CalFactor3: {calibFactor3}");
}
catch (Exception ex)
{
log.Error($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB CH3 Exception:", ex);
}
log.Info( $"WriteQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Set DONE CalFactor1: {calibFactor1}, CalFactor2: {calibFactor2}, CalFactor2: {calibFactor3}");
@ -1569,83 +1736,256 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.communication
}
}
public string PrepareQ3Calibration(TestMethodCfg cfg, Test test)
private void StoreCalibrationValuesResults(TestRslt tstRslt, GenesisSmartReader genesisSmartReader)
{
try
{
if (tstRslt == null || tstRslt.CalibFactorResultsToSave == null)
{
log.Error("StoreCalibrationValuesResults() - Missing TestRslt OR CalibFactorResultsToSave");
return;
}
for (int i = 0; i < tstRslt.CalibFactorResultsToSave.Count; i++)
{
ushort calibFactor = 0;
switch (i)
{
case 0:
calibFactor = Convert.ToUInt16(genesisSmartReader.Q3Calib_Ch1Value);
break;
case 1:
calibFactor = Convert.ToUInt16(genesisSmartReader.Q3Calib_Ch2Value);
break;
case 2:
calibFactor = Convert.ToUInt16(genesisSmartReader.Q3Calib_Ch3Value);
break;
}
tstRslt.CalibFactorResultsToSave[i].CalculatedCalibFactor = calibFactor;
tstRslt.CalibFactorResultsToSave[i].IsCalibFactorValid = genesisSmartReader.Q3CalibValid;
tstRslt.CalibFactorResultsToSave[i].Error = genesisSmartReader.Q3CalibDiffPercentageValue[i];
log.Debug($"StoreCalibrationValuesResults() - CalibFactor: {i} - CalibFactor: {calibFactor} - Q3CalibValid: {genesisSmartReader.Q3CalibValid} - Q3CalibDiffPercentageValue: {genesisSmartReader.Q3CalibDiffPercentageValue[i]}");
}
}
catch (Exception ex)
{
log.Error("StoreCalibrationValuesResults() - Exception:", ex);
}
}
public string PrepareQ3Calibration(TestMethodCfg cfg, Test test, WaterMeter wm)
{
log.Debug("PrepareQ3Calibration() - Start, Head: " + genesisHead?.Name);
if (genesisHead != null && genesisHead.DebugLevel == DebugMode.Simulate)
{
log.Debug("Connect() - Simulated response");
log.Debug("PrepareQ3Calibration() - Simulated response - Config: " + cfg.ToString() + " Test: " + test.ToString() + " WaterMeter: " + wm.ToString());
try
{
Results.Entities.TestRslt tstRslt = ProcessData.BatchRslts.GetTestRslt(test.Name, test.Part);
if (tstRslt.CalibFactorResultsToSave.Count > 0)
{
tstRslt.CalibFactorResultsToSave.Clear();
}
if (tstRslt.CalibFactorResultsToSave.Count == 0)
{
for (int i = 0; i < genesisHead.ChannelsCount; i++)
{
tstRslt.CalibFactorResultsToSave.Add(new TestRsltCalibFactor()
{
Stored = false,
CalibFactorIndex = i,
BaseCalibFactor = 15625,
}
);
}
}
}catch(Exception ex)
{
log.Error($"PrepareQ3Calibration() - Simulated DB Exception: {ex.Message}");
}
return ResultOk;//"Simulated Connect";
}
return Task.Run(() => PrepareQ3Calibration_Async(genesisHead, cfg, test))
if (cfg == null)
{
log.Error($"PrepareQ3Calibration({genesisHead?.Name}) - Missing TestMethodCfg");
return "PrepareQ3Calibration - Missing TestMethodCfg";
}
if (test == null)
{
log.Error($"PrepareQ3Calibration({genesisHead?.Name}) - Missing Test");
return "PrepareQ3Calibration - Missing Test";
}
return Task.Run(() => PrepareQ3Calibration_Async(genesisHead, cfg, test, wm))
.GetAwaiter()
.GetResult();
}
private async Task<string> PrepareQ3Calibration_Async(
GenesisSmartReader genesisSmartReader,
private async Task<string> PrepareQ3Calibration_Async(GenesisSmartReader genesisSmartReader,
TestMethodCfg cfg,
Test test)
Test test, WaterMeter wm)
{
try
{
log.Debug("PrepareQ3Calibration_Async called for iHead: " + genesisHead);
log.Debug("PrepareQ3Calibration_Async called for iHead: " + genesisHead?.Name + ", cfg: " + cfg?.Name + ", test: " + test?.Name);
if (genesisHead == null) return string.Empty;
if (string.IsNullOrEmpty(genesisHead.CommInterface)) return string.Empty;
GciBridge gciBridge = genesisHead.CommInterfaceBridge;
if (gciBridge == null) return string.Empty;
if (test == null) return "Valid Test Missing!";
Results.Entities.TestRslt tstRslt = ProcessData.BatchRslts.GetTestRslt(test.Name, test.Part);
log.Debug($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Test: {test.Name} - Part: {test.Part} - IsTestRslt: {(tstRslt==null?true:false)}");
if (tstRslt.CalibFactorResultsToSave.Count == 0)
if (genesisHead == null)
{
for (int i = 0; i < genesisSmartReader.ChannelsCount; i++)
{
tstRslt.CalibFactorResultsToSave.Add(new TestRsltCalibFactor());
}
log.Error("PrepareQ3Calibration_Async() - Missing GenesisSmartReader");
return string.Empty;
}
if (string.IsNullOrEmpty(genesisHead.CommInterface))
{
log.Error("PrepareQ3Calibration_Async() - Missing CommInterface");
return string.Empty;
}
GciBridge gciBridge = genesisHead.CommInterfaceBridge;
if (gciBridge == null)
{
log.Error("PrepareQ3Calibration_Async() - Missing GciBridge");
return string.Empty;
}
Results.Entities.TestRslt tstRslt = null;
try
{
if (test == null)
{
log.Error($"PrepareQ3Calibration_Async({genesisHead?.Name}) - Missing Test");
return "Valid Test Missing!";
}
tstRslt = ProcessData.BatchRslts.GetTestRslt(test.Name, test.Part);
log.Debug($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Test: {test.Name} - Part: {test.Part} - IsTestRslt: {(tstRslt==null?true:false)}");
if (tstRslt?.CalibFactorResultsToSave?.Count > 0)
{
tstRslt?.CalibFactorResultsToSave.Clear();
}
if (tstRslt?.CalibFactorResultsToSave?.Count == 0)
{
for (int i = 0; i < genesisSmartReader.ChannelsCount; i++)
{
tstRslt.CalibFactorResultsToSave.Add(new TestRsltCalibFactor()
{
Stored = false,
CalibFactorIndex = i
}
);
}
}
}
catch (Exception ex)
{
log.Error($"PrepareQ3Calibration_Async({genesisSmartReader.GetSlotNr}) - DB TestRslt Exception:", ex);
return ex.Message;
}
CancellationToken token = default;
//Get Activity Status
LedState ledMode = LedState.active; // swich on LED
byte valueLed = (ledMode == LedState.active) ? (byte)6 : (byte)0;
//TODO BUMI - implement variable values for Q3Calibration
//TODO BUMI - implement variable values for Q3Channel
UInt16 valueSampleRate = 10;
//TODO BUMI - implement variable values for Q3Calibration - be shure is implemented in Head
string prepareMeterSizeAndCalibration = await PrepareMeterSizeAndCalibration(genesisSmartReader, cfg, gciBridge, token);
//TODO BUMI - implement variable values for Q3Channel - be shure is implemented in Head
string prepareMeterSizeAndCalibration = await PrepareMeterSizeAndCalibration(genesisSmartReader, cfg, gciBridge, tstRslt, token);
if (prepareMeterSizeAndCalibration != ResultOk)
{
log.Error($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - prepareMeterSizeAndCalibration failed. Result: {prepareMeterSizeAndCalibration}");
return prepareMeterSizeAndCalibration;
}
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start - Set Led Mode: {valueLed}");
var CalFactor1AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor1, genesisSmartReader.Q3CalibValue[0], false, false, token);
ushort calibrationFactor1 = Convert.ToUInt16(genesisSmartReader?.Q3CalibValue[0]);
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start - Set CalFactor1: {calibrationFactor1}");
var CalFactor1AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor1, calibrationFactor1, false, false, token);
if (CalFactor1AsyncResult == null || !CalFactor1AsyncResult.Success)
{
log.Error( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - CalFactor1AsyncResult failed. Result: {CalFactor1AsyncResult}");
return "Failed to disable Led Mode";
}
var CalFactor2AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor2, genesisSmartReader.Q3CalibValue[1], false, false, token);
//CH1 to DB
try
{
if (tstRslt != null &&
tstRslt?.CalibFactorResultsToSave?.Count == 3 &&
tstRslt?.CalibFactorResultsToSave?[0] != null)
{
tstRslt.CalibFactorResultsToSave[0].BaseCalibFactor = Convert.ToInt32(calibrationFactor1);
tstRslt.CalibFactorResultsToSave[0].Stored = false;
}
//wm.OrigCalibFactor = calibrationFactor1; // now dosabled
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB Stored tstRslt:{tstRslt.Name()} - CalFactor1: {calibrationFactor1}");
}
catch (Exception ex)
{
log.Error($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB CH1 Exception:", ex);
}
ushort calibrationFactor2 = Convert.ToUInt16(genesisSmartReader?.Q3CalibValue[1]);
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start - Set CalFactor2: {calibrationFactor2}");
var CalFactor2AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor2, calibrationFactor2, false, false, token);
if (CalFactor2AsyncResult == null || !CalFactor2AsyncResult.Success)
{
log.Error( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - CalFactor2AsyncResult failed. Result: {CalFactor2AsyncResult}");
return "Failed to disable Led Mode";
}
//CH2 to DB
try
{
if (tstRslt != null &&
tstRslt?.CalibFactorResultsToSave?.Count == 3 &&
tstRslt?.CalibFactorResultsToSave?[1] != null)
{
tstRslt.CalibFactorResultsToSave[1].BaseCalibFactor = Convert.ToInt32(calibrationFactor2);
tstRslt.CalibFactorResultsToSave[1].Stored = false;
}
//wm.CalibFactorLNA = calibrationFactor2; // now dosabled
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB Stored tstRslt:{tstRslt.Name()} - CalFactor2: {calibrationFactor2}");
}
catch (Exception ex)
{
log.Error($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB CH2 Exception:", ex);
}
var CalFactor3AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor3, genesisSmartReader.Q3CalibValue[2], false, false, token);
ushort calibrationFactor3 = Convert.ToUInt16(genesisSmartReader?.Q3CalibValue[2]);
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - Start - Set CalFactor1: {calibrationFactor3}");
var CalFactor3AsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.CalFactor3, calibrationFactor3, false, false, token);
if (CalFactor3AsyncResult == null || !CalFactor3AsyncResult.Success)
{
log.Error( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - CalFactor3AsyncResult failed. Result: {CalFactor3AsyncResult}");
return "Failed to disable Led Mode";
}
//CH3 to DB
try
{
if (tstRslt != null &&
tstRslt?.CalibFactorResultsToSave?.Count == 3 &&
tstRslt?.CalibFactorResultsToSave?[2] != null)
{
tstRslt.CalibFactorResultsToSave[2].BaseCalibFactor = Convert.ToInt32(calibrationFactor3);
tstRslt.CalibFactorResultsToSave[2].Stored = false;
}
//wm.CalibFactor = calibrationFactor3; // now dosabled
log.Debug( $"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB Stored tstRslt:{tstRslt.Name()} - CalFactor3: {calibrationFactor3}");
}
catch (Exception ex)
{
log.Error($"PrepareQ3Calibration_Async( Slot: {genesisSmartReader.GetSlotNr}) - DB CH3 Exception:", ex);
}
var SampleRateAsyncResult = await gciBridge.WriteRegisterWithRetryAsync(genesisSmartReader.GetSlotNr, RadioService.SampleRate, valueSampleRate, false, false, token);
if (SampleRateAsyncResult == null || !SampleRateAsyncResult.Success)
@ -1673,66 +2013,82 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.communication
}
private static async Task<string> PrepareMeterSizeAndCalibration(GenesisSmartReader genesisSmartReader, TestMethodCfg cfg,
GciBridge gciBridge, CancellationToken token)
GciBridge gciBridge, Results.Entities.TestRslt tstRslt, CancellationToken token)
{
UInt16 valueCalibrate = 15625; //Predefined Calibration Value
log.Debug( $"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader?.GetSlotNr}) - Start - predefined {valueCalibrate}");
try
{
if (cfg != null)
{
var MeterSizeAsyncResult = await gciBridge.ReadRegisterWithRetryAsync(genesisSmartReader.GetSlotNr,
RadioService.MeterSize, token);
if (MeterSizeAsyncResult == null || !MeterSizeAsyncResult.Success)
{
log.Error($"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Error reading MeterSize register. Result: {MeterSizeAsyncResult}");
return "Error reading MeterSize register";
}
string rawHex = MeterSizeAsyncResult.Result?.RawHex;
if (string.IsNullOrWhiteSpace(rawHex))
{
log.Error(
$"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - MeterSize RawHex is empty");
return "MeterSize RawHex is empty";
}
uint meterSizeRaw = ParseRawHexToUInt32(rawHex);
// If register returns 4 bytes like "00 00 00 02", this gives 2.
// If it returns "02", this also gives 2.
if (meterSizeRaw > ushort.MaxValue)
{
log.Error(
$"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - MeterSize too large. RawHex='{rawHex}', Value={meterSizeRaw}");
return "MeterSize value too large";
}
ushort int16MeterSize = (ushort)meterSizeRaw;
double[] dSize = cfg.GetQ3CalibrationBySizeDoubles(int16MeterSize);
if (dSize == null || dSize.Length != 3)
{
log.Info(
$"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Problem with Q3Calibration calculation. Size: {int16MeterSize}");
return ResultNok;
}
genesisSmartReader
.SetQ3Calibration(dSize); // new double[]{valueCalibrate,valueCalibrate,valueCalibrate}
log.Info(
$"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Based MeterSize: {int16MeterSize} Set Q3Calibration: CH1({dSize[0]}), CH2({dSize[1]}), CH3({dSize[2]})");
}
else
// if (cfg != null)
// {
// var MeterSizeAsyncResult = await gciBridge.ReadRegisterWithRetryAsync(genesisSmartReader.GetSlotNr,
// RadioService.MeterSize, token);
//
// if (MeterSizeAsyncResult == null || !MeterSizeAsyncResult.Success)
// {
// log.Error($"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Error reading MeterSize register. Result: {MeterSizeAsyncResult}");
// return "Error reading MeterSize register";
// }
//
// string rawHex = MeterSizeAsyncResult.Result?.RawHex;
// if (string.IsNullOrWhiteSpace(rawHex))
// {
// log.Error(
// $"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - MeterSize RawHex is empty");
// return "MeterSize RawHex is empty";
// }
//
// uint meterSizeRaw = ParseRawHexToUInt32(rawHex);
//
// // If register returns 4 bytes like "00 00 00 02", this gives 2.
// // If it returns "02", this also gives 2.
// if (meterSizeRaw > ushort.MaxValue)
// {
// log.Error(
// $"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - MeterSize too large. RawHex='{rawHex}', Value={meterSizeRaw}");
// return "MeterSize value too large";
// }
//
// ushort int16MeterSize = (ushort)meterSizeRaw;
//
// double[] dSize = cfg.GetQ3CalibrationBySizeDoubles(int16MeterSize);
// if (dSize == null || dSize.Length != 3)
// {
// log.Info(
// $"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Problem with Q3Channel calculation. Size: {int16MeterSize}");
// return ResultNok;
// }
//
// genesisSmartReader .SetQ3Calibration(dSize); // new double[]{valueCalibrate,valueCalibrate,valueCalibrate}
// for (int i = 0; i < genesisSmartReader.ChannelsCount; i++)
// {
// tstRslt.CalibFactorResultsToSave[i].BaseCalibFactor = Convert.ToInt32(dSize[i]);
// }
//
// log.Info(
// $"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Based MeterSize: {int16MeterSize} Set Q3Channel: CH1({dSize[0]}), CH2({dSize[1]}), CH3({dSize[2]})");
// }
// else
{
genesisSmartReader.SetQ3Calibration(new double[]
{ valueCalibrate, valueCalibrate, valueCalibrate });
for (int i = 0; i < genesisSmartReader.ChannelsCount; i++)
{
if(tstRslt != null && tstRslt?.CalibFactorResultsToSave[i] != null)
tstRslt.CalibFactorResultsToSave[i].BaseCalibFactor = Convert.ToInt32(valueCalibrate);
}
log.Info( $"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Hard Set Q3Channel: CH1({valueCalibrate}), CH2({valueCalibrate}), CH3({valueCalibrate})");
}
}catch(Exception ex)
{
log.Error($"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Error during Q3Calibration calculation: {ex.Message}");
log.Error($"PrepareMeterSizeAndCalibration( Slot: {genesisSmartReader.GetSlotNr}) - Error during Q3Channel calculation: {ex.Message}");
genesisSmartReader.SetQ3Calibration(new double[]
{ valueCalibrate, valueCalibrate, valueCalibrate });
for (int i = 0; i < genesisSmartReader.ChannelsCount; i++)
{
tstRslt.CalibFactorResultsToSave[i].BaseCalibFactor = Convert.ToInt32(valueCalibrate);
}
return ResultNok;
}

View File

@ -1340,16 +1340,6 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
void DataStreamPostProcessing()
{
PrepareCalculatedChannelData();
try
{
log.DebugFormat("DataStreamPostProcessing() - harcoded call GetQ3Calibration(200.0, 120.0, 17969.0);");
SetQ3Calibration(new double[]{17969.0,17969.0,17969.0 });
CalculateQ3Calibration(200.0, 120.0);
}
catch (Exception ex)
{
log.Error($"DataStreamPostProcessing -- Q3 CALIBRATION -- failed: {ex}");
}
}
/// <summary>
@ -1883,7 +1873,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
_readLoopTask = Task.Run(() =>
{
log.Debug($"OPTHO {OptoComPortNr} background read loop started.");
logStream.Debug($"OPTHO {OptoComPortNr} background read loop started.");
while (!token.IsCancellationRequested)
{
@ -1939,12 +1929,12 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
catch (Exception ex)
{
log.Error($"OPTHO {OptoComPortNr} background read error: {ex.Message}");
logStream.Error($"OPTHO {OptoComPortNr} background read error: {ex.Message}");
Thread.Sleep(100);
}
}
log.Debug($"OPTHO {OptoComPortNr} background read loop stopped.");
logStream.Debug($"OPTHO {OptoComPortNr} background read loop stopped.");
}, token);
}
@ -2025,7 +2015,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
{
try
{
log.Debug($"OPTHO {OptoComPortNr} processing loop started.");
logStream.Debug($"OPTHO {OptoComPortNr} processing loop started.");
while (!token.IsCancellationRequested)
{
@ -2055,14 +2045,14 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
if (blockCompleted)
{
log.Debug("Processing loop completed flow block detected.");
logStream.Debug("Processing loop completed flow block detected.");
if (resetSerialBuffersOnCompletedFlowBlock)
ResetDataBuffer();
}
}
catch (Exception ex)
{
log.Error($"Processing loop failed: {ex}");
logStream.Error($"Processing loop failed: {ex}");
}
continue;
@ -2076,16 +2066,16 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
catch (Exception ex)
{
log.Error($"OPTHO {OptoComPortNr} processing loop error: {ex}");
logStream.Error($"OPTHO {OptoComPortNr} processing loop error: {ex}");
Thread.Sleep(50);
}
}
log.Debug($"OPTHO {OptoComPortNr} processing loop stopped.");
logStream.Debug($"OPTHO {OptoComPortNr} processing loop stopped.");
}
catch (Exception ex)
{
log.Error($"StartProcessingLoop fatal error: {ex}");
logStream.Error($"StartProcessingLoop fatal error: {ex}");
}
}, token);
}
@ -2114,13 +2104,13 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
// 🔴 STEP 1: Check if we should start processing
if (startDataProcessing && optoState == DataStreamState.ProcessAndSave)
{
log.DebugFormat("Read Opto Data Line timestamp:{0} to process from queue: {1}",timestamp.ToString("HH:mm:ss.fff") , line);
logStream.DebugFormat("Read Opto Data Line timestamp:{0} to process from queue: {1}",timestamp.ToString("HH:mm:ss.fff") , line);
bool blockCompleted;
ProcessOptoLine(line, optoState, out blockCompleted);
if (blockCompleted)
{
log.Debug("ReadOptoData() completed flow block detected.");
logStream.Debug("ReadOptoData() completed flow block detected.");
if (resetSerialBuffersOnCompletedFlowBlock) // DO NOT call ResetDataBuffer() here
ResetDataBuffer();
}
@ -2128,7 +2118,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
catch (Exception ex)
{
log.Error($"OPTHO {OptoComPortNr} processing queued line failed: {ex.Message}");
logStream.Error($"OPTHO {OptoComPortNr} processing queued line failed: {ex.Message}");
}
}
}
@ -2144,7 +2134,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
var encoding = optoSerialPort?.Encoding ?? Encoding.ASCII;
byte[] bytes = encoding.GetBytes(line);
log.Debug("ComPort: " + OptoComPortNr + " OPTHO RX ← " + HexFormatter.ToSerialHex(bytes));
logStream.Debug("ComPort: " + OptoComPortNr + " OPTHO RX ← " + HexFormatter.ToSerialHex(bytes));
var streamingDecode = new StreamingDecoder(true);
streamingDecode.DecodeMsg(line);
@ -2154,14 +2144,14 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
if (streamingDecode.DataFlowTest != null && streamingDecode.DataFlowTest.IsValid)
{
blockCompleted = HandleFlowMarker();
log.Debug("ComPort: " + OptoComPortNr + " Decoded Flow data: " + streamingDecode.DataFlowTest +
" OPTHO RX ← " + HexFormatter.ToSerialHex(bytes));
logStream.Debug("ComPort: " + OptoComPortNr + " Decoded Flow data: " + streamingDecode.DataFlowTest +
" OPTHO RX ← " + HexFormatter.ToSerialHex(bytes));
}
if (calibData != null && calibData.IsValid)
{
log.Debug("ComPort: " + OptoComPortNr + " Decoded Calib: " + calibData + " OPTHO RX ← " +
HexFormatter.ToSerialHex(bytes));
logStream.Debug("ComPort: " + OptoComPortNr + " Decoded Calib: " + calibData + " OPTHO RX ← " +
HexFormatter.ToSerialHex(bytes));
MarkCalibrationChannelSeen(calibData.Channel);
}
@ -2181,7 +2171,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
if (optoData[bufferIx] == null)
{
log.ErrorFormat("{0}: optoData[{1}] was null, recreating.", Name, bufferIx);
logStream.ErrorFormat("{0}: optoData[{1}] was null, recreating.", Name, bufferIx);
optoData[bufferIx] = new OptoTelegramRaw();
}
@ -2194,7 +2184,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
int iChanel = calibData.Channel - 1;
if (iChanel >= 0 && iChanel < iChanelsCount)
{
log.Debug(
logStream.Debug(
$"Before UpdateFromSmart ch={iChanel + 1}: " +
$"volumeRawExtLast={volumeRawExtLast[iChanel]}, " +
$"timestampExtLast={timestampExtLast[iChanel]}, " +
@ -2262,7 +2252,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
var encoding = optoSerialPort?.Encoding ?? Encoding.ASCII;
byte[] bytes = encoding.GetBytes(line);
received = HexFormatter.ToSerialHex(bytes);
log.Debug("RX ← " + received);
logStream.Debug("RX ← " + received);
try
{
@ -2271,19 +2261,19 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
CalibrationRecord data = _streamingDecode.DataCalib;
if (data != null && data.IsValid)
{
log.Info($"OPTHO {OptoComPortNr} DataCalib Parsed opto data: " + data + " RX ← " +
received);
logStream.Info($"OPTHO {OptoComPortNr} DataCalib Parsed opto data: " + data + " RX ← " +
received);
MarkCalibrationChannelSeen(data.Channel);
}
FlowTestRecord dataFlow = _streamingDecode.DataFlowTest;
if (dataFlow != null && dataFlow.IsValid)
{
log.Info($"OPTHO {OptoComPortNr} FLOW Parsed opto data: " + dataFlow + " RX ← " + received);
logStream.Info($"OPTHO {OptoComPortNr} FLOW Parsed opto data: " + dataFlow + " RX ← " + received);
if (HandleFlowMarker())
{
log.Debug("ReadOptoData() completed flow block detected.");
logStream.Debug("ReadOptoData() completed flow block detected.");
if (resetSerialBuffersOnCompletedFlowBlock)
ResetDataBuffer(); // no ResetDataBuffer() here
}
@ -2292,7 +2282,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
catch (Exception ex)
{
log.Error($"OPTHO {OptoComPortNr} Read error: {ex.Message}");
logStream.Error($"OPTHO {OptoComPortNr} Read error: {ex.Message}");
}
// string line = optoSerialPort.ReadExisting();
@ -2337,11 +2327,11 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
catch (TimeoutException)
{
log.Debug($"ReadOptoData() OPTHO {OptoComPortNr} timeout - continuing.");
logStream.Debug($"ReadOptoData() OPTHO {OptoComPortNr} timeout - continuing.");
}
catch (Exception ex)
{
log.Error($"ReadOptoData() OPTHO {OptoComPortNr} Read error: {ex.Message}");
logStream.Error($"ReadOptoData() OPTHO {OptoComPortNr} Read error: {ex.Message}");
}
}
@ -2357,11 +2347,11 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
{
optoSerialPort.DiscardInBuffer();
optoSerialPort.DiscardOutBuffer();
log.Debug("-- Reaset Data Buffer --");
logStream.Debug("-- Reaset Data Buffer --");
return;
}
}
log.Debug("-- Reaset Data Buffer - no serial port --");
logStream.Debug("-- Reaset Data Buffer - no serial port --");
}
void ISmartReader.SetNfcInterface()
@ -2387,17 +2377,17 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
byte[] bytes = optoSerialPort.Encoding.GetBytes(line);
string received = HexFormatter.ToSerialHex(bytes);
log.Debug("RX ← " + received);
logStream.Debug("RX ← " + received);
return line;
}
}
catch (TimeoutException)
{
log.Debug($"ReadOptoData() OPTHO {OptoComPortNr} ReadLine timeout (3s) - continuing.");
logStream.Debug($"ReadOptoData() OPTHO {OptoComPortNr} ReadLine timeout (3s) - continuing.");
}
catch (Exception ex)
{
log.Error($"ReadOptoData() OPTHO {OptoComPortNr} Read error: {ex.Message}");
logStream.Error($"ReadOptoData() OPTHO {OptoComPortNr} Read error: {ex.Message}");
}
return string.Empty;
@ -2408,7 +2398,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
if (completedTask == readTask)
return await readTask;
log.Debug("ReadOptoData timeout after " + timeoutMs + " ms");
logStream.Debug("ReadOptoData timeout after " + timeoutMs + " ms");
return string.Empty;
}
@ -2957,7 +2947,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
if (data == null || !data.IsValid)
continue;
log.Info($"OPTHO {OptoComPortNr} Parsed optho data:" + data);
logStream.Info($"OPTHO {OptoComPortNr} Parsed optho data:" + data);
int dch = data.Channel - 1;
if (dch >= 0 && dch < iChanelsCount)
@ -2970,7 +2960,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
catch (Exception ex)
{
log.Warn($"Parsing DiagnosticLedState4Data: {ex.Message}");
logStream.Warn($"Parsing DiagnosticLedState4Data: {ex.Message}");
}
}
}
@ -2981,7 +2971,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
log.Debug($"Try get End Volume! COM: {this.OptoComPortNr}, Volume: {volumeLtr}");
logStream.Debug($"Try get End Volume! COM: {this.OptoComPortNr}, Volume: {volumeLtr}");
if (optoSerialPort != null && optoSerialPort.IsOpen) CloseOptoSerialPort();
if (!Double.IsNaN(volumeLtr[channel0]))
@ -2992,12 +2982,12 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
//Solve roll over
if (endWMState < beginWMState)
{
log.Debug($"Solve roll over! endWMState: {endWMState} < beginWMState: {beginWMState}");
logStream.Debug($"Solve roll over! endWMState: {endWMState} < beginWMState: {beginWMState}");
const double VOL_RANGE_LITERS = 16777216.0 * 0.00025; // 4,194.304 l
endWMState += VOL_RANGE_LITERS;
volumeLtr[channel0] = endWMState;
ReadPulses();
log.Debug(
logStream.Debug(
$"Solve roll over! Upgraded endWMState: {endWMState}, beginWMState: {beginWMState}");
}
}
@ -3006,7 +2996,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
//}
log.Warn("Default NaN value returned! Data Opto stream reading failed!");
logStream.Warn("Default NaN value returned! Data Opto stream reading failed!");
return Double.NaN;
}).ConfigureAwait(false);
}
@ -3016,14 +3006,14 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
{
if (ConfigStruct == null)
{
log.Debug("ConfigStruct is null - created new in ReadSerialNr()");
logStream.Debug("ConfigStruct is null - created new in ReadSerialNr()");
ConfigStruct = new ConfigStruct();
}
return await Task.Run(() =>
{
log.Debug($"Try get Start Volume! COM: {this.OptoComPortNr}");
logStream.Debug($"Try get Start Volume! COM: {this.OptoComPortNr}");
Start();
@ -3044,7 +3034,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
StreamingDecoder _streamingDecode = new StreamingDecoder(true);
_streamingDecode.DecodeMsg(readOptoDataWithTimeout);
CalibrationRecord data = _streamingDecode.DataCalib;
log.Info($"OPTHO {OptoComPortNr} Parsed optho data:" + data);
logStream.Info($"OPTHO {OptoComPortNr} Parsed optho data:" + data);
if (data == null || !data.IsValid)
continue;
@ -3060,7 +3050,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
catch (Exception ex)
{
log.Warn($"Parsing DiagnosticLedState4Data: {ex.Message}");
logStream.Warn($"Parsing DiagnosticLedState4Data: {ex.Message}");
}
}
}
@ -3070,7 +3060,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
}
log.Debug($"Try get Start Volume! COM: {this.OptoComPortNr}, Volume: {volumeLtr0}");
logStream.Debug($"Try get Start Volume! COM: {this.OptoComPortNr}, Volume: {volumeLtr0}");
if (optoSerialPort != null && optoSerialPort.IsOpen) CloseOptoSerialPort();
if (!Double.IsNaN(volumeLtr0[ch]))
@ -3081,7 +3071,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
//}
log.Warn("Default NaN value returned! Data Opto stream reading failed!");
logStream.Warn("Default NaN value returned! Data Opto stream reading failed!");
return Double.NaN;
}).ConfigureAwait(false);
}
@ -3093,7 +3083,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
if (ConfigStruct == null)
{
log.Debug("ConfigStruct is null - created new in ReadSerialNr()");
logStream.Debug("ConfigStruct is null - created new in ReadSerialNr()");
ConfigStruct = new ConfigStruct();
}
@ -3103,11 +3093,11 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
return await Task.Run(() =>
{
log.Debug($"Try get ReadSerialNr! COM: {this.RfidComPortNr}");
logStream.Debug($"Try get ReadSerialNr! COM: {this.RfidComPortNr}");
SerialNr = OptoHeadTest.ReadRequest_PCB();
if (string.IsNullOrEmpty(SerialNr))
{
log.Debug("ReadSerialNr successful");
logStream.Debug("ReadSerialNr successful");
}
//optoHeadTest.CloseConnection();
@ -3933,6 +3923,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
private double[] q3CalibInitial = {Double.NaN,Double.NaN,Double.NaN};
private bool[] isChQ3CalibValid = { false,false,false};
private double[] q3CalibCh = {Double.NaN,Double.NaN,Double.NaN};
private double[] q3DiffPercentageCalibCh = {Double.NaN,Double.NaN,Double.NaN};
public bool Q3CalibValid
@ -3950,6 +3941,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
}
public double[] Q3CalibValue { get => q3CalibInitial; }
public double[] Q3CalibDiffPercentageValue { get => q3DiffPercentageCalibCh; }
public bool Q3Calib_Ch1Valid { get => isChQ3CalibValid[0]; }
public bool Q3Calib_Ch2Valid { get => isChQ3CalibValid[1]; }
@ -3960,7 +3952,7 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
public int GetSlotNr { get => genesisHeadCfg?.SlotNr ?? -1; }
//TODO BUMI implement variable values for Q3Calibration!
//TODO BUMI implement variable values for Q3Channel!
public void SetQ3Calibration(double[] q3CalibInitial) { this.q3CalibInitial = q3CalibInitial; }
private double refVolume = double.NaN;
@ -3983,10 +3975,10 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
public void CalculateQ3Calibration(double refVolume, double refTime)
{
GetQ3Calibration(refVolume, refTime, q3CalibInitial, ref isChQ3CalibValid, ref q3CalibCh);
GetQ3Calibration(refVolume, refTime, q3CalibInitial, ref isChQ3CalibValid,ref q3DiffPercentageCalibCh, ref q3CalibCh);
}
public void GetQ3Calibration(double refVolume, double refTime, double[] initCalibFactor, ref bool[] isChQ3CalibValid, ref double[] q3CalibCh)
public void GetQ3Calibration(double refVolume, double refTime, double[] initCalibFactor, ref bool[] isChQ3CalibValid, ref double[] calibDiffPercent, ref double[] q3CalibCh)
{
log.Debug("=== Q3 CALIBRATION START ===");
@ -4096,9 +4088,9 @@ namespace TBF.Rig.RegisterReaders.GenesisRegReader.implementations
q3CalibCh[iChannel] = (refVolume / recalculatedDeltaVolume) * initCalibFactor[iChannel];
double diffPercent = Math.Abs((initCalibFactor[iChannel] - q3CalibCh[iChannel] ) / initCalibFactor[iChannel]) * 100.0;
isChQ3CalibValid[iChannel] = diffPercent <= 5.0;
isChQ3CalibValid[iChannel] = diffPercent <= 5.0 && diffPercent >= -5.0;
calibDiffPercent[iChannel] = diffPercent;
log.Debug($"Calculated Q3Calib Ch[{iChannel}] ={q3CalibCh[iChannel]} DiffPercent={diffPercent}% isValid[{isChQ3CalibValid[iChannel]}] IninitCalibFactor={initCalibFactor}");
}
log.Debug("=== Q3 CALIBRATION END ===");

View File

@ -962,6 +962,7 @@ namespace TBF.Rig.TestMethods.FlyingStart
WMPosition = wmNrChX,
YearOfProduction = 0,
Disabled = false,
Q3Channel = iCH + 1
};
chXWaterMeter.CopyContentFrom(waterMeterParent);
@ -980,6 +981,7 @@ namespace TBF.Rig.TestMethods.FlyingStart
//create copy of meterRslt and add to additionalResultsByChannel
MeterTestRslt meterTestRsltChX = new MeterTestRslt(chXWaterMeter, meterRslt.TestRslt, (CompoundMeterId)meterRslt.CompoundMeterId);
meterTestRsltChX.Q3Channel = iCH + 1;
chXWaterMeter.MeterTestRslts.Add(meterTestRsltChX);
MeterTestRslt chanelXMeterRslt = BatchRslts.GetMeterTestRslt(testName, wmNrChX-1, Common.CompoundMeterId.Single);
@ -990,52 +992,67 @@ namespace TBF.Rig.TestMethods.FlyingStart
{
CalculateMeterResults(chanelXMeterRslt, genesisSmart, tstRslt, genesisSmart.TimestampSecStartRawCh1,
genesisSmart.TimestampSecEndRawCh1, genesisSmart.VolumeLtrStartRawCh1, genesisSmart.VolumeLtrEndRawCh1);
//store in table
TestRsltCalibFactor testRsltCalibFactor = new TestRsltCalibFactor()
TestRsltCalibFactor testRsltCalibFactor = null;
if (tstRslt.CalibFactorResultsToSave.Count > 0)
{
TestRslt = chanelXMeterRslt.TestRslt,
TimeStart = genesisSmart.TimestampSecStartRawCh1,
TimeEnd = genesisSmart.TimestampSecEndRawCh1,
VolumeStart = genesisSmart.VolumeLtrStartRawCh1,
VolumeEnd = genesisSmart.VolumeLtrEndRawCh1,
};
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
testRsltCalibFactor = tstRslt.CalibFactorResultsToSave[0];
}
else
{
//store in table
testRsltCalibFactor = new TestRsltCalibFactor();
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
}
testRsltCalibFactor.TestRslt = chanelXMeterRslt.TestRslt;
testRsltCalibFactor.TimeStart = genesisSmart.TimestampSecStartRawCh1;
testRsltCalibFactor.TimeEnd = genesisSmart.TimestampSecEndRawCh1;
testRsltCalibFactor.VolumeStart = genesisSmart.VolumeLtrStartRawCh1;
testRsltCalibFactor.VolumeEnd = genesisSmart.VolumeLtrEndRawCh1;
}
else if (iCH == 1)
{
CalculateMeterResults(chanelXMeterRslt, genesisSmart, tstRslt, genesisSmart.TimestampSecStartRawCh2,
genesisSmart.TimestampSecEndRawCh2, genesisSmart.VolumeLtrStartRawCh2, genesisSmart.VolumeLtrEndRawCh2);
//store in table
TestRsltCalibFactor testRsltCalibFactor = new TestRsltCalibFactor()
TestRsltCalibFactor testRsltCalibFactor = null;
if (tstRslt.CalibFactorResultsToSave.Count > 1)
{
TestRslt = chanelXMeterRslt.TestRslt,
TimeStart = genesisSmart.TimestampSecStartRawCh2,
TimeEnd = genesisSmart.TimestampSecEndRawCh2,
VolumeStart = genesisSmart.VolumeLtrStartRawCh2,
VolumeEnd = genesisSmart.VolumeLtrEndRawCh2,
};
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
testRsltCalibFactor = tstRslt.CalibFactorResultsToSave[1];
}
else
{
//store in table
testRsltCalibFactor = new TestRsltCalibFactor();
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
}
testRsltCalibFactor.TestRslt = chanelXMeterRslt.TestRslt;
testRsltCalibFactor.TimeStart = genesisSmart.TimestampSecStartRawCh2;
testRsltCalibFactor.TimeEnd = genesisSmart.TimestampSecEndRawCh2;
testRsltCalibFactor.VolumeStart = genesisSmart.VolumeLtrStartRawCh2;
testRsltCalibFactor.VolumeEnd = genesisSmart.VolumeLtrEndRawCh2;
}
else if (iCH == 2)
{
CalculateMeterResults(chanelXMeterRslt, genesisSmart, tstRslt, genesisSmart.TimestampSecStartRawCh3,
genesisSmart.TimestampSecEndRawCh3, genesisSmart.VolumeLtrStartRawCh3, genesisSmart.VolumeLtrEndRawCh3);
//store in table
TestRsltCalibFactor testRsltCalibFactor = new TestRsltCalibFactor()
TestRsltCalibFactor testRsltCalibFactor = null;
if (tstRslt.CalibFactorResultsToSave.Count > 2)
{
TestRslt = chanelXMeterRslt.TestRslt,
TimeStart = genesisSmart.TimestampSecStartRawCh3,
TimeEnd = genesisSmart.TimestampSecEndRawCh3,
VolumeStart = genesisSmart.VolumeLtrStartRawCh3,
VolumeEnd = genesisSmart.VolumeLtrEndRawCh3,
};
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
testRsltCalibFactor = tstRslt.CalibFactorResultsToSave[2];
}
else
{
//store in table
testRsltCalibFactor = new TestRsltCalibFactor();
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
}
testRsltCalibFactor.TestRslt = chanelXMeterRslt.TestRslt;
testRsltCalibFactor.TimeStart = genesisSmart.TimestampSecStartRawCh3;
testRsltCalibFactor.TimeEnd = genesisSmart.TimestampSecEndRawCh3;
testRsltCalibFactor.VolumeStart = genesisSmart.VolumeLtrStartRawCh3;
testRsltCalibFactor.VolumeEnd = genesisSmart.VolumeLtrEndRawCh3;
}
if (!genesisSmart.EnableShowChanels)

View File

@ -1396,30 +1396,81 @@ namespace TBF.Rig.TestMethods.FlyingStartMassCollection
chanelXMeterRslt?.CopyContentFrom(meterRslt);
if (iCH == 0)
{
chanelXMeterRslt.Q3Channel = 1;
CalculateMeterResults(chanelXMeterRslt, genesisSmart, tstRslt, genesisSmart.TimestampSecStartRawCh1,
genesisSmart.TimestampSecEndRawCh1, genesisSmart.VolumeLtrStartRawCh1, genesisSmart.VolumeLtrEndRawCh1);
//store in table
TestRsltCalibFactor testRsltCalibFactor = new TestRsltCalibFactor()
TestRsltCalibFactor testRsltCalibFactor = null;
if (tstRslt.CalibFactorResultsToSave.Count > 0)
{
TestRslt = chanelXMeterRslt.TestRslt,
TimeStart = genesisSmart.TimestampSecStartRawCh1,
TimeEnd = genesisSmart.TimestampSecEndRawCh1,
VolumeStart = genesisSmart.VolumeLtrStartRawCh1,
VolumeEnd = genesisSmart.VolumeLtrEndRawCh1,
};
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
testRsltCalibFactor = tstRslt.CalibFactorResultsToSave[0];
}
else
{
//store in table
testRsltCalibFactor = new TestRsltCalibFactor();
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
testRsltCalibFactor.CalibFactorIndex = 1;
}
testRsltCalibFactor.TestRslt = chanelXMeterRslt.TestRslt;
testRsltCalibFactor.TimeStart = genesisSmart.TimestampSecStartRawCh1;
testRsltCalibFactor.TimeEnd = genesisSmart.TimestampSecEndRawCh1;
testRsltCalibFactor.VolumeStart = genesisSmart.VolumeLtrStartRawCh1;
testRsltCalibFactor.VolumeEnd = genesisSmart.VolumeLtrEndRawCh1;
testRsltCalibFactor.Error = chanelXMeterRslt.Error;
}
else if (iCH == 1)
{
chanelXMeterRslt.Q3Channel = 2;
CalculateMeterResults(chanelXMeterRslt, genesisSmart, tstRslt, genesisSmart.TimestampSecStartRawCh2,
genesisSmart.TimestampSecEndRawCh2, genesisSmart.VolumeLtrStartRawCh2, genesisSmart.VolumeLtrEndRawCh2);
TestRsltCalibFactor testRsltCalibFactor = null;
if (tstRslt.CalibFactorResultsToSave.Count > 1)
{
testRsltCalibFactor = tstRslt.CalibFactorResultsToSave[1];
}
else
{
//store in table
testRsltCalibFactor = new TestRsltCalibFactor();
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
testRsltCalibFactor.CalibFactorIndex = 2;
}
testRsltCalibFactor.TestRslt = chanelXMeterRslt.TestRslt;
testRsltCalibFactor.TimeStart = genesisSmart.TimestampSecStartRawCh2;
testRsltCalibFactor.TimeEnd = genesisSmart.TimestampSecEndRawCh2;
testRsltCalibFactor.VolumeStart = genesisSmart.VolumeLtrStartRawCh2;
testRsltCalibFactor.VolumeEnd = genesisSmart.VolumeLtrEndRawCh2;
testRsltCalibFactor.Error = chanelXMeterRslt.Error;
}
else if (iCH == 2)
{
chanelXMeterRslt.Q3Channel = 3;
CalculateMeterResults(chanelXMeterRslt, genesisSmart, tstRslt, genesisSmart.TimestampSecStartRawCh3,
genesisSmart.TimestampSecEndRawCh3, genesisSmart.VolumeLtrStartRawCh3, genesisSmart.VolumeLtrEndRawCh3);
TestRsltCalibFactor testRsltCalibFactor = null;
if (tstRslt.CalibFactorResultsToSave.Count > 2)
{
testRsltCalibFactor = tstRslt.CalibFactorResultsToSave[2];
}
else
{
//store in table
testRsltCalibFactor = new TestRsltCalibFactor();
tstRslt.CalibFactorResultsToSave.Add(testRsltCalibFactor);
testRsltCalibFactor.CalibFactorIndex = 3;
}
testRsltCalibFactor.TestRslt = chanelXMeterRslt.TestRslt;
testRsltCalibFactor.TimeStart = genesisSmart.TimestampSecStartRawCh3;
testRsltCalibFactor.TimeEnd = genesisSmart.TimestampSecEndRawCh3;
testRsltCalibFactor.VolumeStart = genesisSmart.VolumeLtrStartRawCh3;
testRsltCalibFactor.VolumeEnd = genesisSmart.VolumeLtrEndRawCh3;
testRsltCalibFactor.Error = chanelXMeterRslt.Error;
}
if (!genesisSmart.EnableShowChanels)
@ -1445,11 +1496,11 @@ namespace TBF.Rig.TestMethods.FlyingStartMassCollection
meterRslt.TestTime = meterRslt.TimestampEnd - meterRslt.TimestampStart;
meterRslt.VolumeStart = dstrReaderVolumeLtrStart; /// liter
meterRslt.VolumeEnd = dstrReaderVolumeLtrEnd; /// liter
meterRslt.VolumeMeter =
Math.Abs(dstrReaderVolumeLtrEnd - dstrReaderVolumeLtrStart);
meterRslt.VolumeMeter = Math.Abs(dstrReaderVolumeLtrEnd - dstrReaderVolumeLtrStart);
meterRslt.VolumeRef = tstRslt.TestTime==0? tstRslt.VolumeCTV : tstRslt.VolumeCTV * meterRslt.TestTime / tstRslt.TestTime;
meterRslt.PulsesMaster = tstRslt.TestTime == 0? tstRslt.PulsesMaster :
tstRslt.PulsesMaster * meterRslt.TestTime / tstRslt.TestTime;
meterRslt.Error = Formulas.ErrorFromVolumes(meterRslt.VolumeMeter, meterRslt.VolumeRef); // Error based on volume difference
}

View File

@ -50,6 +50,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication
if (decoded.IsOk)
{
string asciiPayload = decoded.GetAsciiPayload();
iHead.SerialNr = asciiPayload;
if (iHead.ConfigStruct != null) // store mechanism
{
iHead.ConfigStruct.PCBNumberString = asciiPayload;

View File

@ -65,6 +65,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
FailedSetActiveMode, /// 1AH = 26
FailedWriteCalibrationFactor,/// 1BH = 27
FailedWriteRegister,/// 1CH = 28
FailedPrepare, /// 1DH = 29
}
@ -818,7 +819,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
else if (currentActivity.ToLower().Equals(SlotSetActiveModeStr.ToLower()))error = SlotSetActiveMode(threadID, ihead, ref resultStr);
else if (currentActivity.ToLower().Equals(SlotDisconnectStr.ToLower())) error = SlotDisconnect(threadID, ihead, ref resultStr);
else if (currentActivity.ToLower().Equals(PrepareSlotQ3CalibrationStr.ToLower())) error = PrepareSlotQ3Calibration(threadID, ihead,wm, currentTest, tests , ref resultStr);
else if (currentActivity.ToLower().Equals(WriteSlotQ3CalibrationStr.ToLower())) error = WriteSlotQ3Calibration(threadID, ihead, ref resultStr);
else if (currentActivity.ToLower().Equals(WriteSlotQ3CalibrationStr.ToLower())) error = WriteSlotQ3Calibration(threadID, ihead, wm, currentTest, tests, ref resultStr);
else if (currentActivity.ToLower().Equals(CheckMeterPrepareStr.ToLower())) error = CheckMeterPrepare(threadID, ihead, ref resultStr);
else if (currentActivity.ToLower().Contains(ReadSerialNrStr.ToLower())) error = ReadSerialNr(threadID, ihead, ref resultStr);
@ -876,9 +877,11 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
(error == CommErr.FailedSetTestMode)||
(error == CommErr.FailedSetActiveMode)||
(error == CommErr.FailedWriteRegister)||
(error == CommErr.FailedWriteCalibrationFactor))
(error == CommErr.FailedWriteCalibrationFactor) ||
(error == CommErr.FailedPrepare)
)
{
OnCommCompleted(null, new CommCompletedEventArgs(threadID, wmNr0, ihead, wm, resultStr, CommErr.FailedInit));
OnCommCompleted(null, new CommCompletedEventArgs(threadID, wmNr0, ihead, wm, resultStr, error));
}
else if (ihead.CommFailed || (error == CommErr.CommFailed))
{
@ -916,6 +919,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
{
OnCommCompleted(null, new CommCompletedEventArgs(threadID, -1, null, null, string.Empty, CommErr.None)); /// Send negative wmNr
}
Thread.Sleep( 2000);
if (stopWorkerThreads) break;
}
@ -1024,57 +1029,113 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
private CommErr PrepareSlotQ3Calibration(int threadId, GenesisSmartReader iHead, WaterMeter wm,
Test currentTest, IList<Test> tests, ref string resultStr)
{
CommErr error = CommErr.FailedLogin;
CommErr error = CommErr.FailedPrepare;
//TODO BUMI get Next test method
Test NextTest = null;
bool bNextChatch = false;
foreach (Test test in tests)
log.InfoFormat("PrepareSlotQ3Calibration() threadId={0}", threadId);
try
{
if (test.Equals(currentTest))
//there is only currecnt test method
//find all tests in Procedure and set the test method
log.Debug($"StateMachne Procedure:{StateMachine.Procedure?.Name}");
log.Debug($"StateMachne TestInstances:{StateMachine.TestInstances?.Length}");
IList<Test> procedureTests = StateMachine.Procedure?.Tests;
Test NextTest = null;
bool bNextChatch = false;
foreach (Test test in procedureTests)
{
bNextChatch = true;
continue;
if (test.Equals(currentTest))
{
bNextChatch = true;
continue;
}
if (bNextChatch)
{
NextTest = test;
break;
}
}
var gciFullLoginResult = iHead.OptoHeadTest.PrepareQ3Calibration(cfg, NextTest, wm);
if (!string.IsNullOrEmpty(resultStr) &&
resultStr.Equals(TBF.Rig.RegisterReaders.GenesisRegReader.communication.OptoHeadTest.ResultOk))
{
log.DebugFormat("PrepareQ3Calibration successfull threadId={0}", threadId);
resultStr = string.Format($"Write Q3 Calibration: OK");
// note Q3 calibration is done
error = CommErr.None;
}
else
{
resultStr = "Write Q3 Calibration: Failed";
}
if (bNextChatch)
{
NextTest = test;
break;
}
}
var gciFullLoginResult = iHead.OptoHeadTest.PrepareQ3Calibration(cfg,NextTest);
if (!string.IsNullOrEmpty(resultStr) && resultStr.Equals(TBF.Rig.RegisterReaders.GenesisRegReader.communication.OptoHeadTest.ResultOk))
return error;
}catch (Exception ex)
{
log.Debug("SlotLogin successful");
resultStr = string.Format($"Write Q3 Calibration: OK");
// note Q3 calibration is done
error = CommErr.None;
log.ErrorFormat("PrepareSlotQ3Calibration() threadId={0}, Error: {1}", threadId, ex.Message);
return CommErr.FailedPrepare;
}
else
{
resultStr = "Write Q3 Calibration: Failed";
}
return error;
}
private CommErr WriteSlotQ3Calibration(int threadId, GenesisSmartReader iHead, ref string resultStr)
private CommErr WriteSlotQ3Calibration(int threadId, GenesisSmartReader iHead, WaterMeter wm,
Test currentTest, IList<Test> tests, ref string resultStr)
{
CommErr error = CommErr.FailedWriteCalibrationFactor;
var gciFullLoginResult = iHead.OptoHeadTest.WriteQ3Calibration();
if (!string.IsNullOrEmpty(resultStr) && resultStr.Equals(TBF.Rig.RegisterReaders.GenesisRegReader.communication.OptoHeadTest.ResultOk))
log.DebugFormat("WriteSlotQ3Calibration() threadId={0}, iHead: {1}, wm: {2}, currentTest: {3}, tests: {4}", threadId, iHead?.Name, wm?.Id, currentTest?.Name, tests?.Count);
//TODO BUMI get Before test method
try
{
log.Debug("SlotLogin successful");
resultStr = string.Format($"Write Q3 Calibration: OK");
// note Q3 calibration is done
error = CommErr.None;
//there is only currecnt test method
//find all tests in Procedure and set the test method
log.Debug($"StateMachne Procedure:{StateMachine.Procedure?.Name}");
log.Debug($"StateMachne TestInstances:{StateMachine.TestInstances?.Length}");
IList<Test> procedureTests = StateMachine.Procedure?.Tests;
Test BeforeTest = null;
foreach (Test test in procedureTests)
{
if (test.Equals(currentTest))
{
log.DebugFormat("WriteSlotQ3Calibration() threadId={0}, currentTest: {1}, BeforeTest: {2}", threadId, currentTest?.Name, BeforeTest?.Name);
break;
}
BeforeTest = test;
}
if (BeforeTest == null)
{
log.DebugFormat($"No Before test method found, we use the current test method threadId={0}, currentTest: {1}", threadId, currentTest?.Name);
BeforeTest = currentTest;
}
var gciFullLoginResult = iHead.OptoHeadTest.WriteQ3Calibration(cfg, BeforeTest, wm);
if (!string.IsNullOrEmpty(resultStr) &&
resultStr.Equals(TBF.Rig.RegisterReaders.GenesisRegReader.communication.OptoHeadTest.ResultOk))
{
log.Debug("SlotLogin successful");
resultStr = string.Format($"Write Q3 Calibration: OK");
// note Q3 calibration is done
error = CommErr.None;
}
else
{
resultStr = "Write Q3 Calibration: Failed";
}
return error;
}
else
catch (Exception ex)
{
resultStr = "Write Q3 Calibration: Failed";
log.ErrorFormat("WriteSlotQ3Calibration() threadId={0}, Error: {1}", threadId, ex.Message);
return CommErr.FailedWriteCalibrationFactor;
}
return error;
}
private CommErr SlotGroupedLogin(int threadId, GenesisSmartReader iHead, ref string resultStr)
@ -1083,8 +1144,9 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
var gciFullLoginResult = iHead.OptoHeadTest.GroupedLoginSlot();
if (gciFullLoginResult.Success)
{
log.Debug("SlotLogin successful");
log.Debug($"SlotLogin Head:{iHead.Name} successful, PCB: {gciFullLoginResult?.PcbResult?.Result?.PcbId}");
resultStr = string.Format($"Login OK - Serial No: {gciFullLoginResult?.PcbResult?.Result?.PcbId}");
log.Debug($"Setting PCB: {gciFullLoginResult?.PcbResult?.Result?.PcbId} for Head: {iHead.Name}");
iHead.SerialNr = gciFullLoginResult?.PcbResult?.Result?.PcbId;
if (iHead.ConfigStruct != null)
{
@ -1190,8 +1252,16 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
PcbReadResult pcbReadSlot = iHead.OptoHeadTest.PCB_ReadSlot();
if (pcbReadSlot.Success)
{
log.Debug("SlotPCBSlot successful");
resultStr = string.Format($"SlotPCBSlot: {pcbReadSlot.PcbId}");
var pcbId = pcbReadSlot?.PcbId;
log.Debug($"SlotPCBSlot Head:{iHead.Name} successful, PCB:{pcbId}");
resultStr = string.Format($"SlotPCBSlot: {pcbId}");
if (!string.IsNullOrWhiteSpace(pcbId))
{
log.Debug($"Setting PCB: {pcbId} for Head: {iHead.Name}");
iHead.SerialNr = pcbId;
if (iHead.ConfigStruct != null) iHead.ConfigStruct.PCBNumberString = pcbId;
}
error = CommErr.None;
}
else
@ -1256,7 +1326,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
CommErr error = CommErr.Read;
var result = ihead.OptoHeadTest.ReadRequest_PCB();
if (string.IsNullOrEmpty(result))
if (!string.IsNullOrEmpty(result))
{
log.Debug("ReadSerialNr successful");
resultStr = string.Format($"Serial No: {result}");
@ -1612,6 +1682,17 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
checkBoxes[data.WMNr0].Checked = true;
checkBoxes[data.WMNr0].Enabled = false;
}
// else if (data.WMNr0 >= 0 && data.CommErr != CommErr.None)
// {
// //disable if error
// ckbState[data.WMNr0] = false;
// checkBoxes[data.WMNr0].Checked = false;
// checkBoxes[data.WMNr0].Enabled = false;
// if (data.Ihead != null) data.Ihead.Disabled = true;
// if (data.Wm != null) data.Wm.Disabled = true;
// //color
// if (counters.Length > data.WMNr0) counters[data.WMNr0].BackColor = OptoNokColor;
// }
///
/// Update opto-communication indication

View File

@ -186,12 +186,24 @@
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.Genesis.Registers">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.Genesis.Registers.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.WaterMeterCore">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.WaterMeterCore.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Hardware.WaterMeter.WaterMeterRegisters">
<HintPath>..\packages\Common\Xylem.Common.Hardware.WaterMeter.WaterMeterRegisters.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Logic.ProductionOrderCore">
<HintPath>..\packages\Common\Xylem.Common.Logic.ProductionOrderCore.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Ui.CordonelPreadjustmentUi">
<HintPath>..\packages\Common\Xylem.Common.Ui.CordonelPreadjustmentUi.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Utils.Logging">
<HintPath>..\packages\Common\Xylem.Common.Utils.Logging.dll</HintPath>
</Reference>
<Reference Include="Xylem.Common.Utils.Logging, Version=2.8.18.30155, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Common\Xylem.Common.Utils.Logging.dll</HintPath>
@ -250,17 +262,17 @@
<Compile Include="Rig\BridgeComponents\GciBridge\UI\MainView.Designer.cs">
<DependentUpon>MainView.cs</DependentUpon>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\UniDataStorageReaderInterfaceView.cs">
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\UniDataSorageActionsView.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\UniDataStorageReaderInterfaceView.Designer.cs">
<DependentUpon>UniDataStorageReaderInterfaceView.cs</DependentUpon>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\UniDataSorageActionsView.Designer.cs">
<DependentUpon>UniDataSorageActionsView.cs</DependentUpon>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\CombinedInterfaceView.cs">
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\CombinedActionsView.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\CombinedInterfaceView.Designer.cs">
<DependentUpon>CombinedInterfaceView.cs</DependentUpon>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\CombinedActionsView.Designer.cs">
<DependentUpon>CombinedActionsView.cs</DependentUpon>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\ConfigurationView.cs">
<SubType>UserControl</SubType>
@ -268,11 +280,17 @@
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\ConfigurationView.Designer.cs">
<DependentUpon>ConfigurationView.cs</DependentUpon>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\GenesisCordonelInterfaceView.cs">
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\SlotsComPortsRegistersActionsView.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\GenesisCordonelInterfaceView.Designer.cs">
<DependentUpon>GenesisCordonelInterfaceView.cs</DependentUpon>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\SlotsComPortsRegistersActionsView.Designer.cs">
<DependentUpon>SlotsComPortsRegistersActionsView.cs</DependentUpon>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\PreadjustmentActionsView.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\PreadjustmentActionsView.Designer.cs">
<DependentUpon>PreadjustmentActionsView.cs</DependentUpon>
</Compile>
<Compile Include="Rig\BuiltIn\PumpTandem\Pump.cs"/>
<Compile Include="Rig\BuiltIn\PumpTandem\PumpCfg.cs"/>
@ -3299,17 +3317,20 @@
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\MainView.resx">
<DependentUpon>MainView.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\CombinedInterfaceView.resx">
<DependentUpon>CombinedInterfaceView.cs</DependentUpon>
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\CombinedActionsView.resx">
<DependentUpon>CombinedActionsView.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\ConfigurationView.resx">
<DependentUpon>ConfigurationView.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\UniDataStorageReaderInterfaceView.resx">
<DependentUpon>UniDataStorageReaderInterfaceView.cs</DependentUpon>
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\UniDataSorageActionsView.resx">
<DependentUpon>UniDataSorageActionsView.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\GenesisCordonelInterfaceView.resx">
<DependentUpon>GenesisCordonelInterfaceView.cs</DependentUpon>
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\SlotsComPortsRegistersActionsView.resx">
<DependentUpon>SlotsComPortsRegistersActionsView.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Rig\BridgeComponents\GciBridge\UI\StaraTuraAPI_GciBridge\PreadjustmentActionsView.resx">
<DependentUpon>PreadjustmentActionsView.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Rig\BuiltIn\PumpTandem\PumpCfgCtrl.resx">
<DependentUpon>PumpCfgCtrl.cs</DependentUpon>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Calendar4NET</RootNamespace>
<AssemblyName>Calendar</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -135,4 +135,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -83,7 +83,7 @@ namespace TBFTests
TestData testData = new TestData
{
Name = "Q3Calibration",
Name = "Q3Channel",
Repeats = 1,
Method = "SmartCommunication"
};
@ -107,6 +107,7 @@ namespace TBFTests
CalibFactorIndex = 1,
BaseCalibFactor = 15625,
CalculatedCalibFactor = 17969,
IsCalibFactorValid = true,
Stored = true,
ErrorStr = "OK",
TimeStart = 1.1,
@ -142,6 +143,7 @@ namespace TBFTests
Assert.AreEqual(1, loadedCalib.CalibFactorIndex);
Assert.AreEqual(15625, loadedCalib.BaseCalibFactor);
Assert.AreEqual(17969, loadedCalib.CalculatedCalibFactor);
Assert.IsTrue(loadedCalib.IsCalibFactorValid);
Assert.IsTrue(loadedCalib.Stored);
Assert.AreEqual("OK", loadedCalib.ErrorStr);
}

View File

@ -1,14 +1,11 @@
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Config.Entities;
using GenesisCordonelInterface.API;
using JetBrains.Annotations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TBF.Rig.BridgeComponents.GciBridge;
using Results.Entities;
using TBF.Rig.RegisterReaders.GenesisRegReader.communication;
using TBF.Rig.RegisterReaders.GenesisRegReader.implementations;
using TBF.Rig.Sequences;
using TBF.Rig.TestMethods.GenesisCommunication;
namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.communication
@ -91,34 +88,50 @@ namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.communication
[TestMethod]
public void PrepareQ3Calibration_SimulateMode_ReturnsOk()
{
// ARRANGE
GenesisSmartReader reader = new GenesisSmartReader
{
DebugLevel = Common.DebugMode.Simulate
};
Factory factory = new Factory();
GenesisSmartReader reader = new GenesisSmartReader(factory.DefaultConfig());
reader.DebugLevel = Common.DebugMode.Simulate;
OptoHeadTest optoHeadTest = new OptoHeadTest(reader);
TestMethodCfg cfg = new TestMethodCfg(null)
{
CalibFactor6InchCh1 = 17969,
CalibFactor6InchCh2 = 17969,
CalibFactor6InchCh3 = 17969
};
string result = optoHeadTest.PrepareQ3Calibration(null, null, null);
Test test = new Test
{
Name = "Q3Calibration",
Part = 1
};
// ACT
string result = optoHeadTest.PrepareQ3Calibration(cfg, test);
// ASSERT
Assert.AreEqual(OptoHeadTest.ResultOk, result);
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(
OptoHeadTest.ResultOk,
result);
}
[TestMethod]
public void PrepareQ3Calibration_TestStoreDB()
{
GenesisSmartReader reader = new GenesisSmartReader();
Results.Entities.TestRslt tstRslt = new Results.Entities.TestRslt();
Assert.IsNotNull(tstRslt.CalibFactorResultsToSave);
tstRslt.CalibFactorResultsToSave.Clear();
Assert.AreEqual(0, tstRslt.CalibFactorResultsToSave.Count);
if (tstRslt?.CalibFactorResultsToSave?.Count == 0)
{
for (int i = 0; i < reader.ChannelsCount; i++)
{
tstRslt.CalibFactorResultsToSave.Add(new TestRsltCalibFactor()
{
Stored = false,
CalibFactorIndex = i
});
}
}
Assert.AreEqual(reader.ChannelsCount, tstRslt.CalibFactorResultsToSave.Count);
for (int i = 0; i < reader.ChannelsCount; i++)
{
Assert.IsFalse(tstRslt.CalibFactorResultsToSave[i].Stored);
Assert.AreEqual(i, tstRslt.CalibFactorResultsToSave[i].CalibFactorIndex);
}
}
}
}

View File

@ -22,12 +22,15 @@ namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.implementations
var valid = new bool[3];
var calib = new double[3];
var calibDiff = new double[3];
sut.SetQ3Calibration(ValidInitFactors);
sut.GetQ3Calibration(
refVolume: 1000.0,
refTime: 120.0,
initCalibFactor: ValidInitFactors,
200.0,
120.0,
ValidInitFactors,
ref valid,
ref calibDiff,
ref calib);
Assert.IsFalse(sut.Q3CalibValid);
@ -47,12 +50,15 @@ namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.implementations
var valid = new bool[3];
var calib = new double[3];
var calibDiff = new double[3];
sut.SetQ3Calibration(ValidInitFactors);
sut.GetQ3Calibration(
refVolume: 1000.0,
refTime: 120.0,
initCalibFactor: ValidInitFactors,
200.0,
120.0,
ValidInitFactors,
ref valid,
ref calibDiff,
ref calib);
Assert.IsFalse(sut.Q3CalibValid);
@ -70,13 +76,16 @@ namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.implementations
var valid = new bool[3];
var calib = new double[3];
var calibDiff = new double[3];
sut.GetQ3Calibration(
refVolume: 0.0,
refTime: 120.0,
initCalibFactor: ValidInitFactors,
ref valid,
ref calib);
ref calibDiff,
ref calib
);
Assert.IsFalse(sut.Q3CalibValid);
CollectionAssert.AreEqual(new[] { false, false, false }, valid);
@ -93,13 +102,17 @@ namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.implementations
var valid = new bool[3];
var calib = new double[3];
var calibDiff = new double[3];
sut.SetQ3Calibration(ValidInitFactors);
sut.GetQ3Calibration(
refVolume: 1000.0,
refTime: 0.0,
initCalibFactor: ValidInitFactors,
ref valid,
ref calib);
ref calibDiff,
ref calib
);
Assert.IsFalse(sut.Q3CalibValid);
CollectionAssert.AreEqual(new[] { false, false, false }, valid);
@ -117,13 +130,17 @@ namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.implementations
var init = new[] { 0.0, 0.0, 0.0 };
var valid = new bool[3];
var calib = new double[3];
var calibDiff = new double[3];
sut.SetQ3Calibration(ValidInitFactors);
sut.GetQ3Calibration(
refVolume: 1000.0,
refTime: 120.0,
initCalibFactor: init,
ref valid,
ref calib);
ref calibDiff,
ref calib
);
Assert.IsFalse(sut.Q3CalibValid);
CollectionAssert.AreEqual(new[] { false, false, false }, valid);
@ -173,14 +190,19 @@ namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.implementations
var init = new[] { 15625.0, 15625.0, 15625.0 };
var valid = new bool[3];
var calib = new double[3];
var calibDiff = new double[3];
sut.SetQ3Calibration(init);
sut.GetQ3Calibration(
refVolume: 200.0,
refTime: 120.0,
initCalibFactor: init,
ref valid,
ref calib);
ref calibDiff,
ref calib
);
double expectedCh1 = (200.0 / 600.0) * 15625.0;
double expectedCh2 = (200.0 / 600.0) * 15625.0;
double expectedCh3 = (200.0 / 560.0) * 15625.0;
@ -220,12 +242,15 @@ namespace TBFTests.Rig.RegisterReaders.GenesisRegReader.implementations
var init = new[] { 15625.0, 15625.0, 15625.0 };
var valid = new bool[3];
var calib = new double[3];
var calibDiff = new double[3];
sut.SetQ3Calibration(init);
sut.GetQ3Calibration(
refVolume: 200.0,
refTime: 120.0,
initCalibFactor: init,
200.0,
120.0,
init,
ref valid,
ref calibDiff,
ref calib);
Assert.IsTrue(valid[0], $"Ch1 invalid, value={calib[0]}");

View File

@ -113,6 +113,7 @@
</Choose>
<ItemGroup>
<Compile Include="DBTest.cs" />
<Compile Include="Entities\helpers\DatabaseMigrationHelperTest.cs" />
<Compile Include="Entities\MeasurementCorrectionTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Rig\Network\Camera\CJMS11\CameraTest.cs" />

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ToFirstMonitor</RootNamespace>
<AssemblyName>ToFirstMonitor</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -70,4 +70,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ToSecondMonitor</RootNamespace>
<AssemblyName>ToSecondMonitor</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -67,4 +67,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>UserManagement</RootNamespace>
<AssemblyName>UserManagement</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -164,4 +164,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WorkflowConfigurator</RootNamespace>
<AssemblyName>WorkflowConfigurator</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -243,4 +243,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Workplace</RootNamespace>
<AssemblyName>Workplace</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@ -421,43 +421,43 @@
<Content Include="WizardDirTree\1. Vodomer\Suez Australia\DN40 - 232mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN15 - 134mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN15 - 134mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN20 - 165mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN20 - 165mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN25 - 198mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN25 - 198mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN32 - 260mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN32 - 260mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN40 - 300mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\400 MHz\DN40 - 300mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\900 MHz\DN15 - 165mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\900 MHz\DN15 - 165mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\900 MHz\DN20 - 190mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\900 MHz\DN20 - 190mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\900 MHz\DN25 - 260mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\900 MHz\DN25 - 260mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\900 MHz\DN40 - 300mm\weight.txt">
<Content Include="WizardDirTree\1. Vodomer\Integrovaný Flexnet\900 MHz\DN40 - 300mm\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\2. Spätný ventil\SAP_No_1\weight.txt">
<Content Include="WizardDirTree\2. Spätný ventil\SAP_No_1\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\2. Spätný ventil\SAP_No_2\weight.txt">
<Content Include="WizardDirTree\2. Spätný ventil\SAP_No_2\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\2. Spätný ventil\SAP_No_3\weight.txt">
<Content Include="WizardDirTree\2. Spätný ventil\SAP_No_3\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\2. Spätný ventil\Žiadny spätný ventil\weight.txt">
<Content Include="WizardDirTree\2. Spätný ventil\Žiadny spätný ventil\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\3. Tesnenie\SAP_No_1\weight.txt">
@ -469,31 +469,31 @@
<Content Include="WizardDirTree\3. Tesnenie\SAP_No_3\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\3. Tesnenie\Žiadne tesnenie\weight.txt">
<Content Include="WizardDirTree\3. Tesnenie\Žiadne tesnenie\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\5. Návod\SAP_No_1\weight.txt">
<Content Include="WizardDirTree\5. Návod\SAP_No_1\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\5. Návod\SAP_No_2\weight.txt">
<Content Include="WizardDirTree\5. Návod\SAP_No_2\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\5. Návod\SAP_No_3\weight.txt">
<Content Include="WizardDirTree\5. Návod\SAP_No_3\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\5. Návod\Žiadny návod\weight.txt">
<Content Include="WizardDirTree\5. Návod\Žiadny návod\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\4. Kovové premostenie\SAP_No_1\weight.txt">
<Content Include="WizardDirTree\4. Kovové premostenie\SAP_No_1\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\4. Kovové premostenie\SAP_No_2\weight.txt">
<Content Include="WizardDirTree\4. Kovové premostenie\SAP_No_2\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\4. Kovové premostenie\SAP_No_3\weight.txt">
<Content Include="WizardDirTree\4. Kovové premostenie\SAP_No_3\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="WizardDirTree\4. Kovové premostenie\Žiadne premostenie\weight.txt">
<Content Include="WizardDirTree\4. Kovové premostenie\Žiadne premostenie\weight.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
@ -505,4 +505,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

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