From fd9d09cf25bd9848ccd0d4e2828d0648dec7e42f Mon Sep 17 00:00:00 2001 From: Michal Buzik Date: Thu, 22 Oct 2026 07:47:43 +0200 Subject: [PATCH] Add compatibility for legacy Laatzen APIs --- .../API/InterfaceGCIToLaatzen.cs | 61 +++++++++++----- .../API/LegacyLaatzenCompatibility.cs | 40 +++++++++++ .../Build/Apply-LaatzenRuntimeReferences.ps1 | 36 ++++++---- .../Build/Laatzen-legacy-api.patch | 71 +++++++++++++++++++ 4 files changed, 174 insertions(+), 34 deletions(-) create mode 100644 GenesisCordonelInterface/API/LegacyLaatzenCompatibility.cs create mode 100644 GenesisCordonelInterface/RuntimePackage/Build/Laatzen-legacy-api.patch diff --git a/GenesisCordonelInterface/API/InterfaceGCIToLaatzen.cs b/GenesisCordonelInterface/API/InterfaceGCIToLaatzen.cs index ae31bf8e9..06c5778b3 100644 --- a/GenesisCordonelInterface/API/InterfaceGCIToLaatzen.cs +++ b/GenesisCordonelInterface/API/InterfaceGCIToLaatzen.cs @@ -2513,31 +2513,36 @@ namespace GenesisCordonelInterface.API _progressProcess.DebugMessage("SQL Completion export is unavailable for this process type.", control.Slot, "DB"); return; } - var snapshots = completion.GetDatabaseSnapshots(); - foreach (var snapshot in snapshots) + var completedControls = _meterControls.Where(m => m.IsEnabled || m.Failed).ToList(); + foreach (var control in completedControls) { int pcbId; - int.TryParse(snapshot.PcbId, out pcbId); + int.TryParse(control.Meter == null ? null : control.Meter.PcbId, out pcbId); + var calibration = control.Meter == null ? null : control.Meter.calibrationResult; + if (calibration == null) + continue; + // The writer reports invalid identity without sending it to SQL. result.DatabaseRecords.Add(new PreadjustmentCompletionRecord { - Slot = snapshot.Slot, PcbId = pcbId, MeterSize = snapshot.MeterSize, - ZeroOffset1 = snapshot.ZeroOffset1, ZeroOffset2 = snapshot.ZeroOffset2, - ZeroOffset3 = snapshot.ZeroOffset3, - FirstHitUpdatePeriod = snapshot.FirstHitUpdatePeriod, - FirstHitShift = snapshot.FirstHitShift, - FirstHitPercent1 = snapshot.FirstHitPercent1, - FirstHitPercent2 = snapshot.FirstHitPercent2, - FirstHitPercent3 = snapshot.FirstHitPercent3, - ToFTempOffset1 = snapshot.ToFTempOffset1, - ToFTempOffset2 = snapshot.ToFTempOffset2, - ToFTempOffset3 = snapshot.ToFTempOffset3, - Date = snapshot.Date, Successful = snapshot.Successful + Slot = control.Slot, PcbId = pcbId, MeterSize = calibration.MeterSize, + ZeroOffset1 = calibration.ZeroOffset1, ZeroOffset2 = calibration.ZeroOffset2, + ZeroOffset3 = calibration.ZeroOffset3, + FirstHitUpdatePeriod = calibration.FirstHitUpdatePeriod, + FirstHitShift = calibration.FirstHitShift, + FirstHitPercent1 = calibration.FirstHitPercent1, + FirstHitPercent2 = calibration.FirstHitPercent2, + FirstHitPercent3 = calibration.FirstHitPercent3, + ToFTempOffset1 = calibration.ToFTempOffset1, + ToFTempOffset2 = calibration.ToFTempOffset2, + ToFTempOffset3 = calibration.ToFTempOffset3, + Date = calibration.Date == default(DateTimeOffset) ? DateTime.UtcNow : calibration.Date.UtcDateTime, + Successful = calibration.Succesfull }); } - foreach (var control in _meterControls.Where(m => m.IsEnabled || m.Failed)) + foreach (var control in completedControls) { - if (snapshots.Any(s => s.Slot == control.Slot)) continue; + if (result.DatabaseRecords.Any(s => s.Slot == control.Slot)) continue; _progressProcess.DebugMessage("SQL write skipped: Completion produced no verified register readout.", control.Slot, "DB"); result.DatabaseWrites.Add(new CompletionDatabaseWriteResult { @@ -2719,8 +2724,9 @@ namespace GenesisCordonelInterface.API throw new InvalidOperationException("No eligible meters remain; preadjustment process was not executed. Run Initialization and Detect for a new attempt."); foreach (var meterCtrl in _meterControls) meterCtrl.Ok = false; process.StartProcess(pp, _meterControls, _tempMeterControls); - // Do not return when cancellation is requested: wait for every owned task. - process.Completion.GetAwaiter().GetResult(); + // Older delivered Laatzen runtimes do not expose BaseProcess.Completion. + // Their ProcessProgress busy flag has the same lifecycle contract. + WaitForProcessCompletion(process, pp, token); runSource.Token.ThrowIfCancellationRequested(); foreach (var meterCtrl in _meterControls) @@ -2757,6 +2763,23 @@ namespace GenesisCordonelInterface.API runSource.Dispose(); } } + + private static void WaitForProcessCompletion(BaseProcess process, ProcessProgress progress, CancellationToken token) + { + var completionProperty = process.GetType().GetProperty("Completion"); + var completion = completionProperty == null ? null : completionProperty.GetValue(process, null) as Task; + if (completion != null) + { + completion.GetAwaiter().GetResult(); + return; + } + + while (progress.IsBusy) + { + token.ThrowIfCancellationRequested(); + Thread.Sleep(10); + } + } #endregion } } diff --git a/GenesisCordonelInterface/API/LegacyLaatzenCompatibility.cs b/GenesisCordonelInterface/API/LegacyLaatzenCompatibility.cs new file mode 100644 index 000000000..b6fe89bda --- /dev/null +++ b/GenesisCordonelInterface/API/LegacyLaatzenCompatibility.cs @@ -0,0 +1,40 @@ +using System; +using CordonelPreadjustmentUi; +using Xylem.Common.Hardware.Interfaces.Ports.PortCore; + +namespace GenesisCordonelInterface.API +{ + /// + /// Compatibility for the delivered Laatzen runtime predating its dedicated + /// streaming-port hand-off API. Instance methods from a newer runtime take + /// precedence over these extensions automatically. + /// + internal static class LegacyLaatzenCompatibility + { + public static void ConnectStreamingPort(this ZeroFlowGenesisMeter meter, PortConfig requestedPort) + { + if (meter == null) throw new ArgumentNullException(nameof(meter)); + if (meter.StreamingPort == null) + throw new InvalidOperationException( + "The installed Laatzen runtime has no configured streaming port. Configure it before initializing the slot."); + + var configuredPort = meter.StreamingPort.GetPortName(); + if (!string.Equals(configuredPort, requestedPort.PortName, StringComparison.OrdinalIgnoreCase)) + throw new NotSupportedException( + "The installed Laatzen runtime cannot replace a streaming port at runtime. " + + "Initialize the slot with the requested streaming port or install the updated Laatzen runtime."); + + if (!meter.CheckStreamingPort()) + throw new InvalidOperationException("Unable to open configured streaming port " + configuredPort + "."); + } + + public static void DisconnectStreamingPort(this ZeroFlowGenesisMeter meter) + { + if (meter == null) return; + + // The legacy API has no streaming-only disconnect. Keeping its + // configured port open avoids disposing the request-session graph. + meter.StopRecordData(); + } + } +} diff --git a/GenesisCordonelInterface/RuntimePackage/Build/Apply-LaatzenRuntimeReferences.ps1 b/GenesisCordonelInterface/RuntimePackage/Build/Apply-LaatzenRuntimeReferences.ps1 index f7250ff44..edf0b79f8 100644 --- a/GenesisCordonelInterface/RuntimePackage/Build/Apply-LaatzenRuntimeReferences.ps1 +++ b/GenesisCordonelInterface/RuntimePackage/Build/Apply-LaatzenRuntimeReferences.ps1 @@ -5,30 +5,36 @@ Set-StrictMode -Version Latest try { $repositoryRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..\..')) - $patchPath = Join-Path $PSScriptRoot 'GenesisToolBox-references.patch' + $patchPaths = @( + (Join-Path $PSScriptRoot 'GenesisToolBox-references.patch'), + (Join-Path $PSScriptRoot 'Laatzen-legacy-api.patch') + ) $externalRoot = Join-Path $repositoryRoot 'ExternalProjects\Laatzen' - if (-not (Test-Path -LiteralPath $patchPath -PathType Leaf)) { - throw "Required GenesisToolBox reference patch is missing: $patchPath" + foreach ($patchPath in $patchPaths) { + if (-not (Test-Path -LiteralPath $patchPath -PathType Leaf)) { + throw "Required Laatzen patch is missing: $patchPath" + } } if (-not (Test-Path -LiteralPath $externalRoot -PathType Container)) { throw "Local Laatzen source is unavailable: $externalRoot" } - # The vendor project has hard-coded Debug DLL references in addition to its - # ProjectReferences. Those copies can combine incompatible runtime builds. - # Applying this tracked, idempotent patch makes the local graph authoritative. - & git -C $repositoryRoot apply --directory=ExternalProjects/Laatzen --reverse --check $patchPath 2>$null - if ($LASTEXITCODE -eq 0) { - Write-Host 'Laatzen GenesisToolBox references are already prepared.' - exit 0 - } + foreach ($patchPath in $patchPaths) { + # The vendor project has hard-coded Debug DLL references and older API + # gaps. Applying tracked patches makes the local graph authoritative. + & git -C $repositoryRoot apply --directory=ExternalProjects/Laatzen --reverse --check $patchPath 2>$null + if ($LASTEXITCODE -eq 0) { + Write-Host (Split-Path -Leaf $patchPath) 'is already prepared.' + continue + } - & git -C $repositoryRoot apply --directory=ExternalProjects/Laatzen $patchPath - if ($LASTEXITCODE -ne 0) { - throw 'Cannot apply GenesisToolBox reference patch. Restore the local Laatzen source or supply a complete delivered runtime package.' + & git -C $repositoryRoot apply --directory=ExternalProjects/Laatzen $patchPath + if ($LASTEXITCODE -ne 0) { + throw "Cannot apply Laatzen patch '$patchPath'. Restore a compatible local Laatzen source or supply a complete delivered runtime package." + } + Write-Host 'Prepared' (Split-Path -Leaf $patchPath) } - Write-Host 'Prepared Laatzen GenesisToolBox project references.' } catch { Write-Host ('{0}(1,1): error GCI002: {1}' -f $PSCommandPath, $_.Exception.Message) diff --git a/GenesisCordonelInterface/RuntimePackage/Build/Laatzen-legacy-api.patch b/GenesisCordonelInterface/RuntimePackage/Build/Laatzen-legacy-api.patch new file mode 100644 index 000000000..8f3cc77d7 --- /dev/null +++ b/GenesisCordonelInterface/RuntimePackage/Build/Laatzen-legacy-api.patch @@ -0,0 +1,71 @@ +--- a/Genesis/Common/Hardware/WaterMeter/Genesis/GenesisCore/GenesisMeter.cs ++++ b/Genesis/Common/Hardware/WaterMeter/Genesis/GenesisCore/GenesisMeter.cs +@@ -1273,4 +1273,49 @@ + } + ++ /// ++ /// Replaces only the streaming connection while preserving the active ++ /// request/session connection. ++ /// ++ public void ConnectStreamingPort(PortConfig streamingPort) ++ { ++ if (string.IsNullOrWhiteSpace(streamingPort.PortName) || ++ string.Equals(streamingPort.PortName, BaseSerialPort.PortNotAssigned, StringComparison.OrdinalIgnoreCase)) ++ throw new ArgumentException("A valid streaming port is required.", nameof(streamingPort)); ++ ++ DisconnectStreamingPort(); ++ streamingPortConfig = streamingPort; ++ ++ var ident = $"Slot:{Slot}, Port:{streamingPort.PortName}, Protocol:LED"; ++ var transmit = new LedTransmitProtocol(streamingPort.PortName); ++ StreamingPort = new LedSerialPort(ident, streamingPort.GetSerialPort(), transmit.GetTransmitPortSettings()); ++ StreamingProtocol = new StreamingProtocol(ident, true); ++ ++ if (!LinkPortToProtocol(StreamingPort, StreamingProtocol, ++ ref _streamingRawReceivedHandler, ref _streamingReadyToSendHandler)) ++ { ++ DisconnectStreamingPort(); ++ throw new InvalidOperationException("Unable to link the streaming port to its protocol."); ++ } ++ ++ StreamingProtocol.OnRecordIsDecoded -= StreamingProtocol_ApplyDecodedRecord; ++ StreamingProtocol.OnRecordIsDecoded += StreamingProtocol_ApplyDecodedRecord; ++ StreamingPort.Open(); ++ } ++ ++ /// Releases only streaming resources; the request session remains usable. ++ public void DisconnectStreamingPort() ++ { ++ if (StreamingProtocol != null) ++ StreamingProtocol.OnRecordIsDecoded -= StreamingProtocol_ApplyDecodedRecord; ++ ++ UnlinkPortFromProtocol(StreamingPort, StreamingProtocol, ++ ref _streamingRawReceivedHandler, ref _streamingReadyToSendHandler); ++ StreamingPort?.Dispose(); ++ StreamingProtocol?.Dispose(); ++ StreamingPort = null; ++ StreamingProtocol = null; ++ streamingPortConfig = null; ++ } ++ + /// + /// +--- a/Genesis/Common/CordonelPreadjustmentUi/Processes/BaseProcess.cs ++++ b/Genesis/Common/CordonelPreadjustmentUi/Processes/BaseProcess.cs +@@ -15,6 +15,8 @@ + public abstract class BaseProcess : IProcess + { + public ProcessProgress CurrentProcessProgress; ++ /// Completes when all tasks owned by this process have finished. ++ public Task Completion { get; private set; } = Task.CompletedTask; + internal List MeterStateCtls = new List(); + internal List TempMeterStateCtls = new List(); + public readonly string ProcessName; +@@ -103,6 +105,7 @@ + + + }); ++ Completion = completTasks; + completTasks.Start(); + +