<Feat>: Add Completion and Q3 calibration database writes through GCI, increase revision to 3.9.3146.109
Cause: - Preadjustment Completion and TBF Q3 calibration results required configurable database persistence. - Both write operations required diagnostics and simulation support. Solution: 1. Added independent database writer configurations - Added PreadjustmentCompletionWriter and Q3CalibrationWriter to gci_config. - Support SQL commands, stored procedures and parameter mappings. - Added SQL table creation and verification scripts. 2. Added Preadjustment Completion storage - Store PCB ID, meter size, amplitude settings, temperature offsets, zero-flow offsets, timestamp and overall result. - Use captured Completion readout values. - Preserve the original HTTP reporting. - Report SQL connection and write status in the corresponding slot diagnostics. 3. Added Q3 calibration storage - Forward TBF results through GCI Bridge to the GCI database API. - Store signed deviations and written calibration factors for all three paths. - Write to SQL after successful calibration register writes and StoreCalibration. - Include PCB ID and UTC timestamp. 4. Added simulation support - Generate sample Completion and Q3 records for simulated slots. - Perform real SQL writes when the corresponding writer is enabled. - Log connection progress, write outcomes and generated record IDs. 5. Separated calibration and database outcomes - Preserve meter operation results when database storage fails. - Expose database write status independently. 6. Increased revision - Updated revision from 3.9.3146.108 to 3.9.3146.109. Validation: - Confirmed successful SQL storage for simulated Completion. - Confirmed successful Q3 calibration result storage. ToDo: - Use the GCI Q3 storage API as the foundation for future migration of Q3 calibration from the direct TBF communication branch to GCI.
This commit is contained in:
@@ -2466,7 +2466,7 @@ namespace GenesisCordonelInterface.API
|
||||
bool success = ExecuteProcess(process, _progressProcess, token);
|
||||
|
||||
var result =
|
||||
new PreAdjustmentProcessResult
|
||||
new CompletionProcessResult
|
||||
{
|
||||
Success = success,
|
||||
Slot = slot,
|
||||
@@ -2476,6 +2476,7 @@ namespace GenesisCordonelInterface.API
|
||||
: process.FailedMessage
|
||||
};
|
||||
|
||||
CaptureCompletionDatabaseRecords(process, result);
|
||||
LogInfo(operation, result.ToString());
|
||||
|
||||
return result;
|
||||
@@ -2495,6 +2496,54 @@ namespace GenesisCordonelInterface.API
|
||||
}
|
||||
}
|
||||
|
||||
private void CaptureCompletionDatabaseRecords(BaseProcess process, CompletionProcessResult result)
|
||||
{
|
||||
var completion = process as CompletionProcess;
|
||||
if (completion == null)
|
||||
{
|
||||
// Single-path Completion has a different readout contract.
|
||||
foreach (var control in _meterControls.Where(m => m.IsEnabled || m.Failed))
|
||||
_progressProcess.DebugMessage("SQL Completion export is unavailable for this process type.", control.Slot, "DB");
|
||||
return;
|
||||
}
|
||||
var snapshots = completion.GetDatabaseSnapshots();
|
||||
foreach (var snapshot in snapshots)
|
||||
{
|
||||
int pcbId;
|
||||
int.TryParse(snapshot.PcbId, out pcbId);
|
||||
// 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
|
||||
});
|
||||
}
|
||||
foreach (var control in _meterControls.Where(m => m.IsEnabled || m.Failed))
|
||||
{
|
||||
if (snapshots.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
|
||||
{
|
||||
Slot = control.Slot,
|
||||
Result = new CalibrationWriteResult
|
||||
{
|
||||
Status = CalibrationWriteStatus.Failed,
|
||||
ErrorMessage = "Completion produced no verified register readout."
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates completion process instance based on current configuration.
|
||||
/// </summary>
|
||||
|
||||
@@ -42,6 +42,82 @@ namespace GenesisCordonelInterface.API
|
||||
public event Action<List<MeterBatchDebugStatus>> MeterBatchStatusChanged;
|
||||
private readonly IMeterLoginPasswordReader loginPasswordsReader;
|
||||
private readonly IPreAdjustmentCalibrationParamsReader calibrationParamsReader;
|
||||
private readonly Core.DataStorage.Writing.CalibrationResultWriter calibrationResultWriter =
|
||||
new Core.DataStorage.Writing.CalibrationResultWriter(null);
|
||||
|
||||
/// <summary>Stores one detached completion record without accessing meter ports.</summary>
|
||||
public Task<CalibrationWriteResult> StorePreadjustmentCompletionResultAsync(
|
||||
PreadjustmentCompletionRecord record, CancellationToken token = default(CancellationToken))
|
||||
{
|
||||
if (record == null) throw new ArgumentNullException(nameof(record));
|
||||
// Capture the progress instance and slot for this write, even if a new
|
||||
// batch is initialized while the database operation is still finishing.
|
||||
var progress = _innerMeterAPI?._progressProcess;
|
||||
int? slot = record.Slot;
|
||||
Action<string> diagnostic = null;
|
||||
if (progress != null && slot.HasValue && slot.Value > 0)
|
||||
diagnostic = message => progress.DebugMessage(message, slot.Value, "DB");
|
||||
return calibrationResultWriter.StorePreadjustmentCompletionAsync(record, token, diagnostic);
|
||||
}
|
||||
|
||||
/// <summary>Creates a synthetic Completion record and exercises the real configured SQL writer.</summary>
|
||||
public async Task<CompletionProcessResult> StoreSimulatedCompletionResultAsync(
|
||||
int slot, int pcbId, bool phaseSuccess, string phaseError,
|
||||
CancellationToken token, Action<string> diagnostic)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (slot <= 0) throw new ArgumentOutOfRangeException(nameof(slot));
|
||||
// Synthetic fixture values belong to GCI, not to the hardware Completion process.
|
||||
var record = new PreadjustmentCompletionRecord
|
||||
{
|
||||
Slot = slot, PcbId = pcbId, MeterSize = 2,
|
||||
ZeroOffset1 = -20, ZeroOffset2 = -30, ZeroOffset3 = -67,
|
||||
FirstHitUpdatePeriod = 10, FirstHitShift = 4,
|
||||
FirstHitPercent1 = 17, FirstHitPercent2 = 13, FirstHitPercent3 = 17,
|
||||
ToFTempOffset1 = 22260, ToFTempOffset2 = -115410, ToFTempOffset3 = 14992,
|
||||
Date = DateTime.UtcNow, Successful = phaseSuccess
|
||||
};
|
||||
// Optional diagnostic subscribers must never change the storage outcome.
|
||||
try { diagnostic?.Invoke("Simulated calibration data; actual SQL write requested. Fixture MeterSize=2."); }
|
||||
catch (Exception) { }
|
||||
var write = await calibrationResultWriter.StorePreadjustmentCompletionAsync(
|
||||
record, token, diagnostic).ConfigureAwait(false);
|
||||
var result = new CompletionProcessResult
|
||||
{
|
||||
Slot = slot, Success = phaseSuccess, ProcessName = "PreAdjustment_Completion",
|
||||
ErrorMessage = phaseError
|
||||
};
|
||||
result.DatabaseRecords.Add(record);
|
||||
result.DatabaseWrites.Add(new CompletionDatabaseWriteResult { Slot = slot, Result = write });
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Stores Q3 values supplied by TBF; does not perform Q3 calibration.</summary>
|
||||
public Task<CalibrationWriteResult> StoreQ3CalibrationResultAsync(
|
||||
Q3CalibrationRecord record, CancellationToken token = default(CancellationToken))
|
||||
{
|
||||
return calibrationResultWriter.StoreQ3CalibrationAsync(record, token);
|
||||
}
|
||||
|
||||
public Task<CalibrationWriteResult> StoreQ3CalibrationResultAsync(
|
||||
Q3CalibrationRecord record, CancellationToken token, Action<string> diagnostic)
|
||||
{
|
||||
return calibrationResultWriter.StoreQ3CalibrationAsync(record, token, diagnostic);
|
||||
}
|
||||
|
||||
public Task<CalibrationWriteResult> StoreSimulatedQ3CalibrationResultAsync(
|
||||
int pcbId, CancellationToken token, Action<string> diagnostic)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
try { diagnostic?.Invoke("Simulated Q3 fixture values; actual SQL write requested."); }
|
||||
catch (Exception) { }
|
||||
return calibrationResultWriter.StoreQ3CalibrationAsync(new Q3CalibrationRecord
|
||||
{
|
||||
PcbId = pcbId, P1Offset = -0.3, P1Cal = 15260,
|
||||
P2Offset = -0.3, P2Cal = 15451, P3Offset = -0.3, P3Cal = 15204,
|
||||
Date = DateTime.UtcNow
|
||||
}, token, diagnostic);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the public GCI facade.
|
||||
@@ -58,10 +134,20 @@ namespace GenesisCordonelInterface.API
|
||||
InterfaceGCIToLaatzen innerMeterApi,
|
||||
IMeterLoginPasswordReader passwordReader,
|
||||
IPreAdjustmentCalibrationParamsReader calibrationReader)
|
||||
: this(innerMeterApi, passwordReader, calibrationReader, null)
|
||||
{
|
||||
}
|
||||
|
||||
public InterfaceOutsideToGCI(
|
||||
InterfaceGCIToLaatzen innerMeterApi,
|
||||
IMeterLoginPasswordReader passwordReader,
|
||||
IPreAdjustmentCalibrationParamsReader calibrationReader,
|
||||
GciDataStorageConfig storageConfig)
|
||||
{
|
||||
_innerMeterAPI = innerMeterApi?? throw new ArgumentNullException(nameof(innerMeterApi));
|
||||
loginPasswordsReader = passwordReader ?? throw new ArgumentNullException(nameof(passwordReader));
|
||||
calibrationParamsReader = calibrationReader ?? throw new ArgumentNullException(nameof(calibrationReader));
|
||||
calibrationResultWriter = new Core.DataStorage.Writing.CalibrationResultWriter(storageConfig);
|
||||
|
||||
//init handlers
|
||||
//_innerMeterAPI._progressProcess.OnRequestedCalibrationParamsFromDb += RequestedCalibrationParamsFromDb;
|
||||
|
||||
@@ -49,6 +49,87 @@ namespace GenesisCordonelInterface.API
|
||||
/// </summary>
|
||||
public class PublicModels
|
||||
{
|
||||
/// <summary>Persisted values for one meter and one preadjustment attempt.</summary>
|
||||
public sealed class PreadjustmentCompletionRecord
|
||||
{
|
||||
// Diagnostic routing only. Not a database column or SQL parameter.
|
||||
public int? Slot { get; set; }
|
||||
public int PcbId { get; set; }
|
||||
public int? MeterSize { get; set; }
|
||||
public int? ZeroOffset1 { get; set; }
|
||||
public int? ZeroOffset2 { get; set; }
|
||||
public int? ZeroOffset3 { get; set; }
|
||||
public int? FirstHitUpdatePeriod { get; set; }
|
||||
public int? FirstHitShift { get; set; }
|
||||
public int? FirstHitPercent1 { get; set; }
|
||||
public int? FirstHitPercent2 { get; set; }
|
||||
public int? FirstHitPercent3 { get; set; }
|
||||
public int? ToFTempOffset1 { get; set; }
|
||||
public int? ToFTempOffset2 { get; set; }
|
||||
public int? ToFTempOffset3 { get; set; }
|
||||
// Timestamp of the attempt, not the time of a possible later write retry.
|
||||
public DateTime Date { get; set; }
|
||||
public bool Successful { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Q3 values calculated and confirmed by the caller; no port access.</summary>
|
||||
public sealed class Q3CalibrationRecord
|
||||
{
|
||||
public int PcbId { get; set; }
|
||||
// Preserve the existing TBF meaning/unit of each offset (do not rescale here).
|
||||
public double? P1Offset { get; set; }
|
||||
public int? P1Cal { get; set; }
|
||||
public double? P2Offset { get; set; }
|
||||
public int? P2Cal { get; set; }
|
||||
public double? P3Offset { get; set; }
|
||||
public int? P3Cal { get; set; }
|
||||
public DateTime Date { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Completion outcome plus detached SQL inputs and separate write outcomes.</summary>
|
||||
public sealed class CompletionProcessResult : PreAdjustmentProcessResult
|
||||
{
|
||||
public List<PreadjustmentCompletionRecord> DatabaseRecords { get; set; } =
|
||||
new List<PreadjustmentCompletionRecord>();
|
||||
public List<CompletionDatabaseWriteResult> DatabaseWrites { get; set; } =
|
||||
new List<CompletionDatabaseWriteResult>();
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return base.ToString() + ", SQL=[" + string.Join("; ",
|
||||
DatabaseWrites.Select(w => "Slot=" + w.Slot + ", " + w.Result.Status)) + "]";
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CompletionDatabaseWriteResult
|
||||
{
|
||||
public int Slot { get; set; }
|
||||
public CalibrationWriteResult Result { get; set; }
|
||||
}
|
||||
|
||||
public enum CalibrationWriteStatus
|
||||
{
|
||||
Failed = 0, Stored = 1, Disabled = 2, Simulated = 3,
|
||||
// The connection failed during commit; verify the DB before retrying.
|
||||
OutcomeUnknown = 4
|
||||
}
|
||||
|
||||
/// <summary>Database outcome, independent of the physical calibration outcome.</summary>
|
||||
public sealed class CalibrationWriteResult
|
||||
{
|
||||
public CalibrationWriteStatus Status { get; set; }
|
||||
public bool Success { get { return Status == CalibrationWriteStatus.Stored; } }
|
||||
public int PcbId { get; set; }
|
||||
public long? RecordId { get; set; }
|
||||
public string ErrorMessage { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return string.Format("Status={0}, PcbId={1}, RecordId={2}, Error={3}",
|
||||
Status, PcbId, RecordId, ErrorMessage ?? "None");
|
||||
}
|
||||
}
|
||||
|
||||
public static bool HideSensitiveValues { get; set; } = true;
|
||||
|
||||
private static string FormatPassword(string password)
|
||||
|
||||
@@ -31,6 +31,48 @@
|
||||
"Type": "LocalDatabase",
|
||||
"DataSource": "Server=(localdb)\\SensusLocalDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
|
||||
"QueryTemplate": "SELECT [ParameterName], [ParameterValue] FROM [dbo].[PreAdjustmentCalibrationParams] WHERE [MeterSize] = QUERYPARAM"
|
||||
},
|
||||
|
||||
"PreadjustmentCompletionWriter": {
|
||||
"Enabled": true,
|
||||
"DataSource": "Server=(localdb)\\MojaDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
|
||||
"CommandText": "INSERT INTO [dbo].[PreadjustmentCompletion] ([PcbId], [ZeroOffset1], [ZeroOffset2], [ZeroOffset3], [FirstHitUpdatePeriod], [FirstHitShift], [FirstHitPercent1], [FirstHitPercent2], [FirstHitPercent3], [ToFTempOffset1], [ToFTempOffset2], [ToFTempOffset3], [MeterSize], [Date], [Successful]) OUTPUT INSERTED.[Id] VALUES (@PcbId, @ZeroOffset1, @ZeroOffset2, @ZeroOffset3, @FirstHitUpdatePeriod, @FirstHitShift, @FirstHitPercent1, @FirstHitPercent2, @FirstHitPercent3, @ToFTempOffset1, @ToFTempOffset2, @ToFTempOffset3, @MeterSize, @Date, @Successful);",
|
||||
"UseStoredProcedure": false,
|
||||
"CommandTimeoutSeconds": 30,
|
||||
"ParameterMappings": {
|
||||
"PcbId": "@PcbId",
|
||||
"ZeroOffset1": "@ZeroOffset1",
|
||||
"ZeroOffset2": "@ZeroOffset2",
|
||||
"ZeroOffset3": "@ZeroOffset3",
|
||||
"FirstHitUpdatePeriod": "@FirstHitUpdatePeriod",
|
||||
"FirstHitShift": "@FirstHitShift",
|
||||
"FirstHitPercent1": "@FirstHitPercent1",
|
||||
"FirstHitPercent2": "@FirstHitPercent2",
|
||||
"FirstHitPercent3": "@FirstHitPercent3",
|
||||
"ToFTempOffset1": "@ToFTempOffset1",
|
||||
"ToFTempOffset2": "@ToFTempOffset2",
|
||||
"ToFTempOffset3": "@ToFTempOffset3",
|
||||
"MeterSize": "@MeterSize",
|
||||
"Date": "@Date",
|
||||
"Successful": "@Successful"
|
||||
}
|
||||
},
|
||||
"Q3CalibrationWriter": {
|
||||
"Enabled": true,
|
||||
"DataSource": "Server=(localdb)\\MojaDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
|
||||
"CommandText": "INSERT INTO [dbo].[Q3Calibration] ([PcbId], [P1Offset], [P1Cal], [P2Offset], [P2Cal], [P3Offset], [P3Cal], [Date]) OUTPUT INSERTED.[Id] VALUES (@PcbId, @P1Offset, @P1Cal, @P2Offset, @P2Cal, @P3Offset, @P3Cal, @Date);",
|
||||
"UseStoredProcedure": false,
|
||||
"CommandTimeoutSeconds": 30,
|
||||
"ParameterMappings": {
|
||||
"PcbId": "@PcbId",
|
||||
"P1Offset": "@P1Offset",
|
||||
"P1Cal": "@P1Cal",
|
||||
"P2Offset": "@P2Offset",
|
||||
"P2Cal": "@P2Cal",
|
||||
"P3Offset": "@P3Offset",
|
||||
"P3Cal": "@P3Cal",
|
||||
"Date": "@Date"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ namespace GenesisCordonelInterface.Core.DataStorage.Config
|
||||
/// </summary>
|
||||
public class GciDataStorageConfig
|
||||
{
|
||||
public GciDatabaseWriterConfig PreadjustmentCompletionWriter { get; set; }
|
||||
public GciDatabaseWriterConfig Q3CalibrationWriter { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Configuration for meter login password lookup.
|
||||
/// </summary>
|
||||
@@ -27,4 +30,4 @@ namespace GenesisCordonelInterface.Core.DataStorage.Config
|
||||
/// </summary>
|
||||
public DataStorageConfig PreAdjustmentCalibrationParams { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GenesisCordonelInterface.Core.DataStorage.Config
|
||||
{
|
||||
/// <summary>SQL Server destination for one logical result type.</summary>
|
||||
public sealed class GciDatabaseWriterConfig
|
||||
{
|
||||
// Missing sections in existing configuration files leave writes disabled.
|
||||
public bool Enabled { get; set; }
|
||||
public string DataSource { get; set; }
|
||||
public string CommandText { get; set; }
|
||||
public bool UseStoredProcedure { get; set; }
|
||||
public int CommandTimeoutSeconds { get; set; } = 30;
|
||||
|
||||
/// <summary>
|
||||
/// Optional complete mapping: DTO property name -> SQL parameter name.
|
||||
/// Null/empty uses the documented default parameter names.
|
||||
/// Commands must return the persisted positive identity as their first scalar.
|
||||
/// </summary>
|
||||
public Dictionary<string, string> ParameterMappings { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GenesisCordonelInterface.Core.DataStorage.Config;
|
||||
using static GenesisCordonelInterface.API.PublicModels;
|
||||
|
||||
namespace GenesisCordonelInterface.Core.DataStorage.Writing
|
||||
{
|
||||
/// <summary>
|
||||
/// Stores detached result records. Each call owns its connection and transaction;
|
||||
/// slot workers, request sessions and streaming ownership are never involved.
|
||||
/// </summary>
|
||||
public sealed class CalibrationResultWriter
|
||||
{
|
||||
private readonly GciDatabaseWriterConfig completion;
|
||||
private readonly GciDatabaseWriterConfig q3;
|
||||
|
||||
public CalibrationResultWriter(GciDataStorageConfig config)
|
||||
{
|
||||
completion = Snapshot(config?.PreadjustmentCompletionWriter);
|
||||
q3 = Snapshot(config?.Q3CalibrationWriter);
|
||||
}
|
||||
|
||||
private static GciDatabaseWriterConfig Snapshot(GciDatabaseWriterConfig config)
|
||||
{
|
||||
if (config == null) return null;
|
||||
return new GciDatabaseWriterConfig
|
||||
{
|
||||
Enabled = config.Enabled, DataSource = config.DataSource,
|
||||
CommandText = config.CommandText, UseStoredProcedure = config.UseStoredProcedure,
|
||||
CommandTimeoutSeconds = config.CommandTimeoutSeconds,
|
||||
ParameterMappings = config.ParameterMappings == null ? null :
|
||||
new Dictionary<string, string>(config.ParameterMappings, StringComparer.Ordinal)
|
||||
};
|
||||
}
|
||||
|
||||
public Task<CalibrationWriteResult> StorePreadjustmentCompletionAsync(
|
||||
PreadjustmentCompletionRecord record, CancellationToken token)
|
||||
{
|
||||
return StorePreadjustmentCompletionAsync(record, token, null);
|
||||
}
|
||||
|
||||
public Task<CalibrationWriteResult> StorePreadjustmentCompletionAsync(
|
||||
PreadjustmentCompletionRecord record, CancellationToken token, Action<string> diagnostic)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (record == null) throw new ArgumentNullException(nameof(record));
|
||||
// Materialize all values before the first await; no mutable record is retained.
|
||||
var values = new Dictionary<string, object>
|
||||
{
|
||||
{ "PcbId", record.PcbId }, { "MeterSize", record.MeterSize },
|
||||
{ "ZeroOffset1", record.ZeroOffset1 }, { "ZeroOffset2", record.ZeroOffset2 },
|
||||
{ "ZeroOffset3", record.ZeroOffset3 },
|
||||
{ "FirstHitUpdatePeriod", record.FirstHitUpdatePeriod },
|
||||
{ "FirstHitShift", record.FirstHitShift },
|
||||
{ "FirstHitPercent1", record.FirstHitPercent1 },
|
||||
{ "FirstHitPercent2", record.FirstHitPercent2 },
|
||||
{ "FirstHitPercent3", record.FirstHitPercent3 },
|
||||
{ "ToFTempOffset1", record.ToFTempOffset1 },
|
||||
{ "ToFTempOffset2", record.ToFTempOffset2 },
|
||||
{ "ToFTempOffset3", record.ToFTempOffset3 },
|
||||
{ "Date", record.Date }, { "Successful", record.Successful }
|
||||
};
|
||||
string error = !record.MeterSize.HasValue || record.MeterSize.Value < 0
|
||||
? "MeterSize is required and must not be negative." : null;
|
||||
if (record.Successful && values.Any(v => v.Value == null))
|
||||
error = "Successful preadjustment requires all calibration values.";
|
||||
return WriteAsync(completion, record.PcbId, values, error, token, diagnostic);
|
||||
}
|
||||
|
||||
public Task<CalibrationWriteResult> StoreQ3CalibrationAsync(
|
||||
Q3CalibrationRecord record, CancellationToken token)
|
||||
{
|
||||
return StoreQ3CalibrationAsync(record, token, null);
|
||||
}
|
||||
|
||||
public Task<CalibrationWriteResult> StoreQ3CalibrationAsync(
|
||||
Q3CalibrationRecord record, CancellationToken token, Action<string> diagnostic)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (record == null) throw new ArgumentNullException(nameof(record));
|
||||
var values = new Dictionary<string, object>
|
||||
{
|
||||
{ "PcbId", record.PcbId }, { "P1Offset", record.P1Offset },
|
||||
{ "P1Cal", record.P1Cal }, { "P2Offset", record.P2Offset },
|
||||
{ "P2Cal", record.P2Cal }, { "P3Offset", record.P3Offset },
|
||||
{ "P3Cal", record.P3Cal }, { "Date", record.Date }
|
||||
};
|
||||
string error = values.Any(v => v.Value == null)
|
||||
? "Q3 requires the offset and confirmed calibration factor for all three paths."
|
||||
: null;
|
||||
if (values.Values.OfType<double>().Any(v => double.IsNaN(v) || double.IsInfinity(v)))
|
||||
error = "Q3 offsets must be finite numbers.";
|
||||
return WriteAsync(q3, record.PcbId, values, error, token, diagnostic);
|
||||
}
|
||||
|
||||
private static async Task<CalibrationWriteResult> WriteAsync(
|
||||
GciDatabaseWriterConfig config, int pcbId, IDictionary<string, object> values,
|
||||
string validationError, CancellationToken token, Action<string> diagnostic = null)
|
||||
{
|
||||
string operation = values.ContainsKey("Successful") ? "Completion" : "Q3 calibration";
|
||||
Report(diagnostic, operation + " database write: START.");
|
||||
var result = new CalibrationWriteResult { PcbId = pcbId };
|
||||
if (config == null || !config.Enabled)
|
||||
{
|
||||
result.Status = CalibrationWriteStatus.Disabled;
|
||||
result.ErrorMessage = "Database writer is not enabled.";
|
||||
Report(diagnostic, operation + " database write skipped: writer is disabled or not configured.");
|
||||
return result;
|
||||
}
|
||||
bool commitStarted = false;
|
||||
bool connectionOpened = false;
|
||||
string stage = "validation";
|
||||
try
|
||||
{
|
||||
if (validationError != null) throw new ArgumentException(validationError);
|
||||
if (pcbId <= 0) throw new ArgumentException("PcbId must be positive.");
|
||||
if ((DateTime)values["Date"] == default(DateTime))
|
||||
throw new ArgumentException("The calibration timestamp is required.");
|
||||
if (string.IsNullOrWhiteSpace(config.DataSource) || string.IsNullOrWhiteSpace(config.CommandText))
|
||||
throw new ArgumentException("Writer DataSource and CommandText are required.");
|
||||
if (config.CommandTimeoutSeconds < 1)
|
||||
throw new ArgumentException("CommandTimeoutSeconds must be positive.");
|
||||
|
||||
using (var connection = new SqlConnection(config.DataSource))
|
||||
using (var command = new SqlCommand(config.CommandText, connection))
|
||||
{
|
||||
command.CommandType = config.UseStoredProcedure ? CommandType.StoredProcedure : CommandType.Text;
|
||||
command.CommandTimeout = config.CommandTimeoutSeconds;
|
||||
AddParameters(command, config, values);
|
||||
stage = "server connection";
|
||||
// Only log the destination, never credentials or the full connection string.
|
||||
var destination = new SqlConnectionStringBuilder(config.DataSource);
|
||||
Report(diagnostic, "Connecting to server '" + destination.DataSource +
|
||||
"', database '" + destination.InitialCatalog + "'.");
|
||||
await connection.OpenAsync(token).ConfigureAwait(false);
|
||||
connectionOpened = true;
|
||||
Report(diagnostic, "Connection opened.");
|
||||
token.ThrowIfCancellationRequested();
|
||||
stage = "transaction start";
|
||||
using (var transaction = connection.BeginTransaction())
|
||||
{
|
||||
command.Transaction = transaction;
|
||||
stage = "data write";
|
||||
Report(diagnostic, "Writing " + operation + " data (" +
|
||||
(config.UseStoredProcedure ? "stored procedure" : "SQL command") + ").");
|
||||
// The command/procedure must return the stored Id (OUTPUT INSERTED.Id).
|
||||
object scalar = await command.ExecuteScalarAsync(token).ConfigureAwait(false);
|
||||
stage = "returned record Id validation";
|
||||
if (scalar == null || scalar == DBNull.Value)
|
||||
throw new InvalidOperationException("Writer did not return a record Id; transaction rolled back.");
|
||||
decimal id = Convert.ToDecimal(scalar, CultureInfo.InvariantCulture);
|
||||
if (id <= 0 || id != decimal.Truncate(id) || id > long.MaxValue)
|
||||
throw new InvalidOperationException("Writer returned an invalid record Id; transaction rolled back.");
|
||||
token.ThrowIfCancellationRequested();
|
||||
Report(diagnostic, "Write command completed; confirming transaction.");
|
||||
stage = "transaction commit";
|
||||
// Once commit starts, cancellation must not hide a committed record.
|
||||
commitStarted = true;
|
||||
transaction.Commit();
|
||||
result.RecordId = (long)id;
|
||||
result.Status = CalibrationWriteStatus.Stored;
|
||||
Report(diagnostic, "Transaction committed; RecordId=" + result.RecordId + ".");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (!commitStarted)
|
||||
{
|
||||
Report(diagnostic, operation + " database write cancelled during " + stage + ".");
|
||||
// Disposing the uncommitted transaction rolls back its write.
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result.Status = commitStarted ? CalibrationWriteStatus.OutcomeUnknown : CalibrationWriteStatus.Failed;
|
||||
result.ErrorMessage = ex.Message;
|
||||
// Server messages can contain record values or login names. Keep
|
||||
// the slot log free of these; retain the original error in the result.
|
||||
var sqlError = ex as SqlException;
|
||||
string detail = sqlError == null ? ex.GetType().Name :
|
||||
"SQL error " + sqlError.Number + ", state " + sqlError.State;
|
||||
Report(diagnostic, operation + " database write failed during " + stage + " (" + detail + ").");
|
||||
if (commitStarted)
|
||||
Report(diagnostic, "Commit outcome is unknown. Verify the database before retrying.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The SQL using scopes have already disposed their resources here.
|
||||
if (connectionOpened) Report(diagnostic, "SQL connection released.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void Report(Action<string> diagnostic, string message)
|
||||
{
|
||||
if (diagnostic == null) return;
|
||||
try { diagnostic(message); }
|
||||
catch (Exception)
|
||||
{
|
||||
// A closed/failing diagnostic subscriber must not change the DB outcome.
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddParameters(SqlCommand command, GciDatabaseWriterConfig config,
|
||||
IDictionary<string, object> values)
|
||||
{
|
||||
var mappings = config.ParameterMappings;
|
||||
bool custom = mappings != null && mappings.Count > 0;
|
||||
if (custom && (mappings.Count != values.Count || mappings.Keys.Any(k => !values.ContainsKey(k))))
|
||||
throw new ArgumentException("ParameterMappings must map every documented record field exactly once.");
|
||||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var value in values)
|
||||
{
|
||||
string name = custom ? mappings[value.Key] : "@" + value.Key;
|
||||
if (string.IsNullOrWhiteSpace(name) || name.Length < 2 || name.Length > 128 ||
|
||||
name[0] != '@' || !(char.IsLetter(name[1]) || name[1] == '_') ||
|
||||
name.Skip(2).Any(c => !char.IsLetterOrDigit(c) && c != '_') || !names.Add(name))
|
||||
throw new ArgumentException("Invalid or duplicate SQL parameter name for " + value.Key + ".");
|
||||
SqlDbType type = value.Key == "Date" ? SqlDbType.DateTime2 :
|
||||
value.Key == "Successful" ? SqlDbType.Bit :
|
||||
value.Key == "P1Offset" || value.Key == "P2Offset" || value.Key == "P3Offset"
|
||||
? SqlDbType.Float : SqlDbType.Int;
|
||||
command.Parameters.Add(name, type).Value = value.Value ?? DBNull.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,8 @@ namespace GenesisCordonelInterface.Core
|
||||
gciExternalInterface = new InterfaceOutsideToGCI(
|
||||
new InterfaceGCIToLaatzen(),
|
||||
loginPasswordsDataStorageReader,
|
||||
calibrationParamsStorageReader);
|
||||
calibrationParamsStorageReader,
|
||||
gciConfig.DataStorageSection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +123,8 @@
|
||||
<Compile Include="Core\Config\GciConfig.cs" />
|
||||
<Compile Include="Core\Config\GciConfigLoader.cs" />
|
||||
<Compile Include="Core\DataStorage\Config\GciDataStorageConfig.cs" />
|
||||
<Compile Include="Core\DataStorage\Config\GciDatabaseWriterConfig.cs" />
|
||||
<Compile Include="Core\DataStorage\Writing\CalibrationResultWriter.cs" />
|
||||
<Compile Include="API\Enums.cs" />
|
||||
<Compile Include="Core\DataStorage\Reading\Common\Providers\CsvDataStorageReader.cs" />
|
||||
<Compile Include="Core\DataStorage\Reading\Common\Providers\DatabaseDataStorageReader.cs" />
|
||||
@@ -329,4 +331,4 @@
|
||||
<!-- Import custom GCI runtime packaging logic -->
|
||||
<Import Project="RuntimePackage\Build\Copy.targets.xml" />
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -31,6 +31,48 @@
|
||||
"Type": "LocalDatabase",
|
||||
"DataSource": "Server=(localdb)\\SensusLocalDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
|
||||
"QueryTemplate": "SELECT [ParameterName], [ParameterValue] FROM [dbo].[PreAdjustmentCalibrationParams] WHERE [MeterSize] = QUERYPARAM"
|
||||
},
|
||||
|
||||
"PreadjustmentCompletionWriter": {
|
||||
"Enabled": true,
|
||||
"DataSource": "Server=(localdb)\\MojaDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
|
||||
"CommandText": "INSERT INTO [dbo].[PreadjustmentCompletion] ([PcbId], [ZeroOffset1], [ZeroOffset2], [ZeroOffset3], [FirstHitUpdatePeriod], [FirstHitShift], [FirstHitPercent1], [FirstHitPercent2], [FirstHitPercent3], [ToFTempOffset1], [ToFTempOffset2], [ToFTempOffset3], [MeterSize], [Date], [Successful]) OUTPUT INSERTED.[Id] VALUES (@PcbId, @ZeroOffset1, @ZeroOffset2, @ZeroOffset3, @FirstHitUpdatePeriod, @FirstHitShift, @FirstHitPercent1, @FirstHitPercent2, @FirstHitPercent3, @ToFTempOffset1, @ToFTempOffset2, @ToFTempOffset3, @MeterSize, @Date, @Successful);",
|
||||
"UseStoredProcedure": false,
|
||||
"CommandTimeoutSeconds": 30,
|
||||
"ParameterMappings": {
|
||||
"PcbId": "@PcbId",
|
||||
"ZeroOffset1": "@ZeroOffset1",
|
||||
"ZeroOffset2": "@ZeroOffset2",
|
||||
"ZeroOffset3": "@ZeroOffset3",
|
||||
"FirstHitUpdatePeriod": "@FirstHitUpdatePeriod",
|
||||
"FirstHitShift": "@FirstHitShift",
|
||||
"FirstHitPercent1": "@FirstHitPercent1",
|
||||
"FirstHitPercent2": "@FirstHitPercent2",
|
||||
"FirstHitPercent3": "@FirstHitPercent3",
|
||||
"ToFTempOffset1": "@ToFTempOffset1",
|
||||
"ToFTempOffset2": "@ToFTempOffset2",
|
||||
"ToFTempOffset3": "@ToFTempOffset3",
|
||||
"MeterSize": "@MeterSize",
|
||||
"Date": "@Date",
|
||||
"Successful": "@Successful"
|
||||
}
|
||||
},
|
||||
"Q3CalibrationWriter": {
|
||||
"Enabled": true,
|
||||
"DataSource": "Server=(localdb)\\MojaDB;Database=UnionTownCalibAndSkeleton;Integrated Security=True;",
|
||||
"CommandText": "INSERT INTO [dbo].[Q3Calibration] ([PcbId], [P1Offset], [P1Cal], [P2Offset], [P2Cal], [P3Offset], [P3Cal], [Date]) OUTPUT INSERTED.[Id] VALUES (@PcbId, @P1Offset, @P1Cal, @P2Offset, @P2Cal, @P3Offset, @P3Cal, @Date);",
|
||||
"UseStoredProcedure": false,
|
||||
"CommandTimeoutSeconds": 30,
|
||||
"ParameterMappings": {
|
||||
"PcbId": "@PcbId",
|
||||
"P1Offset": "@P1Offset",
|
||||
"P1Cal": "@P1Cal",
|
||||
"P2Offset": "@P2Offset",
|
||||
"P2Cal": "@P2Cal",
|
||||
"P3Offset": "@P3Offset",
|
||||
"P3Cal": "@P3Cal",
|
||||
"Date": "@Date"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user