feat(poseidon communication): add V1 diagnostic frame support for C3/C4 data handling

- Introduced support for V1 optical diagnostic frames (C3/C4) with separate processing to prevent interference with metrology data.
- Added `DiagnosticTelegramReceived` callback in `OptoHeadService` for detailed logging of V1 frames.
- Enhanced `PoseidonOpticalLineParser` to parse and handle C3 calibration factors and C4 auxiliary ADC values.
- Implemented a new diagnostic logging method in `SmartReader` for V1 telegrams.
- Extended test coverage with new cases to validate C3/C4 frame parsing and diagnostic handling.
- Bumped assembly version to 3.9.3176.0.
This commit is contained in:
2026-10-19 15:12:23 +02:00
parent 1b678a5b4a
commit 6eeaa113f5
5 changed files with 155 additions and 10 deletions
+2 -2
View File
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// Build Number
// Revision
//
[assembly: AssemblyVersion("3.9.3175.0")]
[assembly: AssemblyFileVersion("3.9.3175.0")]
[assembly: AssemblyVersion("3.9.3176.0")]
[assembly: AssemblyFileVersion("3.9.3176.0")]
@@ -24,6 +24,7 @@ using ConfigStruct = TBF.Rig.RegisterReaders.CommonRR.IPerl.communication.Config
using MeterType = TBF.Rig.RegisterReaders.CommonRR.MeterType;
using PoseidonOpticalHead = TBF.Rig.RegisterReaders.PoseidonReader.communication.PoseidonOpticalHead;
using PoseidonOpticalHeadBuilder = TBF.Rig.RegisterReaders.PoseidonReader.communication.PoseidonOpticalHeadBuilder;
using PoseidonOpticalTelegram = TBF.Rig.RegisterReaders.PoseidonReader.communication.PoseidonOpticalTelegram;
using PoseidonProtocolProfile = TBF.Rig.RegisterReaders.PoseidonReader.communication.PoseidonProtocolProfile;
@@ -590,6 +591,7 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
diagnosticLastAccumulator = null;
diagnosticExtendedAccumulator = 0;
_optoHeadService.DiagnosticReceived = CaptureOpticalDiagnostic;
_optoHeadService.DiagnosticTelegramReceived = CaptureV1DiagnosticTelegram;
bool opened = _optoHeadService.CreateSerialConnection();
if (opened && iHeadCfg.ClearOpticalInputOnOpen)
_optoHeadService.DiscardPendingInput();
@@ -654,6 +656,19 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
null, null, "Stream", data == null ? null : data.ToString());
}
private void CaptureV1DiagnosticTelegram(PoseidonOpticalTelegram telegram)
{
if (_poseidonCfg == null || telegram == null || (telegram.C3 == null && telegram.C4 == null)) return;
string details = telegram.C3 != null ? telegram.C3.ToString() : telegram.C4.ToString();
byte[] raw = System.Text.Encoding.ASCII.GetBytes(telegram.RawLine ?? string.Empty);
opticalDiagnosticWriter.Write(_poseidonCfg.EnableDetailedLogPerWM,
_poseidonCfg.OpticalDiagnosticFormat, _poseidonCfg.RawOpticalDataFormat,
_poseidonCfg.IncludeParsedValues, Sequences.ProcessData.BatchNr,
Position > 0 ? Position.ToString() : Name, Name, SerialNr, telegram.ReceivedUtc,
"OpticalService/V1Diagnostic", "ParsedDiagnostic", raw, telegram.RawLine,
null, null, false, null, null, null, null, "Diagnostic", details);
}
private void OnOptoHandler(object sender, CommonRR.IPerl.communication.OptoReceivedEventArgs e)
{
//received data from optohead
@@ -76,6 +76,9 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
// Driver bytes and parse outcome, including rejected packets.
public Action<byte[], DateTime, WaterMetrologyData, bool> DiagnosticReceived { get; set; }
// Valid non-metrology V1 frames (for example C3/C4) are exposed
// separately so they can be logged without entering the test result.
public Action<PoseidonOpticalTelegram> DiagnosticTelegramReceived { get; set; }
public OptoHeadService(Con con)
: this(con, null)
@@ -193,10 +196,12 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
}
try
{
// Reflect the CURRENT ParseData branch, including its legacy
// simulation condition. Do not label simulated values as wire data.
DiagnosticReceived?.Invoke(rawDiagnosticData, receivedUtc, WaterMetrologyData,
Connection?.DebugModeSetting != DebugMode.Simulate);
// Empty polling is not a rejected frame. Only record actual
// COM data (or a produced metrology result) here; parsed C3/C4
// frames are recorded through DiagnosticTelegramReceived.
if ((rawDiagnosticData != null && rawDiagnosticData.Length > 0) || WaterMetrologyData != null)
DiagnosticReceived?.Invoke(rawDiagnosticData, receivedUtc, WaterMetrologyData,
Connection?.DebugModeSetting != DebugMode.Simulate);
}
catch (Exception ex)
{
@@ -278,6 +283,14 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
log.Warn("Poseidon optical V1 frame rejected: " + error);
return null;
}
try
{
DiagnosticTelegramReceived?.Invoke(telegram);
}
catch (Exception ex)
{
log.Warn("Poseidon V1 diagnostic telegram callback failed.", ex);
}
if (telegram.C7 != null) return WaterMetrologyData.FromC7(telegram.C7);
if (telegram.C2 != null) return WaterMetrologyData.FromC2(telegram.C2);
return null;
@@ -9,12 +9,88 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
public int Sequence { get; internal set; }
public byte MessageType { get; internal set; }
public string Payload { get; internal set; }
/// <summary>Complete V1 line, retained for diagnostic logging.</summary>
public string RawLine { get; internal set; }
public WaterMetrologyDataC2 C2 { get; internal set; }
public WaterMetrologyDataC7 C7 { get; internal set; }
public PoseidonMetrologyCalibrationFactors C3 { get; internal set; }
public PoseidonAuxAdcValues C4 { get; internal set; }
public PoseidonSystemInfoData SystemInfo { get; internal set; }
public PoseidonMeterTime MeterTime { get; internal set; }
}
/// <summary>V1 type C3. These values are diagnostic calibration data and
/// are deliberately not used by the metrology calculation.</summary>
public sealed class PoseidonMetrologyCalibrationFactors
{
public ushort MetrologyCalibrationFactor { get; private set; }
public short AsicTemperatureCalibration { get; private set; }
public short FieldSenseCalibrationFactor { get; private set; }
public int FieldFitCoefficientA0 { get; private set; }
public int FieldFitCoefficientA1 { get; private set; }
public ushort FieldDriveStepMagnitude { get; private set; }
internal static PoseidonMetrologyCalibrationFactors Parse(string payload)
{
byte[] bytes = Convert.FromBase64String(payload);
if (bytes.Length != 16) throw new ArgumentException("C3 payload must contain 16 bytes.");
return new PoseidonMetrologyCalibrationFactors
{
MetrologyCalibrationFactor = BitConverter.ToUInt16(bytes, 0),
AsicTemperatureCalibration = BitConverter.ToInt16(bytes, 2),
FieldSenseCalibrationFactor = BitConverter.ToInt16(bytes, 4),
FieldFitCoefficientA0 = BitConverter.ToInt32(bytes, 6),
FieldFitCoefficientA1 = BitConverter.ToInt32(bytes, 10),
FieldDriveStepMagnitude = BitConverter.ToUInt16(bytes, 14)
};
}
public override string ToString()
{
return string.Format("C3 calibration: Metrology={0}, AsicTemperature={1}, FieldSense={2}, A0={3}, A1={4}, DriveStep={5}",
MetrologyCalibrationFactor, AsicTemperatureCalibration, FieldSenseCalibrationFactor,
FieldFitCoefficientA0, FieldFitCoefficientA1, FieldDriveStepMagnitude);
}
}
/// <summary>One V1 type C4 auxiliary ADC sample and its source identifier.</summary>
public sealed class PoseidonAuxAdcValue
{
public ushort Sample { get; internal set; }
public byte Source { get; internal set; }
}
/// <summary>V1 type C4. Auxiliary ADC values are diagnostic only.</summary>
public sealed class PoseidonAuxAdcValues
{
public PoseidonAuxAdcValue[] Values { get; private set; }
internal static PoseidonAuxAdcValues Parse(string payload)
{
byte[] bytes = Convert.FromBase64String(payload);
if (bytes.Length != 24) throw new ArgumentException("C4 payload must contain 24 bytes.");
PoseidonAuxAdcValue[] values = new PoseidonAuxAdcValue[8];
for (int i = 0; i < values.Length; i++)
{
int offset = i * 3;
values[i] = new PoseidonAuxAdcValue
{
Sample = BitConverter.ToUInt16(bytes, offset),
Source = bytes[offset + 2]
};
}
return new PoseidonAuxAdcValues { Values = values };
}
public override string ToString()
{
string[] values = new string[Values == null ? 0 : Values.Length];
for (int i = 0; i < values.Length; i++)
values[i] = string.Format("ADC{0}={1} (source {2})", i, Values[i].Sample, Values[i].Source);
return "C4 auxiliary ADC: " + string.Join(", ", values);
}
}
/// <summary>Parser of an entire CR/LF terminated optical line. The caller is
/// responsible for stamping it at the serial-port boundary, before queuing.</summary>
public sealed class PoseidonOpticalLineParser
@@ -55,7 +131,10 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
if (XModemCrc16(crcText) != receivedCrc) { error = "Optical frame CRC16 mismatch."; return false; }
bool isExpectedMeasurement = (byte)messageType == profile.ExpectedMessageType;
bool isSystemInfo = (byte)messageType == 0xF0 && profile.ParseSystemInfo;
if (!isExpectedMeasurement && !isSystemInfo)
// C3/C4 are valid, intermittently emitted diagnostic payloads. They
// must not be treated as metrology samples or change the timing path.
bool isDiagnostic = (byte)messageType == 0xC3 || (byte)messageType == 0xC4;
if (!isExpectedMeasurement && !isSystemInfo && !isDiagnostic)
{
error = string.Format("Unexpected optical message type 0x{0:X2}; expected 0x{1:X2}{2}.",
messageType, profile.ExpectedMessageType, profile.ParseSystemInfo ? " or F0 System Info" : "");
@@ -69,7 +148,8 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
ReceivedUtc = utc,
Sequence = sequence,
MessageType = (byte)messageType,
Payload = fields[2]
Payload = fields[2],
RawLine = line.TrimEnd('\r', '\n')
};
if (isSystemInfo)
{
@@ -84,6 +164,14 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
IsEstimated = false
};
}
else if ((byte)messageType == 0xC3)
{
telegram.C3 = PoseidonMetrologyCalibrationFactors.Parse(fields[2]);
}
else if ((byte)messageType == 0xC4)
{
telegram.C4 = PoseidonAuxAdcValues.Parse(fields[2]);
}
else
{
if (profile.MeterTimeCompensation == PoseidonMeterTimeCompensation.RequireSystemInfoAnchor && latestSystemInfo == null)
@@ -8,7 +8,7 @@ namespace TBFTests.Rig.RegisterReaders.PoseidonReader
public class PoseidonProtocolProfileTests
{
[TestMethod]
public void B102AProfileSeparatesWrittenModeFromExpectedC7Telegram()
public void B102AProfileUsesC1ForWrittenModeAndExpectedTelegram()
{
PoseidonProtocolProfile profile = PoseidonProtocolProfileBuilder
.ForFirmware(PoseidonFirmwareGeneration.B1_0_2A)
@@ -16,7 +16,7 @@ namespace TBFTests.Rig.RegisterReaders.PoseidonReader
Assert.AreEqual(PoseidonOpticalProtocol.V1C1FilteredC7, profile.OpticalProtocol);
Assert.AreEqual((byte)0xC1, profile.OpticalDataMode);
Assert.AreEqual((byte)0xC7, profile.ExpectedMessageType);
Assert.AreEqual((byte)0xC1, profile.ExpectedMessageType);
Assert.AreEqual(38400, profile.OpticalBaudRate);
}
@@ -60,6 +60,35 @@ namespace TBFTests.Rig.RegisterReaders.PoseidonReader
StringAssert.Contains(error, "CRC16");
}
[TestMethod]
public void V1C3AndC4DiagnosticFramesParseWithoutBecomingMetrology()
{
PoseidonProtocolProfile profile = PoseidonProtocolProfileBuilder
.ForFirmware(PoseidonFirmwareGeneration.B1_0_2A)
.Build();
PoseidonOpticalLineParser parser = new PoseidonOpticalLineParser(profile);
PoseidonOpticalTelegram c3;
PoseidonOpticalTelegram c4;
string error;
Assert.IsTrue(parser.TryParse(CreateFrame("1A", "C3", "fQwAAEELFokFAMoFAACGBQ=="),
DateTime.UtcNow, out c3, out error), error);
Assert.IsNull(c3.C2);
Assert.IsNull(c3.C7);
Assert.AreEqual((ushort)3197, c3.C3.MetrologyCalibrationFactor);
Assert.AreEqual(362774, c3.C3.FieldFitCoefficientA0);
Assert.IsTrue(parser.TryParse(CreateFrame("16", "C4", "tAcIMA8OnQ0HLg8KxA4KXQIMBwgJAAAA"),
DateTime.UtcNow, out c4, out error), error);
Assert.IsNull(c4.C2);
Assert.IsNull(c4.C7);
Assert.AreEqual(8, c4.C4.Values.Length);
Assert.AreEqual((ushort)1972, c4.C4.Values[0].Sample);
Assert.AreEqual((byte)8, c4.C4.Values[0].Source);
Assert.AreEqual((ushort)0, c4.C4.Values[7].Sample);
Assert.AreEqual((byte)0, c4.C4.Values[7].Source);
}
[TestMethod]
public void ParsingWithMeterTimeUsesF0AnchorForFollowingC7()
{