iPerl ASIC - implementation

This commit is contained in:
2026-03-12 14:50:47 +01:00
parent 3c964f2aab
commit a997c3d7be
378 changed files with 5684 additions and 295925 deletions
@@ -31,7 +31,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
ThreadId,
WMNr0,
(Ihead != null) ? Ihead.Name : "null",
Wm.WMPosition,
(Wm != null) ? Wm.WMPosition : -1,
(CommMessage != null) ? CommMessage : "null",
CommErr);
}
@@ -1,4 +1,4 @@
using Config.Resources;
using Config.Resources;
using log4net;
using Sensus.iPerl.RfidCom.Helper;
using Sensus.iPerl.RfidCom.Services;
@@ -7,8 +7,6 @@ using System;
using System.Threading;
using TBF.Rig.Hart.Common;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.implementations;
using static Sensus.iPerl.NfcHandler.MCI_Protocol;
namespace TBF.Rig.TestMethods.iPerlCommunication
@@ -28,7 +26,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
try
{
byte[] pcb = null;
int readRetVal = IPerlCorrections.ReadRequestPort(SmartCommunicationForm.TestMethodCfg, iHead, RegisterReaders.CommonRR.MessageID.Configuration, Sensus.iPerl.NfcHandler.MCI_Protocol.StructName.Configuration, 16, 5, out pcb);
int readRetVal = iPerlCommunicationForm.ReadRequestPort(iHead, MessageID.Configuration, Sensus.iPerl.NfcHandler.MCI_Protocol.StructName.Configuration, 16, 5, out pcb);
if (readRetVal == 0)
{
return RfidHelper.HexLiteral2Unsigned(RfidHelper.SwapHexcode(BitConverter.ToString(pcb).Replace("-", string.Empty))).ToString();
@@ -45,7 +43,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
internal static string SetActiveMode(IperlHead iHead)
{
byte[] cmd = new byte[1] { (byte)Command.SetActiveMode };
if (0 == IPerlCorrections.WriteRequestPort(SmartCommunicationForm.TestMethodCfg, iHead, RegisterReaders.CommonRR.MessageID.Command, StructName.Command, 0, 1, cmd))
if (0 == iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.Command, StructName.Command, 0, 1, cmd))
{
return "OK";
}
@@ -58,7 +56,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
internal static string SetTestMode(IperlHead iHead)
{
byte[] cmd = new byte[1] { (byte)Command.SetTestMode };
if (0 == IPerlCorrections.WriteRequestPort(SmartCommunicationForm.TestMethodCfg, iHead, RegisterReaders.CommonRR.MessageID.Command, StructName.Command, 0, 1, cmd))
if (0 == iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.Command, StructName.Command, 0, 1, cmd))
{
return "OK";
}
@@ -73,7 +71,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
{
try
{
int retValue = IPerlCorrections.WriteRequestPort(SmartCommunicationForm.TestMethodCfg, iHead, RegisterReaders.CommonRR.MessageID.RadioPassthrough, StructName.RadioParams, 0x1898, 1, new byte[] { (byte)3 }); // WakeUpInterval
int retValue = iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.RadioPassthrough, StructName.RadioParams, 0x1898, 1, new byte[] { (byte)3 }); // WakeUpInterval
return 0 == retValue ? "OK" : "Error";
}
catch (Exception ex)
@@ -86,7 +84,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
{
try
{
int retValue = IPerlCorrections.WriteRequestPort(SmartCommunicationForm.TestMethodCfg,iHead, RegisterReaders.CommonRR.MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, 1, new byte[] { (byte)1 }); // System Status
int retValue = iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, 1, new byte[] { (byte)1 }); // System Status
return 0 == retValue ? "OK" : "Error";
}
catch (Exception ex)
@@ -6,7 +6,6 @@ using System.Collections.Generic;
using log4net;
using Common;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Rig.GenericDevices;
using TBF.Rig.Sequences;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
@@ -14,18 +13,20 @@ using TBF.UiBridge;
namespace TBF.Rig.TestMethods.iPerlCommunication
{
public class TestMethod : SmartComponentBase, ISimultTestMethod, ISequenceCondition, ISessionDataMngmnt
public class TestMethod : SmartComponentBase, ISimultTestMethod, ISequenceCondition, ISessionDataMngmnt, ITestMethodSmart
{
private static readonly ILog log = LogManager.GetLogger(typeof(TestMethod));
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
public override string ToString() { return string.Format("{0}({1})", ClassName, Cfg.ToString(-1)); }
public FlowType MethodFlowType => FlowType.volume;
public bool CanTest(MetersKind meters) { return meters == MetersKind.Single; }
public override string ToString() { return string.Format("{0}({1})", ClassName, Cfg.ToString(-1)); }
public bool CanTest(MetersKind meters) { return meters == MetersKind.Single; }
public bool DoTransitions() { return false; }
public bool SimultWithPrevious { get { return _testMethodCfgIPerl.TestParams.SimultWithPrevious; } }
public bool SimultWithNext { get { return _testMethodCfgIPerl.TestParams.SimultWithNext; } }
public bool SimultWithPrevious { get { return testMethodCfg.TestParams.SimultWithPrevious; } }
public bool SimultWithNext { get { return testMethodCfg.TestParams.SimultWithNext; } }
#region Configuration Change Handling
@@ -42,18 +43,18 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
{
CfgChangeHandler += delegate(object sender, CfgChangeArgs args)
{
TestMethodCfg_IPerl tmpCfgIPerl = args.Cfg as TestMethodCfg_IPerl;
if (tmpCfgIPerl != null && tmpCfgIPerl.Name.Equals(Name))
TestMethodCfg tmpCfg = args.Cfg as TestMethodCfg;
if (tmpCfg != null && tmpCfg.Name.Equals(Name))
{
if (args.Command == CfgChangeCmd.CfgChange)
{
_testMethodCfgIPerl.CommTimeout = tmpCfgIPerl.CommTimeout;
_testMethodCfgIPerl.DelayBetweenRetries = tmpCfgIPerl.DelayBetweenRetries;
_testMethodCfgIPerl.MaxCommRetries = tmpCfgIPerl.MaxCommRetries;
_testMethodCfgIPerl.IperlCheckErrorsToStop = tmpCfgIPerl.IperlCheckErrorsToStop;
_testMethodCfgIPerl.UseWebService = tmpCfgIPerl.UseWebService;
_testMethodCfgIPerl.BaseUrl = tmpCfgIPerl.BaseUrl;
_testMethodCfgIPerl.RelativeUrl = tmpCfgIPerl.RelativeUrl;
testMethodCfg.CommTimeout = tmpCfg.CommTimeout;
testMethodCfg.DelayBetweenRetries = tmpCfg.DelayBetweenRetries;
testMethodCfg.MaxCommRetries = tmpCfg.MaxCommRetries;
testMethodCfg.IperlCheckErrorsToStop = tmpCfg.IperlCheckErrorsToStop;
testMethodCfg.UseWebService = tmpCfg.UseWebService;
testMethodCfg.BaseUrl = tmpCfg.BaseUrl;
testMethodCfg.RelativeUrl = tmpCfg.RelativeUrl;
}
}
};
@@ -62,7 +63,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
#endregion Configuration Change Handling
readonly TestMethodCfg_IPerl _testMethodCfgIPerl;
readonly TestMethodCfg testMethodCfg;
public bool[] IperlCommMilestone;
IList<IOperation> sequenceConditionOps;
@@ -75,7 +76,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
public TestMethod(Generic.IComponentCfg cfg)
: base(cfg)
{
_testMethodCfgIPerl = cfg as TestMethodCfg_IPerl;
testMethodCfg = cfg as TestMethodCfg;
CreateMilestonesAndConditions();
}
@@ -110,7 +111,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
{
if (DebugLevel == DebugMode.Normal)
{
return (new iPerlCommunicationSeq()).Execute(test, repetNr, this, _testMethodCfgIPerl.TestParams);
return (new iPerlCommunicationSeq()).Execute(test, repetNr, this, testMethodCfg.TestParams);
}
else
{
@@ -14,9 +14,9 @@ using TBF.Rig.TestMethods.SmartMeterFlyingStartMassCollection;
namespace TBF.Rig.TestMethods.iPerlCommunication
{
[XmlRoot("TestMethodCfg")] // Add this attribute to match the XML root
public class TestMethodCfg_IPerl : ComponentCfgBase, IiPerlTestMethodCfg
public class TestMethodCfg : ComponentCfgBase, IiPerlTestMethodCfg
{
public static XmlSerializer Serializer = XmlSerializer.FromTypes(new[] { typeof(TestMethodCfg_IPerl) })[0];
public static XmlSerializer Serializer = XmlSerializer.FromTypes(new[] { typeof(TestMethodCfg) })[0];
public override XmlSerializer GetSerializer() { return Serializer; }
public IComponentCfgCtrl GetControl(IList<Config.Entities.Component> cmpntEntities) { return new TestMethodCfgCtrl(); }
@@ -30,7 +30,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
}
/// Private parameterless constructor invoked by all other (public) constructors
TestMethodCfg_IPerl()
TestMethodCfg()
{
Name = "SmartCommunication";
ParentName = string.Empty;
@@ -49,7 +49,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
TestParams = CreateTestParamsProvider() as iPerlCommunicationParams;
}
public TestMethodCfg_IPerl(IComponentFactory factory)
public TestMethodCfg(IComponentFactory factory)
: this()
{
this.Factory = factory;
@@ -7,7 +7,6 @@ using Common;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Resources;
using TBF.Rig.RegisterReaders.CommonRR.IPerl;
namespace TBF.Rig.TestMethods.iPerlCommunication
{
@@ -15,13 +14,13 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
{
public bool ShowMore { get { return false; } }
TestMethodCfg_IPerl config;
TestMethodCfg config;
public IComponentCfg Config
{
get { return config as IComponentCfg; }
set
{
config = value as TestMethodCfg_IPerl;
config = value as TestMethodCfg;
Redraw();
}
}
@@ -9,18 +9,16 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
public class TestMethodFactory : IComponentFactory
{
public string ClassName { get { return GetType().Namespace.Substring(8); } }
public override string ToString() { return ClassName; }
public IComponent DummyComponent() { return new TestMethod(); }
public IComponent GetComponent(IComponentCfg cfg, IList<IComponent> components) { return new TestMethod(cfg); }
public IComponentCfg DefaultConfig() { return new TestMethodCfg_IPerl(this); }
public IComponentCfg DefaultConfig() { return new TestMethodCfg(this); }
public IComponentCfg CmpntCfgFromCmpntEntity(Config.Entities.Component component)
{
return ComponentCfgBase.CreateFromDbEntity(TestMethodCfg_IPerl.Serializer, component, this);
return ComponentCfgBase.CreateFromDbEntity(TestMethodCfg.Serializer, component, this);
}
}
}
@@ -0,0 +1,351 @@
///
/// Copyright (c) 2015-2021 Sensus Metering Systems
///
using System;
using System.Globalization;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
namespace TBF.Rig.TestMethods.iPerlCommunication.common
{
public enum OptoTelegramFlags : byte
{
OK = 0,
OK_TestStart,
OK_TestEnd,
InvalidTelegram, /// Wrong telegram format of checksum error
SyncError,
}
public class OptoTelegramRaw
{
public static readonly int Length = 42;
private static CultureInfo culture;
///
/// Strobed value
///
public static decimal TestStartTimestampDec;
///
/// Stored values
///
public OptoTelegramFlags Flags;
public DateTime DateTime; /// From PC
public float RefFlow; /// [m3/h]
public int Counter;
public Int32 EmfRaw; /// Signed EMF from iPerl opto data
public Int16 MagneticFieldRaw;
public Int16 FlowRaw;
public double VolumeRaw;
public double VolumeRawExt;
public Int16 Impedance;
public double Timestamp;
public double TimestampExt;
public byte CheckSum;
///
/// Calculated values
///
public double EMF()
{
return 0.000000333 * (double)EmfRaw;
}
public double MagneticField() { return (double)MagneticFieldRaw; }
public double Flow(double scalingFactor) { return 0.225 * scalingFactor * (double)FlowRaw; }
public double Volume(double scalingFactor) { return 0.0000625 * scalingFactor * (double)VolumeRawExt; }
public Int32 FlipTime() { return Impedance; }
public decimal TimestampDec() { return (decimal)TimestampExt / (decimal)8192; }
public double VolumeDelta(double scalingFactor, OptoTelegramRaw previous) { return (previous == null) ? 0 : Volume(scalingFactor) - previous.Volume(scalingFactor); }
public decimal TimeDelta() { return TimestampDec() - TestStartTimestampDec; }
public string Label()
{
if (Flags == OptoTelegramFlags.OK_TestStart) return "#### start test ####";
else if (Flags == OptoTelegramFlags.OK_TestEnd) return "#### end of test ####";
else return string.Empty;
}
static OptoTelegramRaw()
{
culture = CultureInfo.CreateSpecificCulture("DE"); /// This is to use comma as decimal number separator
}
public OptoTelegramRaw()
{
}
/// <summary>
/// Parses optical telegram and returns OptoTelegramRaw object
/// </summary>
/// <description>
/// Create a configuration structure from a complete byte array
///
/// Telegram description:
///
/// AAAAAA[tab]BBBB[tab]CCCC[tab]DDDDDD[tab]EEEE[tab]FFFFFFFF[tab]GG[cr][lf] (42 bytes)
///
/// Data Comment Type Calculate to decimal
/// ----------------------------------------------------------------
/// AAAAAA EMF Int24 Value * 0.000000333
/// BBBB Magnetic field Int16 Value
/// CCCC Flow Int16 Value * 0.225 * Scalig factor
/// DDDDDD Volume Int24 Value / 16000 * Scaling factor
/// EEEE Impedance Int16 Value
/// FFFFFFFF Timestamp Uint32 Value / 8192
/// GG Checksum Byte
/// ----------------------------------------------------------------
///
/// Example:
/// FFFFFE 51EA 0000 65324E 0087 F6319DFF 86
/// FFDD3A 51F9 0000 65324E 0088 F631A60B 45
/// ...
/// </description>
/// <param name="data">A complete byte array data</param>
/// <returns>true = telegram OK, false = telegram NOK</returns>
// public bool UpdateFromString(string telegram, int counter, float refFlow, ref Int64 volumeRawExtLast, ref Int64 timestampExtLast, bool isLog = false)
// {
// DateTime = DateTime.Now;
// Counter = counter;
// RefFlow = refFlow;
//
// if ((telegram == null) || (telegram.Length < Length) ||
// (telegram[6] != '\t') || (telegram[11] != '\t') || (telegram[16] != '\t') ||
// (telegram[23] != '\t') || (telegram[28] != '\t') || (telegram[37] != '\t') ||
// (!isLog && (telegram[40] != '\r' || telegram[41] != '\n')))
// {
// Flags = OptoTelegramFlags.InvalidTelegram;
// return false;
// }
//
// UInt32 uEmfRaw;
// bool f1 = UInt32.TryParse(telegram.Substring(0, 6), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out uEmfRaw);
// EmfRaw = (uEmfRaw > 0x7FFFFF) ? ((int)uEmfRaw - 0x1000000) : (int)uEmfRaw;
//
// bool f2 = Int16.TryParse(telegram.Substring(7, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out MagneticFieldRaw);
// bool f3 = Int16.TryParse(telegram.Substring(12, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out FlowRaw);
// bool f4 = UInt32.TryParse(telegram.Substring(17, 6), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out VolumeRaw);
// bool f5 = Int16.TryParse(telegram.Substring(24, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out Impedance);
// bool f6 = UInt32.TryParse(telegram.Substring(29, 8), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out Timestamp);
// bool f7 = byte.TryParse(telegram.Substring(38, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CheckSum);
//
// byte calculatedCheckSum = 0;
// for (int i = 0; i < Length - 4; i++)
// {
// calculatedCheckSum += (byte)telegram[i];
// }
//
// bool allOk = f1 && f2 && f3 && f4 && f5 && f6 && f7 && (calculatedCheckSum == CheckSum);
//
// if (allOk)
// {
// ///
// /// Cope with 'VolumeRaw' overflow
// ///
// Int64 uncorrected = (Int64)(((UInt64)volumeRawExtLast & 0xFFFFFFFFFF000000UL) | VolumeRaw);
// if (Math.Abs(uncorrected - volumeRawExtLast) <= 0x800000L)
// {
// VolumeRawExt = volumeRawExtLast = uncorrected;
// }
// else if (Math.Abs(uncorrected + 0x1000000L - volumeRawExtLast) <= 0x800000L)
// {
// VolumeRawExt = volumeRawExtLast = uncorrected + 0x1000000L;
// }
// else if (Math.Abs(uncorrected - 0x1000000L - volumeRawExtLast) <= 0x800000L)
// {
// VolumeRawExt = volumeRawExtLast = uncorrected - 0x1000000L;
// }
// else
// {
// VolumeRawExt = volumeRawExtLast = uncorrected;
// }
//
// ///
// /// Cope with 'Timestamp' overflow
// ///
// uncorrected = (Int64)(((UInt64)timestampExtLast & 0xFFFFFFFF00000000UL) | Timestamp);
// if (Math.Abs(uncorrected - timestampExtLast) <= 0x80000000L)
// {
// TimestampExt = timestampExtLast = uncorrected;
// }
// else if (Math.Abs(uncorrected + 0x100000000L - timestampExtLast) <= 0x80000000L)
// {
// TimestampExt = timestampExtLast = uncorrected + 0x100000000L;
// }
// else if (Math.Abs(uncorrected - 0x100000000L - timestampExtLast) <= 0x80000000L)
// {
// TimestampExt = timestampExtLast = uncorrected - 0x100000000L;
// }
// else
// {
// TimestampExt = timestampExtLast = uncorrected;
// }
// }
//
// Flags = allOk ? OptoTelegramFlags.OK : OptoTelegramFlags.InvalidTelegram;
//
// return allOk;
// }
// -------- TIMESTAMP (seconds) --------
// bbbbbbbb – unsigned 32 bit ASIC time stamp in 8192 ticks per second– rolls over after 2^32
private const double TS_TICKS_PER_SEC = 8192.0;
private const double TS_RANGE = 4294967296.0 / TS_TICKS_PER_SEC; // 2^32 / 8192 = 524288 sec
// -------- VOLUME (liters) --------
// vvvvvv is unsigned 24-bit, 1 tick = 1/4 ml = 0.00025 L
private const double VOL_LITERS_PER_TICK = 0.00025; // liters per tick
private const double VOL_RANGE = 16777216.0 * VOL_LITERS_PER_TICK; // 2^24 * 0.00025 = 4194.304 L
// -------- VOLUME (liters) --------
private const double GAL_TO_LITER = 3.785411784;
public void UpdateFromSmart(
DiagnosticLedState4Data data,
int counter,
float refFlow,
ref double volumeRawExtLast,
ref double timestampExtLast)
{
DateTime = DateTime.Now;
Counter = counter;
RefFlow = refFlow;
FlowRaw = data.RawFlow;
VolumeRaw = data.RawVolume;
// ---- TIMESTAMP RAW (seconds, modulo TS_RANGE) ----
// If upstream conversion ever produced negative values, normalize them.
double ts = data.AsicTimestamp; // already in seconds, but wraps every TS_RANGE
ts = ts % TS_RANGE;
if (ts < 0) ts += TS_RANGE;
Timestamp = ts;
// ---------- VOLUME UNWRAP ----------
double v = VolumeRaw;
if (double.IsNaN(volumeRawExtLast))
{
VolumeRawExt = volumeRawExtLast = v;
}
else
{
// nearest-lap unwrap
//double k = Math.Round(volumeRawExtLast - v) / VOL_RANGE);
if (v < volumeRawExtLast)
{
VolumeRawExt = volumeRawExtLast = v + VOL_RANGE;
}
else
{
VolumeRawExt = volumeRawExtLast = v;
}
}
// ---------- TIMESTAMP UNWRAP (seconds) ----------
if (double.IsNaN(timestampExtLast))
{
TimestampExt = timestampExtLast = ts;
}
else
{
// robust unwrap: choose the smallest jump across the modulo boundary
double lastMod = timestampExtLast % TS_RANGE;
if (lastMod < 0) lastMod += TS_RANGE;
double delta = ts - lastMod;
if (delta < -TS_RANGE / 2.0) delta += TS_RANGE;
else if (delta > TS_RANGE / 2.0) delta -= TS_RANGE;
TimestampExt = timestampExtLast = timestampExtLast + delta;
}
}
/// <summary>
/// Alternative to UpdateFromString(...) when data are flushed
/// </summary>
public bool UpdateFromStringDummy(string telegram)
{
DateTime = DateTime.Now;
RefFlow = 0;
if ((telegram == null) || (telegram.Length < Length) ||
(telegram[6] != '\t') || (telegram[11] != '\t') || (telegram[16] != '\t') ||
(telegram[23] != '\t') || (telegram[28] != '\t') || (telegram[37] != '\t') ||
(telegram[40] != '\r') || (telegram[41] != '\n'))
{
Flags = OptoTelegramFlags.InvalidTelegram;
return false;
}
bool f7 = byte.TryParse(telegram.Substring(38, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CheckSum);
byte calculatedCheckSum = 0;
for (int i = 0; i < Length - 4; i++)
{
calculatedCheckSum += (byte)telegram[i];
}
bool allOk = f7 && (calculatedCheckSum == CheckSum);
Flags = allOk ? OptoTelegramFlags.OK : OptoTelegramFlags.InvalidTelegram;
return allOk;
}
public void SetFlags(OptoTelegramFlags flags)
{
this.Flags = flags;
}
public string ToString(double scalingFactor, OptoTelegramRaw previous)
{
if (Flags == OptoTelegramFlags.SyncError)
{
return "Sychronization error";
}
else if (Flags == OptoTelegramFlags.InvalidTelegram)
{
return "Invalid telegram";
}
else /// if (flags == OptoTelegramFlags.OK / OptoTelegramFlags.OK_TestStart / OptoTelegramFlags.OK_TestEnd)
{
return string.Format("{0}:{1}:{2}.{3}\t{4} :\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t{17}\t{18}\t{19}\t{20}\t{21}\t{22}",
DateTime.Hour.ToString("D2"),
DateTime.Minute.ToString("D2"),
DateTime.Second.ToString("D2"),
DateTime.Millisecond.ToString("D4"),
Counter,
(EmfRaw & 0x00FFFFFF).ToString("X6"),
MagneticFieldRaw.ToString("X4"),
FlowRaw.ToString("X4"),
VolumeRaw.ToString("X6"),
Impedance.ToString("X4"),
Timestamp.ToString("X8"),
CheckSum.ToString("X2"),
EMF().ToString("F4", culture),
MagneticField().ToString("F0", culture),
Flow(scalingFactor).ToString("F2", culture),
Volume(scalingFactor).ToString("F4", culture),
FlipTime().ToString("F0", culture),
TimestampDec().ToString("F4", culture),
(RefFlow * 1000).ToString("F2", culture),
VolumeDelta(scalingFactor, previous).ToString("F4", culture),
TimeDelta().ToString("F3", culture),
scalingFactor.ToString("F1", culture),
Label());
}
}
}
}
@@ -0,0 +1,25 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public sealed class IperlHatFrame
{
public byte Start { get; }
public byte Direction { get; }
public byte End { get; }
public byte Length { get; }
public byte[] CommandInformation { get; }
public byte[] Payload { get; }
public IperlHatFrame(byte start, byte direction, byte length, byte[] commandBytes, byte[] payload, byte end)
{
Start = start;
Direction = direction;
Length = length;
CommandInformation = commandBytes ?? Array.Empty<byte>();
Payload = payload ?? Array.Empty<byte>();
End = end;
}
}
}
@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public sealed class IperlHatFrameBuilder
{
private byte _direction;
private readonly List<byte> _commandBytes = new List<byte>();
private readonly List<byte> _payload = new List<byte>();
public IperlHatFrameBuilder RequestResponse(bool enabled)
{
_direction = enabled ? TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Write : TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Read;
return this;
}
public IperlHatFrameBuilder AddCommand(ProtocolCommand command)
{
_commandBytes.Add((byte)command);
return this;
}
public IperlHatFrameBuilder AddSubCommand(ProtocolCommand subCommand)
{
if (_commandBytes.Count == 0 ||
_commandBytes[0] != (byte)ProtocolCommand.DeviceSpecific)
throw new InvalidOperationException(
"Sub-command is only valid for DeviceSpecific (0xFD) commands.");
_commandBytes.Add((byte)subCommand);
return this;
}
public IperlHatFrameBuilder AddSubCommand(ProtocolStatuses subCommand)
{
if (_commandBytes.Count == 0 ||
_commandBytes[0] != (byte)ProtocolCommand.SetState)
throw new InvalidOperationException(
"Sub-command is only valid for SetState (0xA1) commands.");
_commandBytes.Add((byte)subCommand);
return this;
}
public IperlHatFrameBuilder AddDeviceCommand(
ProtocolDeviceSubCommand subCommand)
{
_commandBytes.Add((byte)ProtocolCommand.DeviceSpecific);
_commandBytes.Add((byte)subCommand);
return this;
}
public IperlHatFrameBuilder SetVersionCommand()
{
_commandBytes.Add((byte)ProtocolCommand.Question);
_payload.AddRange(TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Version);
return this;
}
public IperlHatFrameBuilder AddPayload(byte[] payload)
{
if (payload != null)
_payload.AddRange(payload);
return this;
}
public IperlHatFrameBuilder AddPayload(DiagnosticLedState state)
{
_payload.Add((byte)state);
return this;
}
public IperlHatFrameBuilder AddPayload(byte payload)
{
_payload.Add(payload);
return this;
}
public IperlHatFrameBuilder AddDiagnosticLedState(DiagnosticLedState state)
{
RequestResponse(true);
AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState);
AddPayload((byte)state);
return this;
}
public IperlHatFrameBuilder AddNullTerminatedAscii(string text)
{
if (!string.IsNullOrEmpty(text))
_commandBytes.AddRange(
System.Text.Encoding.ASCII.GetBytes(text));
_commandBytes.Add(0x00);
return this;
}
public IperlHatFrame BuildFrame()
{
if (_commandBytes.Count == 0)
throw new InvalidOperationException("No command specified.");
byte length = (byte)(4 + _commandBytes.Count + _payload.Count); // 4 = START + dirrection + LEN + END
return new IperlHatFrame(
TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start,
_direction,
length,
_commandBytes.ToArray(),
_payload.ToArray(),
TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End);
}
public byte[] BuildBytes()
{
IperlHatFrame frame = BuildFrame();
if (frame.CommandInformation.Length > 0 && frame.CommandInformation[0] == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question)
{
var bytes = new List<byte>
{
frame.Start,
frame.Direction,
};
bytes.AddRange(frame.CommandInformation);
bytes.AddRange(frame.Payload);
bytes.Add(frame.End);
return bytes.ToArray();
}
else
{
var bytes = new List<byte>
{
frame.Start,
frame.Direction,
frame.Length,
};
bytes.AddRange(frame.CommandInformation);
bytes.AddRange(frame.Payload);
bytes.Add(frame.End);
return bytes.ToArray();
}
}
}
}
@@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public sealed class IperlHatFrameParser
{
public IperlHatResponse Parse(byte[] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (data.Length < 5)
throw new FormatException("Frame too short.");
if (data[0] != TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start)
{
//if version parse version
if (data[0] == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question)
{
//Define Question answer
var prefix = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question };
var end = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End };
if (IsPrefixValid(data, prefix, end))
{
//whole payload may be like "vers: Harry T:B800, V:06.06.01, FW:190215, 7ECE, B1.6.01, HW:4, Serial:0"
prefix = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question };
byte[] payloadVersion = ExtractPayloadUsePrefix(data, prefix, end);
return new IperlHatResponse(TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question, payloadVersion.Length > 0 ? TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusOk : TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusNok, payloadVersion);
}
}
throw new FormatException("Invalid START byte.");
}
if (data[1] != TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Read)
throw new FormatException("Frame is no Response.");
byte length = data[2];
if (length != data.Length)
throw new FormatException("Length mismatch.");
byte direction = data[1];
byte status = data[3];
var prefixCommand = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start,direction,length,status };
var endCommand = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End };
byte[] payload = ExtractPayloadUsePrefix(data,prefixCommand,endCommand);
return new IperlHatResponse(0x00, status, payload);
}
private static byte[] ExtractPayloadUsePrefix(byte[] data, List<byte> prefix, List<byte> end)
{
// payload exists only if frame longer than:
// START + DIRECTION + LEN + CTRL + END = 5 bytes
// OR VERSION_START + VERSION = 5 bytes
if (data.Length <= 5)
return Array.Empty<byte>();
//check prefix is equal
int prefixLength = prefix.Count;
byte[] commandPrefix = new byte[prefixLength];
Buffer.BlockCopy(data, 0, commandPrefix, 0, prefixLength);
if (StartsWithPrefix(end, commandPrefix))
{
return Array.Empty<byte>();
}
int payloadLength = data.Length - (prefix.Count + end.Count);
byte[] payload = new byte[payloadLength];
Buffer.BlockCopy(data, prefix.Count, payload, 0, payloadLength);
return payload;
}
private static bool IsPrefixValid(byte[] data, List<byte> prefix, List<byte> end)
{
int prefixLength = prefix.Count;
// payload exists only if frame longer than:
// OR VERSION_START + VERSION = 5 bytes - "?VERS" version implemented
if (data.Length <= prefixLength) // need be and on END
return false;
//check prefix is equal
byte[] commandPrefix = new byte[prefixLength];
Buffer.BlockCopy(data, 0, commandPrefix, 0, prefixLength);
if (StartsWithPrefix(end, commandPrefix))
{
return false;
}
return true;
}
private static bool StartsWithPrefix(List<byte> data, byte[] prefix)
{
if (data.Count < prefix.Length)
return false;
for (int i = 0; i < prefix.Length; i++)
{
if (data[i] != prefix[i])
return false;
}
return true;
}
private static byte[] ExtractVersionPayload(byte[] data)
{
// payload exists only if frame longer than:
// START + LEN + CTRL + STATUS + CHK_HI + CHK_LO = 6 bytes
if (data.Length <= 5)
return Array.Empty<byte>();
int payloadLength = data.Length - 4;
byte[] payload = new byte[payloadLength];
Buffer.BlockCopy(data, 5, payload, 0, payloadLength);
return payload;
}
}
}
@@ -0,0 +1,10 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public static class IperlHatProtocol
{
public const byte START = 0x0D;
// Control bits (CNTRL1)
public const byte RESPONSE_FLAG = 0x08; // RF
}
}
@@ -0,0 +1,15 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public static class IperlHatProtocolConstants
{
public const byte Start = 0x53; //'S'
public const byte Write = 0x57; // 'W'
public const byte Read = 0x52; // 'R'
public const byte End = 0x0D; //'.'
public const byte Question = (byte)0x3F; // '?'
public static readonly byte[] Version = {0x76, 0x65, 0x72, 0x73 }; // 'v' 'e' 'r' 's'
public const byte StatusOk = 0x01;
public const byte StatusNok = 0x00;
}
}
@@ -0,0 +1,94 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public sealed class IperlHatResponse
{
public byte Control { get; } //classic control byte - valid for question now
private byte Status { get; }
public byte[] Payload { get; }
public bool IsOk => Status == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusOk;
public IperlHatResponse(byte control, byte status, byte[] payload)
{
Control = control;
Status = status;
Payload = payload ?? Array.Empty<byte>();
}
public int GetResponse(ref bool isInt)
{
if (Payload.Length > 0 && Payload.Length <= 1)
{
isInt = true;
return Payload[0];
}
isInt = false;
return 0xFD;
}
public T GetResponse<T>(out bool ok) where T : struct
{
ok = false;
// we expect exactly 1 byte payload
if (Payload == null || Payload.Length != 1)
return default;
byte raw = Payload[0];
Type t = typeof(T);
// ----- BYTE -----
if (t == typeof(byte))
{
ok = true;
return (T)(object)raw;
}
// ----- INT -----
if (t == typeof(int))
{
ok = true;
return (T)(object)(int)raw;
}
// ----- USHORT -----
if (t == typeof(ushort))
{
ok = true;
return (T)(object)(ushort)raw;
}
// ----- ENUM -----
if (t.IsEnum)
{
// check if value exists in enum
if (!Enum.IsDefined(t, raw))
return default;
ok = true;
return (T)Enum.ToObject(t, raw);
}
// unsupported type
return default;
}
public string GetAsciiPayload()
{
if (Payload.Length == 0)
return null;
int length = Array.IndexOf(Payload, (byte)0x00);
if (length < 0)
length = Payload.Length;
return System.Text.Encoding.ASCII.GetString(Payload, 0, length);
}
}
}
@@ -0,0 +1,75 @@
using System;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed
{
public sealed class DiagnosticLedParser
{
private readonly DiagnosticLedState _state;
public DiagnosticLedParser(DiagnosticLedState state)
{
_state = state;
}
public DiagnosticLedData ParseLine(string line, bool checkLineTermination = true)
{
if (string.IsNullOrEmpty(line))
throw new ArgumentNullException(nameof(line));
if (checkLineTermination && !line.EndsWith("\r\n"))
throw new FormatException("Invalid diagnostic LED line termination");
string trimmed = line.TrimEnd('\r', '\n');
string[] parts = trimmed.Split('\t');
if (parts.Length < 2)
throw new FormatException("Too few diagnostic LED fields");
// ---- Checksum ----
string checksumHex = parts[parts.Length - 1];
int lastTab = trimmed.LastIndexOf('\t');
if (lastTab < 0)
throw new FormatException("Checksum separator not found");
string beforeChecksum = trimmed.Substring(0, lastTab + 1);
byte expected = DiagnosticChecksum.Compute(beforeChecksum);
byte actual = DiagnosticHex.ParseByte(checksumHex);
if (expected != actual)
throw new FormatException("Diagnostic LED checksum mismatch");
// ---- Dispatch ----
switch (_state)
{
case DiagnosticLedState.State1:
return new DiagnosticLedState1Data(line, parts);
case DiagnosticLedState.State2:
return new DiagnosticLedState2Data(line, parts);
case DiagnosticLedState.State3:
return new DiagnosticLedState3Data(line, parts);
case DiagnosticLedState.State4:
return new DiagnosticLedState4Data(line, parts);
case DiagnosticLedState.State5:
return new DiagnosticLedState5Data(line, parts);
case DiagnosticLedState.State6:
return new DiagnosticLedState6Data(line, parts);
case DiagnosticLedState.State7:
return new DiagnosticLedState7Data(line, parts);
default:
throw new NotSupportedException("Unknown diagnostic LED state");
}
}
}
}
@@ -0,0 +1,100 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed
{
/// <summary>
/// Diagnostic LED output mode.
/// <para>
/// Determines the format and content of high-speed serial diagnostic data
/// emitted by the meter when the diagnostic LED is enabled.
/// </para>
/// <para>
/// Each state corresponds to a specific TAB-separated ASCII HEX frame layout
/// as defined in the iPERL TouchRead protocol documentation.
/// </para>
/// <para>
/// See <see cref="ProtocolDeviceSubCommand.SetDiagnosticLEDState"/>
/// diagnostic LED States.
/// </para>
/// </summary>
public enum DiagnosticLedState : byte
{
/// <summary>
/// Diagnostic LED OFF - State #0.
/// <para>
/// Basic diagnostic output containing raw ADC, field strength,
/// flow rate, volume accumulator, and capacitor voltage.
/// </para>
/// </summary>
StateOFF = 0x00,
/// <summary>
/// Diagnostic LED State #1.
/// <para>
/// Basic diagnostic output containing raw ADC, field strength,
/// flow rate, volume accumulator, and capacitor voltage.
/// </para>
/// </summary>
State1 = 0x01,
/// <summary>
/// Diagnostic LED State #2.
/// <para>
/// Extends State #1 with LCD volume, meter state,
/// and low-flow cutoff indication.
/// </para>
/// </summary>
State2 = 0x02,
/// <summary>
/// Diagnostic LED State #3.
/// <para>
/// Extends State #1 with field calibration value,
/// ASIC timestamp, and field drive time.
/// </para>
/// </summary>
State3 = 0x03,
/// <summary>
/// Diagnostic LED State #4.
/// <para>
/// Extended diagnostic output including mean flow rate,
/// field measurements, integrator calibration values,
/// and ASIC state.
/// </para>
/// </summary>
State4 = 0x04,
/// <summary>
/// Diagnostic LED State #5.
/// <para>
/// Extends State #4 with water impedance measurement.
/// </para>
/// </summary>
State5 = 0x05,
/// <summary>
/// Diagnostic LED State #6.
/// <para>
/// Extends State #5 with electrode delta, spike detection data,
/// pipe status, LCD volume, and additional ASIC state.
/// </para>
/// </summary>
State6 = 0x06,
/// <summary>
/// Diagnostic LED State #7.
/// <para>
/// Extends State #6 with raw ADC before offset correction,
/// detrended ADC value, imaginary water impedance,
/// electrode voltage noise, and ADC offset learning status.
/// </para>
/// </summary>
State7 = 0x07,
/// <summary>
/// Unknown state.
/// </summary>
StatusUnknown = 0xFF,
}
}
@@ -0,0 +1,114 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Base class for all Diagnostic LED data frames.
///
/// <para>
/// The iPERL meter emits diagnostic LED frames when the
/// Diagnostic LED is enabled using the
/// <c>Set Diagnostic LED State (0xFD 0x60)</c> command.
/// </para>
///
/// <para>
/// All diagnostic LED states (State #1 – State #7) share a common
/// set of leading fields, followed by state-specific extensions.
/// This class represents those common fields.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>Pos</term>
/// <description>Common field description</description>
/// </listheader>
/// <item><term>0 – xxxxxx</term><description>Signed 24-bit ADC value (two’s complement)</description></item>
/// <item><term>1 – aaaa</term><description>Unsigned 16-bit field strength (internal units)</description></item>
/// <item><term>2 – yyyy</term><description>Signed 16-bit raw flow rate (¼ ml per bit)</description></item>
/// <item><term>3 – vvvvvv</term><description>Unsigned 24-bit raw volume accumulation (¼ ml per bit)</description></item>
/// <item><term>4 – cccc</term><description>Unsigned 16-bit millivolt delta on the field drive capacitor</description></item>
/// </list>
///
/// <para>
/// Each derived state class parses additional fields starting at
/// position 5, according to the selected diagnostic LED state.
/// </para>
///
/// <para>
/// The raw ASCII line (including checksum and CRLF) is preserved
/// for logging, debugging, and offline analysis.
/// </para>
/// </summary>
public abstract class DiagnosticLedData
{
const double GalToLiterConversion = 3.785411784D;
public abstract int GetByteCount();
/// <summary>
/// Raw diagnostic LED line exactly as received from the meter,
/// including checksum and CRLF.
/// </summary>
public string RawLine { get; }
// ----- Common fields (present in all LED states) -----
/// <summary>
/// Signed 24-bit ADC value (two’s complement).
/// </summary>
public int Adc24 { get; protected set; }
/// <summary>
/// Unsigned 16-bit field strength in internal (non-legacy) units.
/// </summary>
public ushort FieldStrength { get; protected set; }
/// <summary>
/// Signed 16-bit raw flow rate in units of ¼ milliliter per bit.
/// </summary>
public short RawFlow { get; protected set; }
/// <summary>
/// Unsigned 24-bit raw volume accumulation in units of ¼ milliliter per bit. it is in Gal * 2
/// </summary>
public uint RawVolume1to4 { get; protected set; } // in 1/4 ml Gal * 2
/// <summary>
/// Raw volume in liters
/// </summary>
public double RawVolume // in liter
{
get
{
double volume = (RawVolume1to4 * 0.00025) ; // convert to liters
return volume;
}
}
/// <summary>
/// Raw volume in Gal
/// </summary>
public double RawVolumeInGal // in Gal
{
get
{
double volume = (RawVolume1to4 * 4.0) / 1000.0F; // convert to Gal
//volume = (volume / GalToLiterConversion) / 2; // convert to liter
return volume;
}
}
/// <summary>
/// Unsigned 16-bit millivolt delta measured on the field drive capacitor.
/// </summary>
public ushort CapacitorMv { get; protected set; }
/// <summary>
/// Initializes the base diagnostic LED data with the raw input line.
/// </summary>
/// <param name="raw">
/// Raw ASCII line received from the diagnostic LED output.
/// </param>
protected DiagnosticLedData(string raw)
{
RawLine = raw;
}
}
}
@@ -0,0 +1,37 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
public static class DiagnosticLedFrameSpec
{
public static int GetExpectedAsciiLength(DiagnosticLedState state)
{
switch (state)
{
case DiagnosticLedState.State1: return 33;
case DiagnosticLedState.State2: return 48;
case DiagnosticLedState.State3: return 50;
case DiagnosticLedState.State4: return 84;
case DiagnosticLedState.State5: return 89;
case DiagnosticLedState.State6: return 112;
case DiagnosticLedState.State7: return 139;
default: throw new ArgumentOutOfRangeException(nameof(state));
}
}
public static int GetExpectedFieldCount(DiagnosticLedState state)
{
switch (state)
{
case DiagnosticLedState.State1: return 6;
case DiagnosticLedState.State2: return 9;
case DiagnosticLedState.State3: return 9;
case DiagnosticLedState.State4: return 15;
case DiagnosticLedState.State5: return 16;
case DiagnosticLedState.State6: return 21;
case DiagnosticLedState.State7: return 26;
default: throw new ArgumentOutOfRangeException(nameof(state));
}
}
}
}
@@ -0,0 +1,58 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #1 data frame.
///
/// <para>
/// Frame format: TAB-separated ASCII hexadecimal fields, terminated by CRLF.
/// The checksum is an 8-bit sum of all previous ASCII bytes including
/// the TAB character before the checksum field.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>Pos</term>
/// <description>Field description</description>
/// </listheader>
/// <item><term>0 – xxxxxx</term><description>Signed 24-bit ADC value (two’s complement)</description></item>
/// <item><term>1 – aaaa</term><description>Unsigned 16-bit field strength (internal units)</description></item>
/// <item><term>2 – yyyy</term><description>Signed 16-bit raw flow rate (¼ ml per bit)</description></item>
/// <item><term>3 – vvvvvv</term><description>Unsigned 24-bit raw volume accumulation (¼ ml per bit)</description></item>
/// <item><term>4 – cccc</term><description>Unsigned 16-bit millivolt delta on the field drive capacitor</description></item>
/// <item><term>5 – ss</term><description>Unsigned 8-bit checksum (sum of all previous ASCII bytes
/// including the TAB before the checksum field)</description></item>
/// </list>
/// </summary>
public class DiagnosticLedState1Data : DiagnosticLedData
{
public DiagnosticLedState1Data(string raw, string[] f)
: base(raw)
{
Adc24 = DiagnosticHex.ParseInt24(f[0]);
FieldStrength = DiagnosticHex.ParseUInt16(f[1]);
RawFlow = DiagnosticHex.ParseInt16(f[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(f[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(f[4]);
}
public override string ToString()
{
return $"DiagnosticLedState1Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc ss
/// Chars total = 26
/// Tabs = 5
/// CRLF = 2
/// Total bytes = 33
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 33;
}
}
}
@@ -0,0 +1,90 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #2 data frame.
///
/// <para>
/// State #2 extends the common diagnostic LED fields with information
/// about the LCD-displayed volume, the current meter operating state,
/// and whether the meter is in low-flow cutoff mode.
/// </para>
///
/// <para>
/// Frame format: TAB-separated ASCII hexadecimal fields, terminated by CRLF.
/// The checksum is an 8-bit sum of all previous ASCII bytes including
/// the TAB character before the checksum field.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>Pos</term>
/// <description>Field description</description>
/// </listheader>
/// <item><term>0 – xxxxxx</term><description>Signed 24-bit ADC value (two’s complement)</description></item>
/// <item><term>1 – aaaa</term><description>Unsigned 16-bit field strength (internal units)</description></item>
/// <item><term>2 – yyyy</term><description>Signed 16-bit raw flow rate (¼ ml per bit)</description></item>
/// <item><term>3 – vvvvvv</term><description>Unsigned 24-bit raw volume accumulation (¼ ml per bit)</description></item>
/// <item><term>4 – cccc</term><description>Unsigned 16-bit millivolt delta on the field drive capacitor</description></item>
/// <item><term>5 – gggggggg</term><description>Unsigned 32-bit volume displayed on the LCD</description></item>
/// <item><term>6 – mm</term><description>Unsigned 8-bit meter state (see Table 17-23 in protocol documentation)</description></item>
/// <item><term>7 – ff</term><description>Unsigned 8-bit boolean flag indicating low-flow cutoff
/// state (0 = false, 1 = true)</description></item>
/// <item><term>8 – ss</term><description>Unsigned 8-bit checksum (sum of all previous ASCII bytes including
/// the TAB before the checksum field)</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState2Data : DiagnosticLedData
{
/// <summary>
/// Volume displayed on LCD (raw units).
/// </summary>
public uint LcdVolume { get; }
/// <summary>
/// Meter state (see Table 17-23).
/// </summary>
public byte MeterState { get; }
/// <summary>
/// True if meter is in low-flow cutoff.
/// </summary>
public bool IsLowFlowCutoff { get; }
public DiagnosticLedState2Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (0–4) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #2 specific ----
LcdVolume = DiagnosticHex.ParseUInt32(fields[5]);
MeterState = DiagnosticHex.ParseByte(fields[6]);
IsLowFlowCutoff = DiagnosticHex.ParseByte(fields[7]) != 0;
}
public override string ToString()
{
return $"DiagnosticLedState2Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, LcdVolume={LcdVolume}, MeterState={MeterState}, IsLowFlowCutoff={IsLowFlowCutoff}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc gggggggg mm ff ss
/// Chars total = 38
/// Tabs = 8
/// CRLF = 2
/// Total bytes = 48
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 48;
}
}
}
@@ -0,0 +1,89 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #3 data frame.
///
/// <para>
/// State #3 extends the common diagnostic LED fields with calibration
/// and timing information related to the field drive and ASIC operation.
/// </para>
///
/// <para>
/// Frame format: TAB-separated ASCII hexadecimal fields, terminated by CRLF.
/// The checksum is an 8-bit sum of all previous ASCII bytes including
/// the TAB character before the checksum field.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>Pos</term>
/// <description>Field description</description>
/// </listheader>
/// <item><term>0 – xxxxxx</term><description>Signed 24-bit ADC value (two’s complement)</description></item>
/// <item><term>1 – aaaa</term><description>Unsigned 16-bit field strength (internal units)</description></item>
/// <item><term>2 – yyyy</term><description>Signed 16-bit raw flow rate (¼ ml per bit)</description></item>
/// <item><term>3 – vvvvvv</term><description>Unsigned 24-bit raw volume accumulation (¼ ml per bit)</description></item>
/// <item><term>4 – cccc</term><description>Unsigned 16-bit millivolt delta on the field drive capacitor</description></item>
/// <item><term>5 – tttt</term><description>Unsigned 16-bit field calibration value</description></item>
/// <item><term>6 – bbbbbbbb</term><description>Unsigned 32-bit ASIC timestamp (8192 ticks per second,
/// rolls over at 2^32)</description></item>
/// <item><term>7 – ff</term><description>Unsigned 8-bit field drive time in microseconds</description></item>
/// <item><term>8 – ss</term><description>Unsigned 8-bit checksum (sum of all previous ASCII bytes including
/// the TAB before the checksum field)</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState3Data : DiagnosticLedData
{
/// <summary>
/// Unsigned 16-bit field calibration value.
/// </summary>
public ushort FieldCalibration { get; }
/// <summary>
/// ASIC timestamp in units of 1 / 8192 seconds.
/// Rolls over at 2^32.
/// </summary>
public uint AsicTimestamp { get; }
/// <summary>
/// Field drive time in microseconds.
/// </summary>
public byte FieldDriveTimeUs { get; }
public DiagnosticLedState3Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (0–4) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #3 specific fields ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestamp = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
}
public override string ToString()
{
return $"DiagnosticLedState3Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc tttt bbbbbbbb ff ss
/// Chars total = 40
/// Tabs = 8
/// CRLF = 2
/// Total bytes = 50
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 50;
}
}
}
@@ -0,0 +1,104 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #4 data frame.
/// <para>Frame format (TAB-separated ASCII HEX fields, CRLF terminated).</para>
/// <list type="table">
/// <listheader>
/// <term># / Field</term>
/// <description>Description</description>
/// </listheader>
/// <item><term>0 – xxxxxx</term><description>signed 24-bit ADC value</description></item>
/// <item><term>1 – aaaa</term><description>unsigned 16-bit Field strength</description></item>
/// <item><term>2 – yyyy</term><description>signed 16-bit Raw flow rate (1/4 ml per bit)</description></item>
/// <item><term>3 – vvvvvv</term><description>unsigned 24 bit raw volume accumulation in ¼ ml per bit</description></item>
/// <item><term>4 – cccc</term><description>unsigned 16-bit Capacitor mV delta</description></item>
/// <item><term>5 – tttt</term><description>unsigned 16-bit Field calibration</description></item>
/// <item><term>6 – bbbbbbbb</term><description>unsigned 32-bit ASIC timestamp</description></item>
/// <item><term>7 – ff</term><description>unsigned 8-bit Field drive time (µs)</description></item>
/// <item><term>8 – mmmmmmmm</term><description>signed 32-bit Mean flow rate</description></item>
/// <item><term>9 – gggg</term><description>unsigned 16-bit Field 1 measurement</description></item>
/// <item><term>10 – hhhh</term><description>unsigned 16-bit Field 2 measurement</description></item>
/// <item><term>11 – cccc</term><description>unsigned 16-bit Integrator calibration positive</description></item>
/// <item><term>12 – nnnn</term><description>unsigned 16-bit Integrator calibration negative</description></item>
/// <item><term>13 – qq</term><description>unsigned 8-bit ASIC state</description></item>
/// <item><term>14 – ss</term><description>unsigned 8-bit Checksum</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState4Data : DiagnosticLedData
{
public ushort FieldCalibration { get; }
/// <summary>
/// ASIC timestamp in seconds
/// </summary>
public double AsicTimestamp
{
get { return AsicTimestampTicks / 8192; } //4096.0; }
}
/// <summary>
/// ASIC timestamp in units of 1 / 4096 seconds.
/// </summary>
public uint AsicTimestampTicks { get; }
public byte FieldDriveTimeUs { get; }
public int MeanFlowRate { get; }
public ushort Field1Measurement { get; }
public ushort Field2Measurement { get; }
public ushort IntegratorCalibrationPositive { get; }
public ushort IntegratorCalibrationNegative { get; }
public byte AsicState { get; }
public DiagnosticLedState4Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (0–4) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]); //1/4 ml Gal double
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #4 specific ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestampTicks = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
MeanFlowRate = unchecked((int)DiagnosticHex.ParseUInt32(fields[8]));
Field1Measurement = DiagnosticHex.ParseUInt16(fields[9]);
Field2Measurement = DiagnosticHex.ParseUInt16(fields[10]);
IntegratorCalibrationPositive = DiagnosticHex.ParseUInt16(fields[11]);
IntegratorCalibrationNegative = DiagnosticHex.ParseUInt16(fields[12]);
AsicState = DiagnosticHex.ParseByte(fields[13]);
}
public override string ToString()
{
return $"DiagnosticLedState4Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, RawVolume1to4 = {RawVolume1to4}, RawVolumeGal={RawVolumeInGal}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}, MeanFlowRate={MeanFlowRate}, Field1Measurement={Field1Measurement}, Field2Measurement={Field2Measurement}, IntegratorCalibrationPositive={IntegratorCalibrationPositive}, IntegratorCalibrationNegative={IntegratorCalibrationNegative}, AsicState={AsicState}, RawLine={RawLine}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc tttt bbbbbbbb mmmmmmmm ff gggg hhhh cccc nnnn qq ss
/// Chars total = 68
/// Tabs = 14
/// CRLF = 2
/// Total bytes = 84
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 84;
}
}
}
@@ -0,0 +1,111 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #5 data frame.
/// <para>
/// Frame format: TAB-separated ASCII HEX fields, CRLF terminated.
/// </para>
/// <list type="table">
/// <listheader>
/// <term># / Field</term>
/// <description>Description</description>
/// </listheader>
/// <item><term>0 – xxxxxx</term><description>signed 24-bit ADC value</description></item>
/// <item><term>1 – aaaa</term><description>unsigned 16-bit Field strength (internal units)</description></item>
/// <item><term>2 – yyyy</term><description>signed 16-bit Raw flow rate (1/4 ml per bit)</description></item>
/// <item><term>3 – vvvvvv</term><description>unsigned 24-bit Raw volume accumulation (1/4 ml per bit)</description></item>
/// <item><term>4 – cccc</term><description>unsigned 16-bit Millivolts delta on field drive capacitor</description></item>
/// <item><term>5 – tttt</term><description>unsigned 16-bit Field calibration value</description></item>
/// <item><term>6 – bbbbbbbb</term><description>unsigned 32-bit ASIC timestamp (8192 ticks/sec, rolls over at 2^32)</description></item>
/// <item><term>7 – ff</term><description>unsigned 8-bit Field drive time in microseconds</description></item>
/// <item><term>8 – mmmmmmmm</term><description>signed 32-bit Mean flow rate (rolls over at 2^32)</description></item>
/// <item><term>9 – gggg</term><description>unsigned 16-bit Field 1 measurement</description></item>
/// <item><term>10 – hhhh</term><description>unsigned 16-bit Field 2 measurement</description></item>
/// <item><term>11 – cccc</term><description>unsigned 16-bit Integrator calibration positive</description></item>
/// <item><term>12 – nnnn</term><description>unsigned 16-bit Integrator calibration negative</description></item>
/// <item><term>13 – qq</term><description>unsigned 8-bit ASIC state</description></item>
/// <item><term>14 – iiii</term><description>signed 16-bit Water impedance measurement</description></item>
/// <item><term>15 – ss</term><description>unsigned 8-bit Checksum</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState5Data : DiagnosticLedData
{
/// <summary>Field calibration value (tttt).</summary>
public ushort FieldCalibration { get; }
/// <summary>ASIC timestamp (bbbbbbbb), 8192 ticks per second.</summary>
public uint AsicTimestamp { get; }
/// <summary>Field drive time in microseconds (ff).</summary>
public byte FieldDriveTimeUs { get; }
/// <summary>Mean flow rate (mmmmmmmm), signed 32-bit.</summary>
public int MeanFlowRate { get; }
/// <summary>Field 1 measurement (gggg).</summary>
public ushort Field1Measurement { get; }
/// <summary>Field 2 measurement (hhhh).</summary>
public ushort Field2Measurement { get; }
/// <summary>Integrator calibration positive (cccc).</summary>
public ushort IntegratorCalibrationPositive { get; }
/// <summary>Integrator calibration negative (nnnn).</summary>
public ushort IntegratorCalibrationNegative { get; }
/// <summary>ASIC state (qq).</summary>
public byte AsicState { get; }
/// <summary>Water impedance measurement (iiii), signed 16-bit.</summary>
public short WaterImpedance { get; }
public DiagnosticLedState5Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #5 specific ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestamp = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
MeanFlowRate = unchecked((int)DiagnosticHex.ParseUInt32(fields[8]));
Field1Measurement = DiagnosticHex.ParseUInt16(fields[9]);
Field2Measurement = DiagnosticHex.ParseUInt16(fields[10]);
IntegratorCalibrationPositive = DiagnosticHex.ParseUInt16(fields[11]);
IntegratorCalibrationNegative = DiagnosticHex.ParseUInt16(fields[12]);
AsicState = DiagnosticHex.ParseByte(fields[13]);
WaterImpedance = DiagnosticHex.ParseInt16(fields[14]);
}
public override string ToString()
{
return $"DiagnosticLedState5Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}, MeanFlowRate={MeanFlowRate}, Field1Measurement={Field1Measurement}, Field2Measurement={Field2Measurement}, IntegratorCalibrationPositive={IntegratorCalibrationPositive}, IntegratorCalibrationNegative={IntegratorCalibrationNegative}, AsicState={AsicState}, WaterImpedance={WaterImpedance}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc tttt bbbbbbbb mmmmmmmm ff iiii ss
/// Chars total = 72
/// Tabs = 15
/// CRLF = 2
/// Total bytes = 89
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 89;
}
}
}
@@ -0,0 +1,152 @@
using System;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #6 data frame.
/// <para>
/// Frame format: TAB-separated ASCII HEX fields, CRLF terminated.
/// </para>
/// <list type="table">
/// <listheader>
/// <term># / Field</term>
/// <description>Description</description>
/// </listheader>
/// <item><term>0 – xxxxxx</term><description>signed 24-bit ADC value</description></item>
/// <item><term>1 – aaaa</term><description>unsigned 16-bit Field strength (internal units)</description></item>
/// <item><term>2 – yyyy</term><description>signed 16-bit Raw flow rate (1/4 ml per bit)</description></item>
/// <item><term>3 – vvvvvv</term><description>unsigned 24-bit Raw volume accumulation (1/4 ml per bit)</description></item>
/// <item><term>4 – cccc</term><description>unsigned 16-bit Millivolts delta on field drive capacitor</description></item>
/// <item><term>5 – tttt</term><description>unsigned 16-bit Field calibration value</description></item>
/// <item><term>6 – bbbbbbbb</term><description>unsigned 32-bit ASIC timestamp (8192 ticks/sec, rolls over at 2^32)</description></item>
/// <item><term>7 – ff</term><description>unsigned 8-bit Field drive time in microseconds</description></item>
/// <item><term>8 – mmmmmmmm</term><description>signed 32-bit Mean flow rate (rolls over at 2^32)</description></item>
/// <item><term>9 – gggg</term><description>unsigned 16-bit Field 1 measurement</description></item>
/// <item><term>10 – hhhh</term><description>unsigned 16-bit Field 2 measurement</description></item>
/// <item><term>11 – cccc</term><description>unsigned 16-bit Integrator calibration positive</description></item>
/// <item><term>12 – nnnn</term><description>unsigned 16-bit Integrator calibration negative</description></item>
/// <item><term>13 – qq</term><description>unsigned 8-bit ASIC state 0</description></item>
/// <item><term>14 – iiii</term><description>signed 16-bit Water impedance measurement</description></item>
/// <item><term>15 – rrrr</term><description>signed 16-bit Electrode delta (mV)</description></item>
/// <item><term>16 – pp</term><description>unsigned 8-bit Spike detection diagnostic</description></item>
/// <item><term>17 – ll</term><description>unsigned 8-bit Pipe status</description></item>
/// <item><term>18 – dddddddd</term><description>unsigned 32-bit LCD volume</description></item>
/// <item><term>19 – oo</term><description>unsigned 8-bit ASIC state 1</description></item>
/// <item><term>20 – ss</term><description>unsigned 8-bit Checksum</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState6Data : DiagnosticLedData
{
public ushort FieldCalibration { get; }
public uint AsicTimestamp { get; }
public byte FieldDriveTimeUs { get; }
public int MeanFlowRate { get; }
public ushort Field1Measurement { get; }
public ushort Field2Measurement { get; }
public ushort IntegratorCalibrationPositive { get; }
public ushort IntegratorCalibrationNegative { get; }
public byte AsicState0 { get; }
public short WaterImpedance { get; }
public short ElectrodeDeltaMv { get; }
public byte SpikeDetection { get; }
public byte PipeStatus { get; }
public uint LcdVolume { get; }
public byte AsicState1 { get; }
public DiagnosticLedState6Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (0–4) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #6 specific ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestamp = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
MeanFlowRate = unchecked((int)DiagnosticHex.ParseUInt32(fields[8]));
Field1Measurement = DiagnosticHex.ParseUInt16(fields[9]);
Field2Measurement = DiagnosticHex.ParseUInt16(fields[10]);
IntegratorCalibrationPositive = DiagnosticHex.ParseUInt16(fields[11]);
IntegratorCalibrationNegative = DiagnosticHex.ParseUInt16(fields[12]);
AsicState0 = DiagnosticHex.ParseByte(fields[13]);
WaterImpedance = DiagnosticHex.ParseInt16(fields[14]);
ElectrodeDeltaMv = DiagnosticHex.ParseInt16(fields[15]);
SpikeDetection = DiagnosticHex.ParseByte(fields[16]);
PipeStatus = DiagnosticHex.ParseByte(fields[17]);
LcdVolume = DiagnosticHex.ParseUInt32(fields[18]);
AsicState1 = DiagnosticHex.ParseByte(fields[19]);
}
/// <summary>
/// Pipe status interpreted as <see cref="PipeStatus"/>.
/// If the value is outside the defined range, returns null.
/// </summary>
public PipeStatus PipeStatusEnumValue
{
get
{
if (!Enum.IsDefined(typeof(PipeStatus), PipeStatus))
throw new InvalidOperationException(
"Unknown pipe status value: 0x" + PipeStatus.ToString("X2"));
return (PipeStatus)PipeStatus;
}
}
/// <summary>
/// Spike Detection interpreted as <see cref="SpikeDetectionStatus"/>.
/// If the value is outside the defined range, returns null.
/// </summary>
public SpikeDetectionStatus SpikeDetectionEnumValue
{
get
{
if (!Enum.IsDefined(typeof(SpikeDetectionStatus), SpikeDetection))
throw new InvalidOperationException(
"Unknown Spike Detection value: 0x" + SpikeDetection.ToString("X2"));
return (SpikeDetectionStatus)SpikeDetection;
}
}
public override string ToString()
{
return $"DiagnosticLedState6Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}, MeanFlowRate={MeanFlowRate}, Field1Measurement={Field1Measurement}, Field2Measurement={Field2Measurement}, IntegratorCalibrationPositive={IntegratorCalibrationPositive}, IntegratorCalibrationNegative={IntegratorCalibrationNegative}, AsicState0={AsicState0}, WaterImpedance={WaterImpedance}, SpikeDetection={SpikeDetection}, PipeStatus={PipeStatus}, LcdVolume={LcdVolume}, AsicState1={AsicState1}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc tttt bbbbbbbb mmmmmmmm ff iiii rrrr pp ll dddddddd oo ss
/// Chars total = 90
/// Tabs = 20
/// CRLF = 2
/// Total bytes = 112
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 112;
}
}
}
@@ -0,0 +1,155 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #7 data frame.
/// <para>
/// Frame format: TAB-separated ASCII HEX fields, CRLF terminated.
/// This state extends State #6 with additional ADC and learning diagnostics.
/// </para>
/// <list type="table">
/// <listheader>
/// <term># / Field</term>
/// <description>Description</description>
/// </listheader>
/// <item><term>0 – xxxxxx</term><description>signed 24-bit ADC value</description></item>
/// <item><term>1 – aaaa</term><description>unsigned 16-bit Field strength (internal units)</description></item>
/// <item><term>2 – yyyy</term><description>signed 16-bit Raw flow rate (1/4 ml per bit)</description></item>
/// <item><term>3 – vvvvvv</term><description>unsigned 24-bit Raw volume accumulation (1/4 ml per bit)</description></item>
/// <item><term>4 – cccc</term><description>unsigned 16-bit Millivolts delta on field drive capacitor</description></item>
/// <item><term>5 – tttt</term><description>unsigned 16-bit Field calibration value</description></item>
/// <item><term>6 – bbbbbbbb</term><description>unsigned 32-bit ASIC timestamp (8192 ticks/sec)</description></item>
/// <item><term>7 – ff</term><description>unsigned 8-bit Field drive time (µs)</description></item>
/// <item><term>8 – mmmmmmmm</term><description>signed 32-bit Mean flow rate</description></item>
/// <item><term>9 – gggg</term><description>unsigned 16-bit Field 1 measurement</description></item>
/// <item><term>10 – hhhh</term><description>unsigned 16-bit Field 2 measurement</description></item>
/// <item><term>11 – cccc</term><description>unsigned 16-bit Integrator calibration positive</description></item>
/// <item><term>12 – nnnn</term><description>unsigned 16-bit Integrator calibration negative</description></item>
/// <item><term>13 – qq</term><description>unsigned 8-bit ASIC state 0</description></item>
/// <item><term>14 – iiii</term><description>signed 16-bit Water impedance measurement</description></item>
/// <item><term>15 – rrrr</term><description>signed 16-bit Electrode delta (mV)</description></item>
/// <item><term>16 – pp</term><description>unsigned 8-bit Spike detection diagnostic</description></item>
/// <item><term>17 – ll</term><description>unsigned 8-bit Pipe status</description></item>
/// <item><term>18 – dddddddd</term><description>unsigned 32-bit LCD volume</description></item>
/// <item><term>19 – oo</term><description>unsigned 8-bit ASIC state 1</description></item>
/// <item><term>20 – xxxxxx</term><description>signed 24-bit Raw ADC value (before offset correction)</description></item>
/// <item><term>21 – yyyyyy</term><description>signed 24-bit Detrended ADC value</description></item>
/// <item><term>22 – iiii</term><description>signed 16-bit Imaginary water impedance</description></item>
/// <item><term>23 – nnnn</term><description>unsigned 16-bit Electrode voltage noise level</description></item>
/// <item><term>24 – aa</term><description>unsigned 8-bit ADC offset learning status</description></item>
/// <item><term>25 – ss</term><description>unsigned 8-bit Checksum</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState7Data : DiagnosticLedData
{
// ----- State #6 fields -----
public ushort FieldCalibration { get; }
public uint AsicTimestamp { get; }
public byte FieldDriveTimeUs { get; }
public int MeanFlowRate { get; }
public ushort Field1Measurement { get; }
public ushort Field2Measurement { get; }
public ushort IntegratorCalibrationPositive { get; }
public ushort IntegratorCalibrationNegative { get; }
public byte AsicState0 { get; }
public short WaterImpedance { get; }
public short ElectrodeDeltaMv { get; }
public byte SpikeDetection { get; }
public byte PipeStatus { get; }
public uint LcdVolume { get; }
public byte AsicState1 { get; }
// ----- State #7 extensions -----
/// <summary>Raw ADC value before offset correction (signed 24-bit).</summary>
public int RawAdcBeforeOffset { get; }
/// <summary>Detrended ADC value (signed 24-bit).</summary>
public int DetrendedAdc { get; }
/// <summary>Imaginary water impedance (signed 16-bit).</summary>
public short ImaginaryWaterImpedance { get; }
/// <summary>Electrode voltage noise level (unsigned 16-bit).</summary>
public ushort ElectrodeVoltageNoise { get; }
/// <summary>
/// ADC offset learning status bitfield.
/// Bit 0: currently learning
/// Bit 1: completed first learning cycle
/// Other bits reserved.
/// </summary>
public byte AdcOffsetLearningStatus { get; }
public DiagnosticLedState7Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (0–4) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #6 fields ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestamp = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
MeanFlowRate = unchecked((int)DiagnosticHex.ParseUInt32(fields[8]));
Field1Measurement = DiagnosticHex.ParseUInt16(fields[9]);
Field2Measurement = DiagnosticHex.ParseUInt16(fields[10]);
IntegratorCalibrationPositive = DiagnosticHex.ParseUInt16(fields[11]);
IntegratorCalibrationNegative = DiagnosticHex.ParseUInt16(fields[12]);
AsicState0 = DiagnosticHex.ParseByte(fields[13]);
WaterImpedance = DiagnosticHex.ParseInt16(fields[14]);
ElectrodeDeltaMv = DiagnosticHex.ParseInt16(fields[15]);
SpikeDetection = DiagnosticHex.ParseByte(fields[16]);
PipeStatus = DiagnosticHex.ParseByte(fields[17]);
LcdVolume = DiagnosticHex.ParseUInt32(fields[18]);
AsicState1 = DiagnosticHex.ParseByte(fields[19]);
// ---- State #7 extensions ----
RawAdcBeforeOffset = DiagnosticHex.ParseInt24(fields[20]);
DetrendedAdc = DiagnosticHex.ParseInt24(fields[21]);
ImaginaryWaterImpedance = DiagnosticHex.ParseInt16(fields[22]);
ElectrodeVoltageNoise = DiagnosticHex.ParseUInt16(fields[23]);
AdcOffsetLearningStatus = DiagnosticHex.ParseByte(fields[24]);
}
public override string ToString()
{
return $"DiagnosticLedState7Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}, MeanFlowRate={MeanFlowRate}, Field1Measurement={Field1Measurement}, Field2Measurement={Field2Measurement}, IntegratorCalibrationPositive={IntegratorCalibrationPositive}, IntegratorCalibrationNegative={IntegratorCalibrationNegative}, AsicState0={AsicState0}, WaterImpedance={WaterImpedance}, ElectrodeDeltaMv={ElectrodeDeltaMv}, SpikeDetection={SpikeDetection}, PipeStatus={PipeStatus}, LcdVolume={LcdVolume}, AsicState1={AsicState1}, RawAdcBeforeOffset={RawAdcBeforeOffset}, DetrendedAdc={DetrendedAdc}, ImaginaryWaterImpedance={ImaginaryWaterImpedance}, ElectrodeVoltageNoise={ElectrodeVoltageNoise}, AdcOffsetLearningStatus={AdcOffsetLearningStatus}";
}
/// <summary>
/// Format:
/// Chars total = 112
/// Tabs = 25
/// CRLF = 2
/// Total bytes = 139
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 139;
}
}
}
@@ -0,0 +1,11 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
public enum PipeStatus : byte
{
MetroLowFlowCut = 0,
MetroFlowReverse = 1,
MetroFlowForward = 2,
MetroEmptyPipe = 3
}
}
@@ -0,0 +1,11 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
public enum SpikeDetectionStatus : byte
{
NoSpike = 0,
AdcSpike = 1,
SpikeHoldOff = 2,
SpikeHighFlow = 5
}
}
@@ -0,0 +1,13 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils
{
internal static class DiagnosticChecksum
{
public static byte Compute(string lineWithoutChecksum)
{
byte sum = 0;
foreach (char c in lineWithoutChecksum)
sum += (byte)c;
return sum;
}
}
}
@@ -0,0 +1,40 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils
{
internal static class DiagnosticHex
{
public static int ParseInt24(string hex)
{
int value = Convert.ToInt32(hex, 16);
if ((value & 0x800000) != 0)
value |= unchecked((int)0xFF000000); // sign extend
return value;
}
public static uint ParseUInt24(string hex)
{
return Convert.ToUInt32(hex, 16);
}
public static short ParseInt16(string hex)
{
return unchecked((short)Convert.ToUInt16(hex, 16));
}
public static ushort ParseUInt16(string hex)
{
return Convert.ToUInt16(hex, 16);
}
public static uint ParseUInt32(string hex)
{
return Convert.ToUInt32(hex, 16);
}
public static byte ParseByte(string hex)
{
return Convert.ToByte(hex, 16);
}
}
}
@@ -0,0 +1,49 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils
{
public class DiagnostigLedDataByUnit
{
private readonly Common.Unit _unitFlow;
private readonly Common.Unit _unitVolume;
private readonly DiagnosticLedState4Data _data;
public DiagnostigLedDataByUnit(Common.Unit unitFlow, Common.Unit unitVolume, DiagnosticLedState4Data data)
{
this._unitFlow = unitFlow;
this._unitVolume = unitVolume;
this._data = data;
}
public Common.Unit Unit => _unitVolume;
public DiagnosticLedState4Data Data => _data;
public double RawFlow {
get { return UnitVolume(_unitFlow, _data.RawFlow); }
}
public double RawVolume
{
get { return Common.Units.ConvertFrom(_unitVolume, _data.RawVolume); }
}
public double AsicTimestamp
{
get { return _data.AsicTimestamp; }
}
public static double UnitVolume(Common.Unit unit, double volume)
{
return Common.Units.ConvertFrom(unit, volume); /// 1 liter
}
public static uint DeltaTicks(uint oldTicks, uint newTicks)
{
return newTicks >= oldTicks
? newTicks - oldTicks
: uint.MaxValue - oldTicks + newTicks + 1;
}
}
}
@@ -0,0 +1,175 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public static class HexFormatter
{
/// <summary>
/// Byte to hex string.
/// Formats a single byte as 0xNN.
/// Example: 0x0D
/// </summary>
public static string ToHex(byte value)
{
return "0x" + value.ToString("X2");
}
/// <summary>
/// int to byte - securely
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static byte ToHexByte(int value)
{
if (value < 0 || value > 255)
throw new ArgumentOutOfRangeException(nameof(value),
"Value must be between 0 and 255.");
return (byte)value;
}
/// <summary>
/// Formats a byte array as 0xNN 0xNN ...
/// </summary>
public static string ToHex(byte[] data)
{
if (data == null || data.Length == 0)
return "<empty>";
var sb = new System.Text.StringBuilder();
for (int i = 0; i < data.Length; i++)
{
if (i > 0)
sb.Append(' ');
sb.Append("0x");
sb.Append(data[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Formats a byte array exactly as shown in serial terminals.
/// Example: "0D 04 08 01 00 1A"
/// </summary>
public static string ToSerialHex(byte[] data)
{
if (data == null || data.Length == 0)
return string.Empty;
var sb = new System.Text.StringBuilder();
for (int i = 0; i < data.Length; i++)
{
if (i > 0)
sb.Append(' ');
sb.Append(data[i].ToString("X2"));
}
return sb.ToString();
}
public static string ToHexWithAscii(byte value)
{
char c = (value >= 32 && value <= 126) ? (char)value : '.';
return $"0x{value:X2} ('{c}')";
}
public static string ToSerialHexWithAscii(byte[] data)
{
if (data == null || data.Length == 0)
return string.Empty;
var hex = new StringBuilder(data.Length * 3);
var ascii = new StringBuilder(data.Length);
foreach (byte b in data)
{
hex.Append(b.ToString("X2")).Append(' ');
// Printable ASCII range
if (b >= 32 && b <= 126)
{
ascii.Append((char)b);
}
// Binary numbers 0–9 -> show digit
else if (b <= 9)
{
ascii.Append((char)('0' + b));
}
else
{
ascii.Append('.');
}
}
// remove last trailing space in hex
if (hex.Length > 0)
hex.Length--;
return $"{hex} | {ascii}";
}
public static string ToHex(int value)
{
return $"0x{(byte)value:X2}";
}
public static byte[] IntToBytesBE(int value, int byteCount)
{
var result = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
result[byteCount - 1 - i] = (byte)(value >> (8 * i));
return result;
}
public static byte[] IntToBytesLE(int value, int byteCount)
{
var result = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
result[i] = (byte)(value >> (8 * i));
return result;
}
public static byte[] AsciiToBytes(string text)
{
return string.IsNullOrEmpty(text)
? Array.Empty<byte>()
: System.Text.Encoding.ASCII.GetBytes(text);
}
/// <summary>
/// Converts a hex string to a byte array.
/// Like: string hex = "3F 76 65 72 73 3A 20 48 61 72 72 79 20 54 3A 42 38 30 30 2C 20";
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static byte[] HexStringToByteArray(string hex)
{
if (hex == null)
throw new ArgumentNullException(nameof(hex));
return hex
.Split(new[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(b => byte.Parse(b, NumberStyles.HexNumber, CultureInfo.InvariantCulture))
.ToArray();
}
}
}
@@ -0,0 +1,21 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public class IpelHatCommandDecoder
{
public static string DescribeCommand(byte command)
{
return "";
}
public static string DescribeDirection(byte direction)
{
if (direction == IperlHatProtocol.IperlHatProtocolConstants.Write)
return "(WRITE - OUTGOING)";
if (direction == IperlHatProtocol.IperlHatProtocolConstants.Read)
return "(READ - INCOMING)";
return "INVALID CONTROL BITS (unsupported pattern)";
}
}
}
@@ -0,0 +1,85 @@
using System;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public static class IperlHatLogger
{
public static string DescribeTx(byte[] frame)
{
if (frame == null || frame.Length < 5)
return "Invalid frame";
if (frame[2] == IperlHatProtocol.IperlHatProtocolConstants.Question)
{
return
"TX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" DIRECTION : {HexFormatter.ToHex(frame[1])} ({IpelHatCommandDecoder.DescribeDirection(frame[1])})\n" +
$" COMMAND : {HexFormatter.ToHexWithAscii(frame[2])}\n" +
$" INFO : {HexFormatter.ToSerialHexWithAscii(GetInformatioQuestion(frame))}\n" +
$" END : {HexFormatter.ToHex(frame[frame.Length - 1])}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
else
{
return
"TX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" DIRECTION : {HexFormatter.ToHex(frame[1])} ({HexFormatter.ToHexWithAscii(frame[1])}) {IpelHatCommandDecoder.DescribeDirection(frame[1])}\n" +
$" LEN : {HexFormatter.ToHex(frame[2])} - {(int)frame[2]}\n" +
$" COMMAND : {HexFormatter.ToHexWithAscii(frame[3])}\n" +
$" INFO : {HexFormatter.ToSerialHexWithAscii(GetInformation(frame))}\n" +
$" END : {HexFormatter.ToHex(frame[frame.Length - 1])}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
}
//payload
private static byte[] GetInformation(byte[] frame)
{
int infoLength = frame.Length - 5; // START + DIRECTION + LEN + COMMAND + END
if (infoLength <= 0)
return Array.Empty<byte>();
var info = new byte[infoLength];
Buffer.BlockCopy(frame, 4, info, 0, infoLength);
return info;
}
//payload for question
private static byte[] GetInformatioQuestion(byte[] frame)
{
int infoLength = frame.Length - 4; // START + DIRECTION + COMMAND + END
if (infoLength <= 0)
return Array.Empty<byte>();
var info = new byte[infoLength];
Buffer.BlockCopy(frame, 3, info, 0, infoLength);
return info;
}
public static string DescribeRx(byte[] frame, TouchReadResponse response)
{
return
"RX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" LEN : {HexFormatter.ToHex(frame[1])} ({frame[1]})\n" +
$" CONTROL : {HexFormatter.ToHex(response.Control)}\n" +
$" STATUS : {HexFormatter.ToHex(response.Status)} ({DescribeStatus(response.Status)})\n" +
$" PAYLOAD : {HexFormatter.ToHex(response.Payload)}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
private static string DescribeStatus(byte status)
{
switch (status)
{
case 0x01: return "Command complete, no errors";
case 0x02: return "Unable to execute";
case 0x04: return "Unsupported control bits";
default: return "Unknown status";
}
}
}
}
@@ -0,0 +1,16 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public static class TouchReadControlDecoder
{
public static string Describe(byte control)
{
if (control == 0x00)
return "RF=0 (No response expected)";
if (control == 0x08)
return "RF=1 (Response expected)";
return "INVALID CONTROL BITS (unsupported pattern)";
}
}
}
@@ -0,0 +1,57 @@
using System;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public static class TouchReadLogger
{
public static string DescribeTx(byte[] frame)
{
if (frame == null || frame.Length < 6)
return "Invalid frame";
return
"TX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" LEN : {HexFormatter.ToHex(frame[1])} ({frame[1]})\n" +
$" CONTROL : {HexFormatter.ToHex(frame[2])} - {TouchReadControlDecoder.Describe(frame[2])}\n" +
$" INFO : {HexFormatter.ToHex(GetInformation(frame))}\n" +
$" CHECKSUM: {HexFormatter.ToHex(frame[frame.Length - 2])} {HexFormatter.ToHex(frame[frame.Length - 1])}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
private static byte[] GetInformation(byte[] frame)
{
int infoLength = frame.Length - 5; // CTRL + INFO + CHK(2)
if (infoLength <= 0)
return Array.Empty<byte>();
var info = new byte[infoLength];
Buffer.BlockCopy(frame, 3, info, 0, infoLength);
return info;
}
public static string DescribeRx(byte[] frame, TouchReadResponse response)
{
return
"RX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" LEN : {HexFormatter.ToHex(frame[1])} ({frame[1]})\n" +
$" CONTROL : {HexFormatter.ToHex(response.Control)}\n" +
$" STATUS : {HexFormatter.ToHex(response.Status)} ({DescribeStatus(response.Status)})\n" +
$" PAYLOAD : {HexFormatter.ToHex(response.Payload)}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
private static string DescribeStatus(byte status)
{
switch (status)
{
case 0x01: return "Command complete, no errors";
case 0x02: return "Unable to execute";
case 0x04: return "Unsupported control bits";
default: return "Unknown status";
}
}
}
}
@@ -0,0 +1,7 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led
{
public interface ITouchReadLedParser
{
TouchReadLedData Parse(TouchReadLedMessage message);
}
}
@@ -0,0 +1,17 @@
using System.Globalization;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led
{
public class ShortVariableLedParser : ITouchReadLedParser
{
public TouchReadLedData Parse(TouchReadLedMessage msg)
{
return new TouchReadLedData(msg.Raw)
{
MeterId = msg.Fields[0],
Reading = decimal.Parse(msg.Fields[1],
CultureInfo.InvariantCulture)
};
}
}
}
@@ -0,0 +1,77 @@
using System;
using System.Globalization;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led
{
/// <summary>
/// Parsed data from a unidirectional TouchRead LED message.
/// The exact populated fields depend on the configured reading mode.
/// </summary>
public sealed class TouchReadLedData
{
/// <summary>
/// Raw LED message including delimiters.
/// Example: ";12345678,00012345.67,m3;"
/// </summary>
public string Raw { get; }
/// <summary>
/// Meter factory ID or serial number (if present).
/// </summary>
public string MeterId { get; set; }
/// <summary>
/// Customer programmable ID (if present).
/// </summary>
public string CustomerId { get; set; }
/// <summary>
/// Parsed meter reading value.
/// </summary>
public decimal? Reading { get; set; }
/// <summary>
/// Engineering units (e.g. "m3", "ft3", "gal").
/// </summary>
public string Units { get; set; }
/// <summary>
/// Optional alarm/status field (bitfield or text).
/// </summary>
public string AlarmStatus { get; set; }
/// <summary>
/// Timestamp when the LED data was received.
/// </summary>
public DateTime Timestamp { get; }
public TouchReadLedData(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
throw new ArgumentException("Raw LED data must not be null or empty.", nameof(raw));
Raw = raw;
Timestamp = DateTime.UtcNow;
}
/// <summary>
/// Helper to safely parse a decimal value using invariant culture.
/// </summary>
public static decimal? ParseDecimal(string value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
if (decimal.TryParse(
value,
NumberStyles.Number,
CultureInfo.InvariantCulture,
out var result))
{
return result;
}
return null;
}
}
}
@@ -0,0 +1,21 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led
{
public class TouchReadLedMessage
{
public string Raw { get; }
public string[] Fields { get; }
public TouchReadLedMessage(string raw)
{
Raw = raw ?? throw new ArgumentNullException(nameof(raw));
if (!raw.StartsWith(";") || !raw.EndsWith(";"))
throw new FormatException("Invalid LED message framing");
string content = raw.Substring(1, raw.Length - 2);
Fields = content.Split(',');
}
}
}
@@ -0,0 +1,140 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons
{
/// <summary>
/// Common iPERL TouchRead bidirectional commands.
/// These commands consist of a single-byte command code
/// placed in the Information field.
/// </summary>
public enum ProtocolCommand : byte
{
/// <summary>
/// Simple (legacy) commands (e.g. View Factory ID = 0x01)
/// </summary>
Simple = 0x00,
/// <summary>
/// View Factory ID (ex-works serial number).
/// Returns a 0–12 byte ASCII string terminated by NULL.
/// Response only if RF flag is set.
/// </summary>
ViewFactoryId = 0x01,
/// <summary>
/// Set Factory ID (0–12 ASCII characters, NULL terminated).
/// Protected by meter seal.
/// </summary>
SetFactoryId = 0x02,
/// <summary>
/// View Customer Programmable ID (1–12 ASCII characters).
/// </summary>
ViewProgrammableId = 0x03,
/// <summary>
/// Set Customer Programmable ID (1–12 ASCII characters, NULL terminated).
/// </summary>
SetProgrammableId = 0x04,
/// <summary>
/// View Version and Type string.
/// Example: B1.22,SMW002,B0.02
/// </summary>
ViewVersionAndType = 0x05,
/// <summary>
/// View Customer Programmable Text (0–20 ASCII characters).
/// </summary>
ViewProgrammableText = 0x07,
/// <summary>
/// Set Customer Programmable Text (0–20 ASCII characters, NULL terminated).
/// </summary>
SetProgrammableText = 0x08,
/// <summary>
/// View number of reading digits and decimal shift.
/// Payload: uint8 digits, int8 decimal shift.
/// </summary>
ViewNumberOfReadingDigits = 0x09,
/// <summary>
/// Set number of reading digits and decimal shift.
/// Digits range: 4–8, Decimal shift: -5..0.
/// </summary>
SetNumberOfReadingDigits = 0x0A,
/// <summary>
/// View reading units.
/// Returns numeric unit code (m3, ft3, gallons).
/// </summary>
ViewReadingUnits = 0x0B,
/// <summary>
/// Set reading units.
/// Valid values: 0x00=m3, 0x01=ft3, 0x04=US gallons, 0xFF=off.
/// </summary>
SetReadingUnits = 0x0C,
/// <summary>
/// View reading multiplier (resolution).
/// Range: -7..+5 or 0x80 (disabled).
/// </summary>
ViewReadingMultiplier = 0x0F,
/// <summary>
/// Set reading multiplier (resolution).
/// </summary>
SetReadingMultiplier = 0x10,
/// <summary>
/// View preset total (volume accumulator).
/// Returns 8 ASCII digits + NULL.
/// </summary>
ViewPresetTotal = 0x13,
/// <summary>
/// Set preset total (0–8 ASCII digits, NULL terminated).
/// Protected by meter seal.
/// </summary>
SetPresetTotal = 0x14,
/// <summary>
/// View reading mode (unidirectional TouchRead format).
/// </summary>
ViewReadingMode = 0x15,
/// <summary>
/// Set reading mode.
/// Values: Short Variable, Extended, Fixed, Smart Meter.
/// </summary>
SetReadingMode = 0x16,
/// <summary>
/// View build information (firmware details).
/// </summary>
ViewBuildInformation = 0x17,
/// <summary>
/// View meter state.
/// </summary>
ViewState = 0x19,
/// <summary>
/// Set meter state (operating mode).
/// Protected by meter seal.
/// </summary>
SetState = 0x1A,
/// <summary>
/// Device-specific command prefix.
/// Must be followed by a device sub-command byte.
/// </summary>
DeviceSpecific = 0xFD,
/// <summary>
/// Question - specific switch to add additional payload request like "vers"
/// Mandatory add payload
/// </summary>
Question = 0x3F,
}
}
@@ -0,0 +1,203 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons
{
/// <summary>
/// Device-specific TouchRead sub-commands.
/// These sub-commands are used together with the
/// <see cref="TouchReadCommand.DeviceSpecific"/> (0xFD) command.
/// </summary>
public enum ProtocolDeviceSubCommand : byte
{
// ==========================================================
// System / Time
// ==========================================================
/// <summary>
/// View system time.
/// Returns uint32 seconds since 2000-01-01 00:00:00.
/// </summary>
ViewSystemTime = 0x10,
/// <summary>
/// Set system time.
/// Payload: uint32 seconds since 2000-01-01.
/// If set to zero, the meter resets and erases data.
/// Protected by meter seal.
/// </summary>
SetSystemTime = 0x11,
// ==========================================================
// Alarm Mask / Alarm Configuration
// ==========================================================
/// <summary>View alarm mask (lower 16 bits).</summary>
ViewAlarmMask = 0x31,
/// <summary>Set alarm mask (lower 16 bits).</summary>
SetAlarmMask = 0x32,
/// <summary>View alarm persistence period (days).</summary>
ViewPersistence = 0x33,
/// <summary>Set alarm persistence period (days).</summary>
SetPersistence = 0x34,
/// <summary>View leak duration (hours).</summary>
ViewLeakDuration = 0x35,
/// <summary>Set leak duration (hours).</summary>
SetLeakDuration = 0x36,
/// <summary>View current alarm states.</summary>
ViewAlarms = 0x37,
/// <summary>Set alarm states (protected by meter seal).</summary>
SetAlarms = 0x38,
// ==========================================================
// Manufacture / Counters
// ==========================================================
/// <summary>View manufacture date.</summary>
ViewManufactureDate = 0x39,
/// <summary>Set manufacture date (protected by meter seal).</summary>
SetManufactureDate = 0x3A,
/// <summary>View seconds idle.</summary>
ViewSecondsIdle = 0x3B,
/// <summary>View seconds active.</summary>
ViewSecondsActive = 0x3D,
/// <summary>View seconds used.</summary>
ViewSecondsUsed = 0x3F,
// ==========================================================
// Snapshot / Datalog
// ==========================================================
/// <summary>View snapshot data.</summary>
ViewSnapshotData = 0x41,
/// <summary>View datalog duration.</summary>
ViewDatalogDuration = 0x43,
/// <summary>Set datalog duration.</summary>
SetDatalogDuration = 0x44,
/// <summary>Read datalog.</summary>
ReadDatalog = 0x45,
/// <summary>Clear datalog.</summary>
ClearDatalog = 0x46,
// ==========================================================
// History
// ==========================================================
/// <summary>View history mask.</summary>
ViewHistoryMask = 0x47,
/// <summary>Set history mask.</summary>
SetHistoryMask = 0x48,
/// <summary>Read history.</summary>
ReadHistory = 0x49,
/// <summary>Clear history.</summary>
ClearHistory = 0x4A,
// ==========================================================
// Diagnostics / Status
// ==========================================================
/// <summary>View diagnostics.</summary>
ViewDiagnostics = 0x4B,
/// <summary>Reset diagnostics.</summary>
ResetDiagnostics = 0x4C,
/// <summary>View status file.</summary>
ViewStatusFile = 0x4F,
/// <summary>Set status file (protected by meter seal).</summary>
SetStatusFile = 0x50,
// ==========================================================
// Calibration / Configuration
// ==========================================================
/// <summary>View calibration structure.</summary>
ViewCalibrationStructure = 0x51,
/// <summary>Set calibration structure (protected by meter seal).</summary>
SetCalibrationStructure = 0x52,
/// <summary>View calibration.</summary>
ViewCalibration = 0x53,
/// <summary>Set calibration (protected by meter seal).</summary>
SetCalibration = 0x54,
/// <summary>View reboot count.</summary>
ViewRebootCount = 0x55,
/// <summary>Set reboot count (protected by meter seal).</summary>
SetRebootCount = 0x56,
/// <summary>View temperature.</summary>
ViewTemperature = 0x57,
/// <summary>Set temperature (protected by meter seal).</summary>
SetTemperature = 0x58,
// ==========================================================
// Diagnostic LED / Hardware
// ==========================================================
/// <summary>
/// Set diagnostic LED state.
/// Enables or disables high-speed LED serial output.
/// <para>
/// See <see cref="DiagnosticLedState"/>
/// diagnostic LED output modes.
/// </para>
/// </summary>
SetDiagnosticLEDState = 0x60,
// ==========================================================
// Build / Firmware Info
// ==========================================================
/// <summary>View iPERL build information.</summary>
ViewIPerlBuild = 0x65,
/// <summary>Set iPERL build (protected by meter seal).</summary>
SetIPerlBuild = 0x66,
// ==========================================================
// Bootloader (DANGEROUS – use with care)
// ==========================================================
/// <summary>Enter bootloader mode.</summary>
EnterBootloader = 0x81,
/// <summary>Read FLASH memory.</summary>
ReadFlash = 0x82,
/// <summary>Erase all FLASH memory.</summary>
EraseAll = 0x83,
/// <summary>Erase FLASH segment.</summary>
EraseSegment = 0x84,
/// <summary>Update firmware code.</summary>
UpdateCode = 0x85,
/// <summary>Exit bootloader mode.</summary>
ExitBootloader = 0x86
}
}
@@ -0,0 +1,13 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons
{
public enum ProtocolStatuses : byte
{
Idle = 0x01,
Active = 0x02,
EndOfLife = 0x03,
MeterTest = 0x04,
MeterTestEMF = 0x05,
Unknown = 0x00
}
}
@@ -0,0 +1,27 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public sealed class TouchReadFrame
{
public byte Start { get; }
public byte Length { get; }
public byte Control { get; }
public byte[] Information { get; }
public ushort Checksum { get; }
public TouchReadFrame(
byte start,
byte length,
byte control,
byte[] information,
ushort checksum)
{
Start = start;
Length = length;
Control = control;
Information = information ?? Array.Empty<byte>();
Checksum = checksum;
}
}
}
@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public sealed class TouchReadFrameBuilder
{
private const byte START = 0x0D;
private byte _control;
private readonly List<byte> _information = new List<byte>();
public TouchReadFrameBuilder RequestResponse(bool enabled)
{
_control = enabled ? (byte)0x08 : (byte)0x00;
return this;
}
public TouchReadFrameBuilder AddCommand(ProtocolCommand command)
{
_information.Add((byte)command);
return this;
}
public TouchReadFrameBuilder AddSubCommand(ProtocolDeviceSubCommand subCommand)
{
if (_information.Count == 0 ||
_information[0] != (byte)ProtocolCommand.DeviceSpecific)
throw new InvalidOperationException(
"Sub-command is only valid for DeviceSpecific (0xFD) commands.");
_information.Add((byte)subCommand);
return this;
}
public TouchReadFrameBuilder AddDeviceCommand(
ProtocolDeviceSubCommand subCommand)
{
_information.Add((byte)ProtocolCommand.DeviceSpecific);
_information.Add((byte)subCommand);
return this;
}
public TouchReadFrameBuilder AddPayload(byte[] payload)
{
if (payload != null)
_information.AddRange(payload);
return this;
}
public TouchReadFrameBuilder AddDiagnosticLedState(DiagnosticLedState state)
{
_information.Add((byte)ProtocolCommand.DeviceSpecific);
_information.Add((byte)ProtocolDeviceSubCommand.SetDiagnosticLEDState);
_information.Add((byte)state);
return this;
}
public TouchReadFrameBuilder AddNullTerminatedAscii(string text)
{
if (!string.IsNullOrEmpty(text))
_information.AddRange(
System.Text.Encoding.ASCII.GetBytes(text));
_information.Add(0x00);
return this;
}
public TouchReadFrame BuildFrame()
{
if (_information.Count == 0)
throw new InvalidOperationException("No command specified.");
byte length = (byte)(1 + _information.Count + 2);
var raw = new List<byte>
{
START,
length,
_control
};
raw.AddRange(_information);
ushort checksum = CalculateChecksum(raw);
raw.Add((byte)(checksum >> 8));
raw.Add((byte)(checksum & 0xFF));
return new TouchReadFrame(
START,
length,
_control,
_information.ToArray(),
checksum);
}
public byte[] BuildBytes()
{
TouchReadFrame frame = BuildFrame();
var bytes = new List<byte>
{
frame.Start,
frame.Length,
frame.Control
};
bytes.AddRange(frame.Information);
bytes.Add((byte)(frame.Checksum >> 8));
bytes.Add((byte)(frame.Checksum & 0xFF));
return bytes.ToArray();
}
public static ushort CalculateChecksum(IEnumerable<byte> data)
{
ushort sum = 0;
foreach (var b in data)
sum += b;
return sum;
}
}
}
@@ -0,0 +1,63 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public sealed class TouchReadFrameParser
{
private const byte START = 0x0D;
public TouchReadResponse Parse(byte[] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (data.Length < 6)
throw new FormatException("Frame too short.");
if (data[0] != START)
throw new FormatException("Invalid START byte.");
byte length = data[1];
if (length + 2 != data.Length)
throw new FormatException("Length mismatch.");
ushort receivedChecksum =
(ushort)((data[data.Length - 2] << 8) |
data[data.Length - 1]);
ushort calculatedChecksum = CalculateChecksum(data, data.Length - 2);
if (receivedChecksum != calculatedChecksum)
throw new FormatException("Checksum error.");
byte control = data[2];
byte status = data[3];
byte[] payload = ExtractPayload(data);
return new TouchReadResponse(control, status, payload);
}
private static ushort CalculateChecksum(byte[] data, int count)
{
ushort sum = 0;
for (int i = 0; i < count; i++)
sum += data[i];
return sum;
}
private static byte[] ExtractPayload(byte[] data)
{
// payload exists only if frame longer than:
// START + LEN + CTRL + STATUS + CHK_HI + CHK_LO = 6 bytes
if (data.Length <= 6)
return Array.Empty<byte>();
int payloadLength = data.Length - 6;
byte[] payload = new byte[payloadLength];
Buffer.BlockCopy(data, 4, payload, 0, payloadLength);
return payload;
}
}
}
@@ -0,0 +1,10 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public static class TouchReadProtocol
{
public const byte START = 0x0D;
// Control bits (CNTRL1)
public const byte RESPONSE_FLAG = 0x08; // RF
}
}
@@ -0,0 +1,34 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public sealed class TouchReadResponse
{
public byte Control { get; }
public byte Status { get; }
public byte[] Payload { get; }
public bool IsOk => Status == 0x01;
public TouchReadResponse(byte control, byte status, byte[] payload)
{
Control = control;
Status = status;
Payload = payload ?? Array.Empty<byte>();
}
public string GetAsciiPayload()
{
if (Payload.Length == 0)
return null;
int length = Array.IndexOf(Payload, (byte)0x00);
if (length < 0)
length = Payload.Length;
return System.Text.Encoding.ASCII.GetString(Payload, 0, length);
}
}
}
@@ -0,0 +1,10 @@
using log4net;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication
{
public class OpthoHeadService
{
}
}
@@ -0,0 +1,369 @@
using System;
using System.IO.Ports;
using Common;
using log4net;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.Utils;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication
{
public class OptoHeadTest : IDisposable
{
//protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
private static readonly ILog log = LogManager.GetLogger(typeof(OptoHeadTest));
private IperlHead iperlHead;
private SerialDriver serialDriver;
public static SerialDriver BuildConnection(IperlHead iHead)
{
return new SerialDriverBuilder()
.WithPort($"COM{iHead.RfidComPortNr}")
.WithBaudRate(2400)
.WithDataBits(8)
.WithParity(Parity.None)
.WithStopBits(StopBits.One)
.WithTimeouts(4000, 2000)
.BuildAndConnect();
}
public OptoHeadTest(IperlHead iperlHead)
{
this.iperlHead = iperlHead;
}
public void CloseConnection()
{
if (serialDriver != null)
serialDriver.CloseConnection();
serialDriver = null;
}
public bool ReadSerialNr()
{
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
log.Debug("ReadSerialNr called for iHead: " + iperlHead.ToString() + " serialDriver: " + serialDriver);
RadioService headService = new RadioService(serialDriver);
string serialNo = headService.ReadRequest_PCB(ref iperlHead);
if (!string.IsNullOrEmpty(serialNo))
{
log.Info($"Success Serial No: {serialNo} on COM{iperlHead.RfidComPortNr} serialDriver: {serialDriver}");
return true;
}
}
}
catch (Exception ex)
{
log.Error($"ReadSerialNr(COM{iperlHead.RfidComPortNr}) - Exception:" + ex.Message);
}
return false;
}
public string ReadRequest_PCB()
{
if (iperlHead.DebugLevel == DebugMode.Simulate)
{
return "-OK Simulated response-";
}
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
RadioService headService = new RadioService(serialDriver);
string serialNo = headService.ReadRequest_PCB(ref iperlHead);
log.Info($"PCB Number: {serialNo} on COM{iperlHead.RfidComPortNr} serialDriver: {serialDriver}");
return serialNo;
}
}
catch (Exception ex)
{
log.Error("ReadRequest_PCB() - Exception:" + ex.StackTrace);
return (ex.Message.ToString());
}
return "";
}
/// <summary>
/// Set Test mode
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
public bool SetTestMode()
{
log.Debug("SetTestMode called for iHead: " + iperlHead.ToString());
bool activityModeActive = SetActivityMode_Active();
bool optActiveMode = SetOptTestMode();
log.Debug("SetTestMode result: optoMod-> " + optActiveMode + " meterModeActive ->" + activityModeActive);
return (optActiveMode && activityModeActive);
}
/// <summary>
/// Set Active mode
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
public bool SetActiveMode()
{
log.Debug("SetActiveMode called for iHead: " + iperlHead.ToString());
bool optActiveMode = SetOptActiveMode(iperlHead);
//bool activityModeIdle = SetActivityMode_Idle();
return optActiveMode;
}
/// <summary>
/// Set Idle mode - only
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
public bool SetIdleMode()
{
log.Debug("SetIdleMode called for iHead: " + iperlHead.ToString());
bool activityModeIdle = SetActivityMode_Idle();
return activityModeIdle;
}
/// <summary>
/// Set Test mode - string response
/// </summary>
/// <param name="iHead"></param>
/// <param name="isTestModeSuccessful"></param>
/// <returns></returns>
public string SetTestMode(ref bool isTestModeSuccessful)
{
if (iperlHead.DebugLevel == DebugMode.Simulate)
{
isTestModeSuccessful = true;
return "-OK Simulated response-";
}
try
{
bool testMode = SetTestMode();
isTestModeSuccessful = testMode;
return testMode ? "Set Test Mode - OK" : "Set Test Mode - FAILED";
}catch (Exception ex)
{
log.Error("SetTestMode() - Exception:" + ex.StackTrace);
return "Set Test Mode - Exception";
}
}
/// <summary>
/// Set Optical -> Test mode
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private bool SetOptTestMode()
{
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
RadioService headService = new RadioService(serialDriver);
bool optTestMode = headService.SetOptTestMode(iperlHead);
if (iperlHead.ConfigStruct != null)
iperlHead.ConfigStruct.OpthoStatusMode = optTestMode ? DiagnosticLedState.State4 : DiagnosticLedState.StatusUnknown;
return optTestMode;
}
}
catch (Exception ex)
{
log.Error("SetOptTestMode() - Exception:" + ex.StackTrace);
}
return false;
}
/// <summary>
/// Set Active mode - string response
/// </summary>
/// <param name="iHead"></param>
/// <param name="isTestModeSuccessful"></param>
/// <returns></returns>
public string SetActiveMode(ref bool isTestModeSuccessful)
{
if (iperlHead.DebugLevel == DebugMode.Simulate)
{
isTestModeSuccessful = true;
return "-OK Simulated response-";
}
try
{
bool activeMode = SetActiveMode();
isTestModeSuccessful = activeMode;
return activeMode ? "Set Active Mode - OK" : "Set Active Mode - FAILED";
}
catch (Exception ex)
{
log.Error("SetActiveMode() - Exception:" + ex.StackTrace);
return "Set Active Mode - Exception";
}
}
/// <summary>
/// Set Optical -> Active mode
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private bool SetOptActiveMode(IperlHead iHead)
{
try
{
if (iHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iHead);
RadioService headService = new RadioService(serialDriver);
return headService.SetOptActiveMode(iHead);
}
}
catch (Exception ex)
{
log.Error("SetOptActiveMode() - Exception:" + ex.StackTrace);
}
return false;
}
/// <summary>
/// Set activity mode to active
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private bool SetActivityMode_Active()
{
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
log.Debug("SetActivityMode_Active called for iHead: " + iperlHead.ToString() + " serialDriver: " + serialDriver);
RadioService headService = new RadioService(serialDriver);
return headService.SetActivityMode_Active(iperlHead);
}
}
catch (Exception ex)
{
log.Error("SetActivityMode_Active() - Exception:" + ex.StackTrace);
}
return false;
}
/// <summary>
/// Set activity mode to idle
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private bool SetActivityMode_Idle()
{
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
log.Debug("SetActivityMode_Idle called for iHead: " + iperlHead.ToString() + " serialDriver: " + serialDriver);
RadioService headService = new RadioService(serialDriver);
return headService.SetActivityMode_Idle(iperlHead);
}
}
catch (Exception ex)
{
log.Error("SetActivityMode_Idle() - Exception:" + ex.StackTrace);
}
return false;
}
public void Dispose()
{
CloseConnection();
}
/// <summary>
/// Read configuration from iHead
/// DiagnosticLedState is not readable, mus only be set!
/// </summary>
/// <param name="iHead"></param>
/// <param name="ledState"></param>
/// <returns></returns>
public bool ReadConfiguration(DiagnosticLedState ledState )
{
if (iperlHead.DebugLevel == DebugMode.Simulate)
{
return true;
}
try
{
if (iperlHead != null)
{
iperlHead.ConfigStruct = new ConfigStruct();
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
RadioService headService = new RadioService(serialDriver);
iperlHead.ConfigStruct.PCBNumberString = headService.ReadRequest_PCB(ref iperlHead);
iperlHead.ConfigStruct.StatusMode = headService.GetActivityStatusMode(iperlHead);
iperlHead.ConfigStruct.Unit = headService.GetUnit(iperlHead);
if (ledState != DiagnosticLedState.StatusUnknown) // do set
{
iperlHead.ConfigStruct.OpthoStatusMode = headService.SetOptoStatusMode(iperlHead, ledState);
}
else
{
iperlHead.ConfigStruct.OpthoStatusMode = DiagnosticLedState.StatusUnknown;
}
iperlHead.ConfigStruct.Version = headService.GetVersion(iperlHead);
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
}
}
@@ -0,0 +1,318 @@
using log4net;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
using TBF.Rig.TestMethods.iPerlCommunication.communication.Utils;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication
{
public class RadioService
{
private static readonly ILog log = LogManager.GetLogger(typeof(RadioService));
static string okResponse = "Command complete, no errors";
static string errorResponse = "Unable to execute";
private ISerialDriver serialDriver;
public RadioService(SerialDriver serialDriver)
{
this.serialDriver = serialDriver;
log.Debug("RadioService created with serialDriver= " + serialDriver + "");
}
public RadioService(ISerialDriver serialDriver)
{
this.serialDriver = serialDriver;
log.Debug("RadioService created with serialDriver= " + serialDriver + "");
}
public string ReadRequest_PCB(ref IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.ViewFactoryId)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return null;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
if (decoded.IsOk)
{
string asciiPayload = decoded.GetAsciiPayload();
if (iHead.ConfigStruct != null) // store mechanism
{
iHead.ConfigStruct.PCBNumberString = asciiPayload;
}
return asciiPayload;
}
return null;
}
public ProtocolStatuses GetActivityStatusMode(IperlHead iHead)
{
if (!serialDriver.IsOpen())
serialDriver.Open();
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.ViewState)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return ProtocolStatuses.Unknown;
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
if (!decoded.IsOk)
return ProtocolStatuses.Unknown;
ProtocolStatuses statusMode = decoded.GetResponse<ProtocolStatuses>(out bool isOK);
if (!isOK)
return ProtocolStatuses.Unknown; // wrong payload
return statusMode;
}
public DiagnosticLedState SetOptoStatusMode(IperlHead iHead, DiagnosticLedState opthoStatusMode)
{
if (!serialDriver.IsOpen())
serialDriver.Open();
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
.AddPayload(opthoStatusMode)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return DiagnosticLedState.StatusUnknown;
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("SetOptoStatusMode isOK: " + decoded.IsOk);
// if is response ok - it set it correctly
if (!decoded.IsOk)
return DiagnosticLedState.StatusUnknown;
return opthoStatusMode;
}
private static ushort SafeIntToUShort(int value)
{
if (value < ushort.MinValue || value > ushort.MaxValue)
return 0xFD; // your error code
return (ushort)value;
}
public string GetVersion(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
byte[] request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.Question)
.AddPayload(IperlHatProtocolConstants.Version)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return "";
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("GetVersion isOK: " + decoded.IsOk);
if (decoded.IsOk)
{
return decoded.GetAsciiPayload();
}
return "";
}
public bool SetActivityMode_Active(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
//Set LED to state 4
byte[] request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.SetState)
.AddSubCommand(ProtocolStatuses.Active) // Active
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 5000);
if (rawData == null)
return false;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("SetActivityMode_Active isOK: " + decoded.IsOk);
if (decoded.IsOk && iHead.ConfigStruct != null)
{
iHead.ConfigStruct.StatusMode = ProtocolStatuses.Active;
}
return decoded.IsOk;
}
public bool SetActivityMode_Idle(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
//Set Activity State Idle
byte[] request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.SetState)
.AddSubCommand(ProtocolStatuses.Idle)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 5000);
if (rawData == null)
return false;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("SetActivityMode_Idle isOK: " + decoded.IsOk);
if (decoded.IsOk && iHead.ConfigStruct != null)
{
iHead.ConfigStruct.StatusMode = ProtocolStatuses.Idle;
}
return decoded.IsOk;
}
public bool SetOptTestMode(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
//Set LED to state 4
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
.AddPayload(DiagnosticLedState.State4)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 5000);
if (rawData == null)
return false;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
bool isOk = decoded.IsOk;
log.Debug("SetOptTestMode isOK: " + isOk);
if (decoded.IsOk && iHead.ConfigStruct != null)
{
iHead.ConfigStruct.OpthoStatusMode = DiagnosticLedState.State4;
}
return isOk;
}
/// <summary>
/// stop data streaming by LED
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
public bool SetOptActiveMode(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
//Set LED to state 1
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
.AddPayload(DiagnosticLedState.StateOFF)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 5000);
if (rawData == null)
return false;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("SetOptActiveMode isOK: " + decoded.IsOk);
if (decoded.IsOk && iHead.ConfigStruct != null)
{
iHead.ConfigStruct.OpthoStatusMode = DiagnosticLedState.StateOFF;
}
return decoded.IsOk;
}
public string GetUnit(IperlHead iperlHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.ViewFactoryId)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return null;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
if (decoded.IsOk)
{
string asciiPayload = decoded.GetAsciiPayload();
if (iperlHead.ConfigStruct != null) // store mechanism
{
iperlHead.ConfigStruct.Unit = asciiPayload;
}
return asciiPayload;
}
return null;
}
}
}
@@ -0,0 +1,9 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.Utils
{
public interface ISerialDriver
{
bool IsOpen();
bool Open();
byte[] SendAndWait(byte[] request, int timeout);
}
}
@@ -0,0 +1,308 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Threading;
using FluentNHibernate.Conventions;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.Utils
{
public class SerialDriver : IDisposable, ISerialDriver
{
readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(SerialDriver));
public string ErrorMessage { get; private set; }
private List<byte> SerialPortReadBuffer = new List<byte>();
private SerialPort _serialPort;
private readonly List<byte> _binMessages = new List<byte>();
private bool _isReading;
// Stored configuration (used by Builder)
private readonly string _portName;
private readonly int _baudRate;
private readonly int _dataBits;
private readonly Parity _parity;
private readonly StopBits _stopBits;
private readonly int _readTimeout;
private readonly int _writeTimeout;
private readonly ManualResetEvent _responseReceived = new ManualResetEvent(false);
#region Constructors
// Default constructor (legacy support)
public SerialDriver()
{
_serialPort = new SerialPort();
}
// Builder constructor
internal SerialDriver(
string portName,
int baudRate,
int dataBits,
Parity parity,
StopBits stopBits,
int readTimeout,
int writeTimeout)
{
_portName = portName;
_baudRate = baudRate;
_dataBits = dataBits;
_parity = parity;
_stopBits = stopBits;
_readTimeout = readTimeout;
_writeTimeout = writeTimeout;
}
#endregion
#region Open / Close
// Builder-based open
public bool Open()
{
return OpenConnection(
_portName,
_baudRate,
_dataBits,
_parity,
_stopBits,
_readTimeout,
_writeTimeout
);
}
// Legacy API (unchanged)
public bool OpenConnection(
string comPort,
int baudrate,
int dataBits,
Parity parity,
StopBits stopbits,
int readTimeout = 1000,
int writeTimeout = 1000)
{
lock (this)
{
CloseConnection();
try
{
ErrorMessage = string.Empty;
_serialPort = new SerialPort(comPort, baudrate, parity, dataBits, stopbits)
{
ReadTimeout = readTimeout,
WriteTimeout = writeTimeout
};
_serialPort.DataReceived += DataReceivedHandler;
_serialPort.Open();
}
catch (Exception ex)
{
ErrorMessage = $"COM error: Open failed {comPort}. {ex.Message}";
return false;
}
if (!_serialPort.IsOpen)
{
ErrorMessage = $"COM error: Can't open {comPort}.";
return false;
}
log.Debug("SerialDriver opened successfully for port: " + comPort);
}
return true;
}
public void CloseConnection()
{
if (_serialPort != null)
{
_serialPort.DataReceived -= DataReceivedHandler;
if (_serialPort.IsOpen)
_serialPort.Close();
_serialPort.Dispose();
_serialPort = null;
}
}
public bool IsOpen() => _serialPort?.IsOpen == true;
#endregion
#region Send / Receive
public bool SendMessage(byte[] sendDataBytes, int length, int readTimeout = 1000, int writeTimeout = 1000)
{
if (!IsOpen()) return false;
if (sendDataBytes.Length == 0) return true;
try
{
PrepareReading();
_serialPort.WriteTimeout = writeTimeout;
_serialPort.ReadTimeout = readTimeout;
_serialPort.Write(sendDataBytes, 0, length);
_isReading = true;
var stopwatch = Stopwatch.StartNew();
while (_isReading)
{
if (stopwatch.ElapsedMilliseconds > readTimeout)
{
ErrorMessage = "COM error: Receive timeout";
return false;
}
}
}
catch (Exception ex)
{
ErrorMessage = $"COM error: Transmit failed {_serialPort.PortName}. {ex.Message}";
return false;
}
return true;
}
private void PrepareReading()
{
_serialPort.DiscardInBuffer();
_binMessages.Clear();
_responseReceived.Reset();
SerialPortReadBuffer.Clear();
_isReading = true;
}
public byte[] GetRawData()
{
return _binMessages.ToArray();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
lock (this)
{
if (_serialPort == null || !_serialPort.IsOpen) return;
try
{
//Thread.Sleep(5);
if (!SerialPortReadBuffer.IsEmpty())
{
SerialPortReadBuffer.Clear();
}
int iWordCounter = 0;
bool isStart = false;
bool isQuestion = false;
int iLength = 0;
while (true)//_serialPort.BytesToRead > 0
{
byte readByte = (byte)_serialPort.ReadByte();
//I have START
if (readByte == C4.IperlHatProtocol.IperlHatProtocolConstants.Start)
{
iWordCounter++;
isStart = true;
}
// I have QUESTION
if (readByte == C4.IperlHatProtocol.IperlHatProtocolConstants.Question)
{
iWordCounter++;
isQuestion = true;
}
//I count length from start
if (iWordCounter > 0)
iWordCounter++;
if (iWordCounter > 0)
{
//Store byte to data
SerialPortReadBuffer.Add(readByte);
}
// we have length
if (iLength == 0 && isStart && SerialPortReadBuffer.Count > 2 )
{
iLength = (int)SerialPortReadBuffer[2];
}
//If we have enough bytes
if (isStart && iLength > 0
&& (SerialPortReadBuffer.Count >= iLength ||
readByte == C4.IperlHatProtocol.IperlHatProtocolConstants.End
)
)
{
break;
}
//if we read END
if (isQuestion && readByte == C4.IperlHatProtocol.IperlHatProtocolConstants.End)
{
break;
}
}
if (SerialPortReadBuffer.Count > 0)
{
_binMessages.AddRange(SerialPortReadBuffer.ToArray());
_responseReceived.Set();
}
}
catch (TimeoutException te)
{
// Ignore shutdown race conditions
}
finally
{
_isReading = false;
}
}
}
public byte[] SendAndWait(byte[] data, int timeoutMs)
{
if (!IsOpen())
throw new InvalidOperationException("Serial port not open");
log.Debug("SendAndWait() - TX: " + HexFormatter.ToHex(data));
PrepareReading();
_serialPort.Write(data, 0, data.Length);
if (!_responseReceived.WaitOne(timeoutMs))
{
log.Error("SendAndWait() - Response timeout! Details: " +
" SerialPortReadBuffer: " + HexFormatter.ToHex(SerialPortReadBuffer.ToArray()) +
" _binMessages" + HexFormatter.ToHex(_binMessages.ToArray()) +
"_responseReceived: " + _responseReceived.WaitOne(0)
);
ErrorMessage = "COM error: response timeout";
return null;
}
return GetRawData();
}
#endregion
public void Dispose()
{
CloseConnection();
}
public override string ToString()
{
return "SerialDriver: " + _serialPort.PortName + " (opened status:" + _serialPort.IsOpen +")";
}
}
}
@@ -0,0 +1,82 @@
using System;
using System.IO.Ports;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.Utils
{
public class SerialDriverBuilder
{
private string _portName;
private int _baudRate = 9600;
private int _dataBits = 8;
private Parity _parity = Parity.None;
private StopBits _stopBits = StopBits.One;
private int _readTimeout = 1000;
private int _writeTimeout = 1000;
public SerialDriverBuilder WithPort(string portName)
{
_portName = portName;
return this;
}
public SerialDriverBuilder WithBaudRate(int baudRate)
{
_baudRate = baudRate;
return this;
}
public SerialDriverBuilder WithDataBits(int dataBits)
{
_dataBits = dataBits;
return this;
}
public SerialDriverBuilder WithParity(Parity parity)
{
_parity = parity;
return this;
}
public SerialDriverBuilder WithStopBits(StopBits stopBits)
{
_stopBits = stopBits;
return this;
}
public SerialDriverBuilder WithTimeouts(int readTimeout, int writeTimeout)
{
_readTimeout = readTimeout;
_writeTimeout = writeTimeout;
return this;
}
/// <summary>
/// Build driver WITHOUT opening connection
/// </summary>
public SerialDriver Build()
{
return new SerialDriver(
_portName,
_baudRate,
_dataBits,
_parity,
_stopBits,
_readTimeout,
_writeTimeout
);
}
/// <summary>
/// Build driver AND open connection
/// </summary>
public SerialDriver BuildAndConnect()
{
var driver = Build();
if (!driver.Open())
{
throw new InvalidOperationException(driver.ErrorMessage);
}
return driver;
}
}
}
@@ -4,7 +4,7 @@
///
namespace TBF.Rig.TestMethods.iPerlCommunication
{
partial class iPerlCommunicationFormTestMethod
partial class iPerlCommunicationForm
{
/// <summary>
/// Required designer variable.
@@ -32,7 +32,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(iPerlCommunicationFormTestMethod));
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(iPerlCommunicationForm));
this.wmTextBox2 = new System.Windows.Forms.TextBox();
this.wmLabel2 = new System.Windows.Forms.Label();
this.wmLabel1 = new System.Windows.Forms.Label();
@@ -2585,7 +2585,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "iPerlCommunicationFormTestMethod";
this.Name = "iPerlCommunicationForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "iPerl Communication";
this.TopMost = true;
@@ -10,23 +10,27 @@ using Config.Entities;
using TBF.Rig.Generic;
using TBF.Resources;
using System.Collections.Generic;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
namespace TBF.Rig.TestMethods.iPerlCommunication
{
public class iPerlCommunicationParams : TestParamsBase, ITestParams
public class iPerlCommunicationParams : TestParamsBase, IParamsProvider, ITestParams
{
public static XmlSerializer Serializer = XmlSerializer.FromTypes(new[] { typeof(iPerlCommunicationParams) })[0];
public override XmlSerializer GetSerializer() { return Serializer; }
public string Activity
{
get { return base.Activity; }
set { base.Activity = value; }
}
public string Activity { get; set; } /// Communication activity
public bool SimultWithPrevious { get; set; }
public bool SimultWithNext { get; set; }
/// Communication activity
public bool SimultWithPrevious;
public bool SimultWithNext;
public override void InitializeAll()
{
Activity = "Read Configuration";
Activity = iPerlCommunicationForm.ReadConfigurationStr;
SimultWithPrevious = false;
SimultWithNext = false;
}
@@ -46,54 +50,56 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
if (i == 0)
{
var retVal = new List<string>();
retVal.Add(iPerlCommunicationConstants.ReadConfigurationStr);
retVal.Add(string.Format("{0} A0", iPerlCommunicationConstants.SetTestModeStr));
retVal.Add(string.Format("{0} A4", iPerlCommunicationConstants.SetTestModeStr));
retVal.Add(iPerlCommunicationConstants.ReadCalibrationStr);
retVal.Add(iPerlCommunicationConstants.ReadCalibrationV4Str);
retVal.Add(iPerlCommunicationConstants.NormalizeCalibrationFactorStr);
retVal.Add(iPerlCommunicationConstants.NormalizeCalibrationV4FactorsStr);
retVal.Add(iPerlCommunicationConstants.GetDefaultQ2CorrectionsStr);
retVal.Add(iPerlCommunicationConstants.ReadQ2CorrectionStr);
retVal.Add(iPerlCommunicationConstants.ResetQ2CorrectionStr);
retVal.Add(iPerlCommunicationConstants.WriteDefaultQ2CorrectionsStr);
retVal.Add(iPerlCommunicationConstants.InitOrReadQ2CorrectionsStr);
retVal.Add(iPerlCommunicationConstants.WriteCalibrationFactorStr);
retVal.Add(iPerlCommunicationConstants.WriteCalibrationV4FactorsStr);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionStr);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionAltStr);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionGreeceStr);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionRLStr);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionLRStr);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionIncl05Str);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionAltIncl05Str);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionPlusIncl05Str);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionPlusAltIncl05Str);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionGreeceIncl05Str);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionRLIncl05Str);
retVal.Add(iPerlCommunicationConstants.WriteQ2CorrectionLRIncl05Str);
retVal.Add(iPerlCommunicationConstants.Q2correctedFromCmd + "Qx");
retVal.Add(iPerlCommunicationConstants.StrictQ2ErrorCheckStr + "Qx");
retVal.Add(iPerlCommunicationConstants.Q2correctionCheckCmd);
retVal.Add(iPerlCommunicationConstants.IperlCheckCmd);
retVal.Add(iPerlCommunicationConstants.UpdateBothQ2FactorsTestRLOnlyStr);
retVal.Add(iPerlCommunicationConstants.UpdateBothQ2FactorsTestLROnlyStr);
retVal.Add(iPerlCommunicationConstants.UpdateQ2CorrectionsStr);
retVal.Add(iPerlCommunicationConstants.ConditnlUpdateQ2CorrectionsStr);
retVal.Add(iPerlCommunicationConstants.ConditnlUpdateQ2CorrRLStr);
retVal.Add(iPerlCommunicationConstants.ConditnlUpdateQ2CorrLRStr);
retVal.Add(iPerlCommunicationForm.ReadConfigurationStr);
retVal.Add(iPerlCommunicationForm.ReadSerialNrStr);
retVal.Add(string.Format("{0} A0", iPerlCommunicationForm.SetTestModeStr));
retVal.Add(string.Format("{0} A4", iPerlCommunicationForm.SetTestModeStr));
retVal.Add(iPerlCommunicationForm.ReadCalibrationStr);
retVal.Add(iPerlCommunicationForm.ReadCalibrationV4Str);
retVal.Add(iPerlCommunicationForm.NormalizeCalibrationFactorStr);
retVal.Add(iPerlCommunicationForm.NormalizeCalibrationV4FactorsStr);
retVal.Add(iPerlCommunicationForm.GetDefaultQ2CorrectionsStr);
retVal.Add(iPerlCommunicationForm.ReadQ2CorrectionStr);
retVal.Add(iPerlCommunicationForm.ResetQ2CorrectionStr);
retVal.Add(iPerlCommunicationForm.WriteDefaultQ2CorrectionsStr);
retVal.Add(iPerlCommunicationForm.InitOrReadQ2CorrectionsStr);
retVal.Add(iPerlCommunicationForm.WriteCalibrationFactorStr);
retVal.Add(iPerlCommunicationForm.WriteCalibrationV4FactorsStr);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionStr);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionAltStr);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionGreeceStr);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionRLStr);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionLRStr);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionIncl05Str);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionAltIncl05Str);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionPlusIncl05Str);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionPlusAltIncl05Str);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionGreeceIncl05Str);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionRLIncl05Str);
retVal.Add(iPerlCommunicationForm.WriteQ2CorrectionLRIncl05Str);
retVal.Add(iPerlCommunicationSeq.Q2correctedFromCmd + "Qx");
retVal.Add(iPerlCommunicationSeq.StrictQ2ErrorCheckStr + "Qx");
retVal.Add(iPerlCommunicationSeq.Q2correctionCheckCmd);
retVal.Add(iPerlCommunicationSeq.IperlCheckCmd);
retVal.Add(iPerlCommunicationForm.UpdateBothQ2FactorsTestRLOnlyStr);
retVal.Add(iPerlCommunicationForm.UpdateBothQ2FactorsTestLROnlyStr);
retVal.Add(iPerlCommunicationForm.UpdateQ2CorrectionsStr);
retVal.Add(iPerlCommunicationForm.ConditnlUpdateQ2CorrectionsStr);
retVal.Add(iPerlCommunicationForm.ConditnlUpdateQ2CorrRLStr);
retVal.Add(iPerlCommunicationForm.ConditnlUpdateQ2CorrLRStr);
retVal.Add("Q2 corrected from Q2adj");
retVal.Add("Q2 correction check Q2bc Q2ac");
retVal.Add(iPerlCommunicationConstants.SetActiveModeStr);
retVal.Add(iPerlCommunicationForm.SetActiveModeStr);
retVal.Add(iPerlCommunicationForm.SetIdleModeStr);
retVal.Add("---");
retVal.Add(iPerlCommunicationConstants.Reset2HzCorrectionStr);
retVal.Add(iPerlCommunicationConstants.Write2HzCorrectionStr);
retVal.Add(iPerlCommunicationConstants.DewaReworkRLStr);
retVal.Add(iPerlCommunicationConstants.DewaReworkLRStr);
retVal.Add(iPerlCommunicationConstants.StartTestingSealedMetersStr);
retVal.Add(iPerlCommunicationConstants.EndTestingSealedMetersStr);
retVal.Add(string.Format("{0} if enabled", iPerlCommunicationConstants.ReadConfigurationStr));
retVal.Add(string.Format("{0} 80", iPerlCommunicationConstants.SetTestModeStr));
retVal.Add(iPerlCommunicationForm.Reset2HzCorrectionStr);
retVal.Add(iPerlCommunicationForm.Write2HzCorrectionStr);
retVal.Add(iPerlCommunicationForm.DewaReworkRLStr);
retVal.Add(iPerlCommunicationForm.DewaReworkLRStr);
retVal.Add(iPerlCommunicationForm.StartTestingSealedMetersStr);
retVal.Add(iPerlCommunicationForm.EndTestingSealedMetersStr);
retVal.Add(string.Format("{0} if enabled", iPerlCommunicationForm.ReadConfigurationStr));
retVal.Add(string.Format("{0} 80", iPerlCommunicationForm.SetTestModeStr));
retVal.Add("iPerl_check prevWorkStep direction q2factors");
for (ConditionID id = ConditionID.A; id < ConditionID.Count; id++)
{
@@ -35,7 +35,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
///
void OpenIPerlCommForm(iPerlCommunicationSeq myRef, TestMethod method, Test test, iPerlCommunicationParams testParams)
{
myRef.modelessDlg = new iPerlCommunicationFormTestMethod(method, test, testParams);
myRef.modelessDlg = new iPerlCommunicationForm(method, test, testParams);
myRef.modelessDlg.Show();
}
@@ -59,7 +59,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
/// </returns>
public IList<Event> Execute(Test test, int repetitionNr, TestMethod method, ITestParams testParams)
{
TestMethodCfg_IPerl cfgIPerl = method.Cfg as TestMethodCfg_IPerl;
TestMethodCfg cfg = method.Cfg as TestMethodCfg;
IList<Event> e; /// Events from currently running operations
checkUiOp = new Operations.CheckUIOp(true); /// Runs in more then one state
@@ -68,7 +68,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
processDataLoggingOp = new TBF.Rig.Operations.ProcessDataLoggingOp(processDataLogger, this, false);
string cmd;
if (testParams.Activity.ToLower().Equals(cmd = iPerlCommunicationFormTestMethod.GetDefaultQ2CorrectionsStr.ToLower()))
if (testParams.Activity.ToLower().Equals(cmd = iPerlCommunicationForm.GetDefaultQ2CorrectionsStr.ToLower()))
{
TestProgressEventArgs.SetEstimatedTimes(new int[] { 0, 0, 0, 30, 0, 30, 0, 0 });
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.JustStarted));
@@ -87,9 +87,9 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
}*/
#endif
if (cfgIPerl.UseWebService)
if (cfg.UseWebService)
{
IsQ2PreCorrectionCalculated = GetQ2PreCorrectionsOrBackups(cfgIPerl, wmType, out CalculatedQ2PreCorrectionLR, out CalculatedQ2PreCorrectionRL);
IsQ2PreCorrectionCalculated = GetQ2PreCorrectionsOrBackups(cfg, wmType, out CalculatedQ2PreCorrectionLR, out CalculatedQ2PreCorrectionRL);
}
/// Generate test results
@@ -106,7 +106,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
{
if (mtr.TestRslt == tstRslt)
{
mtr.Passed = !cfgIPerl.UseWebService || IsQ2PreCorrectionCalculated;
mtr.Passed = !cfg.UseWebService || IsQ2PreCorrectionCalculated;
mtr.TestDone = true;
break;
}
@@ -271,7 +271,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, tstRslt));
allResults.Info(TestResult2CsvLine(test.Name, 0)); /// Append the results to the CSV-file
if (wrongMetersCount >= cfgIPerl.IperlCheckErrorsToStop)
if (wrongMetersCount >= cfg.IperlCheckErrorsToStop)
{
State.Create("iPerlCommunicationSeq : Show check result")
.AddOperation(new Operations.LargeMessageBoxOp(message))
@@ -409,12 +409,12 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
/// <summary>
/// Read default Q2 correction factors from a REST service (= Web service).
/// </summary>
/// <param name="cfgIPerl">iPerlCommunication component configuration</param>
/// <param name="cfg">iPerlCommunication component configuration</param>
/// <param name="wmType">Water meter type (WZ Typ)</param>
/// <param name="q2PreCorrectionLR">Default Q2 correction LR</param>
/// <param name="q2PreCorrectionRL">Default Q2 correction RL</param>
/// <returns>true when successful</returns>
static bool ReadCorrectionsFromWebService(TestMethodCfg_IPerl cfgIPerl, int wmType, out int q2PreCorrectionLR, out int q2PreCorrectionRL)
static bool ReadCorrectionsFromWebService(TestMethodCfg cfg, int wmType, out int q2PreCorrectionLR, out int q2PreCorrectionRL)
{
if (wmType == 0)
{
@@ -426,9 +426,9 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
try
{
GetQ2PreCorrectionClient client = new GetQ2PreCorrectionClient(cfgIPerl.BaseUrl);
GetQ2PreCorrectionClient client = new GetQ2PreCorrectionClient(cfg.BaseUrl);
client.GetToken("ReadUser", "sensus", "https://deluh1web03.world.fluidtechnology.net/SensusCore/api/v1/Locations/1/Login2").Wait();
Q2PreCorrection response = client.GetQ2Correction(string.Format(cfgIPerl.RelativeUrl, wmType)).Result;
Q2PreCorrection response = client.GetQ2Correction(string.Format(cfg.RelativeUrl, wmType)).Result;
if (response != null && response.AreDataCalculated)
{
q2PreCorrectionLR = response.CorrLR;
@@ -456,15 +456,15 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
/// <summary>
/// Obtain Q2 correction factors from a REST service or from local settings (stored backup values)
/// </summary>
/// <param name="cfgIPerl">iPerlCommunication component configuration</param>
/// <param name="cfg">iPerlCommunication component configuration</param>
/// <param name="wmType">Water meter type (WZ Typ)</param>
/// <param name="q2PreCorrectionLR">Default Q2 correction LR</param>
/// <param name="q2PreCorrectionRL">Default Q2 correction RL</param>
/// <returns>true when successful</returns>
public static bool GetQ2PreCorrectionsOrBackups(TestMethodCfg_IPerl cfgIPerl, int wmType, out int q2PreCorrectionLR, out int q2PreCorrectionRL)
public static bool GetQ2PreCorrectionsOrBackups(TestMethodCfg cfg, int wmType, out int q2PreCorrectionLR, out int q2PreCorrectionRL)
{
/// Get Q2 pre-correction values from REST service
bool restOK = ReadCorrectionsFromWebService(cfgIPerl, wmType, out q2PreCorrectionLR, out q2PreCorrectionRL);
bool restOK = ReadCorrectionsFromWebService(cfg, wmType, out q2PreCorrectionLR, out q2PreCorrectionRL);
/// Store / load Q2 pre-correction values
Point storedValue;
@@ -3,264 +3,203 @@
///
using System;
using System.IO;
using System.Text;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
public class ConfigStruct
{
public const int Length = 32;
//public const int Length = 32; // dynamic
public Byte Version; /// 0: 1 byte
public MeterState MeterState; /// 1: 1 byte
public UInt32 TargetTimeVeryLowBatt; /// 2: 4 bytes in seconds
public UInt32 TargetTimeLowBatt; /// 6: 4 bytes, in seconds
public UInt32 TestModeTime; /// 10: 4 bytes, Max. test mode time in seconds
public UInt16 EmptyPipeThreshold; /// 14: 2 bytes
public byte[] PCBNumber; /// 16: 5 bytes
public byte TestModeConfig; /// 21: 1 byte
public UInt32 RadioAddress; /// 22: 4 bytes
public UInt16 TempCalibration; /// 26: 2 bytes
public UInt16 AlarmMask; /// 28: 2 bytes, Default 0xA3F7
public UInt16 ConfigCheckSum; /// 30: 2 bytes
//public Byte Version; // 0: 1 byte
public string PCBNumberString; // dynamic
public ProtocolStatuses StatusMode; // byte
public DiagnosticLedState OpthoStatusMode;// byte
public string Unit; //dynamic
public string Version; // dynamic
public ConfigStruct()
{
PCBNumber = new byte[5];
}
public byte[] ToByteArray()
//Optho test status mode
public DiagnosticLedState TestModeConfig
{
byte[] result = new byte[Length];
result[0] = Version;
result[1] = (byte)MeterState;
result[2] = (byte)(TargetTimeVeryLowBatt & 0x000000FF);
result[3] = (byte)((TargetTimeVeryLowBatt >> 8) & 0x000000FF);
result[4] = (byte)((TargetTimeVeryLowBatt >> 16) & 0x000000FF);
result[5] = (byte)((TargetTimeVeryLowBatt >> 24) & 0x000000FF);
result[6] = (byte)(TargetTimeLowBatt & 0x000000FF);
result[7] = (byte)((TargetTimeLowBatt >> 8) & 0x000000FF);
result[8] = (byte)((TargetTimeLowBatt >> 16) & 0x000000FF);
result[9] = (byte)((TargetTimeLowBatt >> 24) & 0x000000FF);
result[10] = (byte)(TestModeTime & 0x000000FF);
result[11] = (byte)((TestModeTime >> 8) & 0x000000FF);
result[12] = (byte)((TestModeTime >> 16) & 0x000000FF);
result[13] = (byte)((TestModeTime >> 24) & 0x000000FF);
result[14] = (byte)(EmptyPipeThreshold & 0x00FF);
result[15] = (byte)((EmptyPipeThreshold >> 8) & 0x00FF);
result[16] = PCBNumber[0];
result[17] = PCBNumber[1];
result[18] = PCBNumber[2];
result[19] = PCBNumber[3];
result[20] = PCBNumber[4];
result[21] = TestModeConfig;
result[22] = (byte)(RadioAddress & 0x000000FF);
result[23] = (byte)((RadioAddress >> 8) & 0x000000FF);
result[24] = (byte)((RadioAddress >> 16) & 0x000000FF);
result[25] = (byte)((RadioAddress >> 24) & 0x000000FF);
result[26] = (byte)(TempCalibration & 0x00FF);
result[27] = (byte)((TempCalibration >> 8) & 0x00FF);
result[28] = (byte)(AlarmMask & 0x00FF);
result[29] = (byte)((AlarmMask >> 8) & 0x00FF);
result[30] = (byte)(ConfigCheckSum & 0x00FF);
result[31] = (byte)((ConfigCheckSum >> 8) & 0x00FF);
return result;
get { return OpthoStatusMode; }
}
/// <summary>
/// Create a configuration structure from a complete byte array
/// </summary>
/// <param name="data">A complete byte array data</param>
/// <returns>ConfigStruct or null when byte array was not complete</returns>
public static ConfigStruct FromByteArray(byte[] data)
//Activity test status mode
public ProtocolStatuses MeterState
{
if (data.Length != Length) return null;
ConfigStruct result = new ConfigStruct();
result.Version = data[0];
result.MeterState = (MeterState)data[1];
result.TargetTimeVeryLowBatt = (((UInt32)data[5] * 256 + data[4]) * 256 + data[3]) * 256 + data[2];
result.TargetTimeLowBatt = (((UInt32)data[9] * 256 + data[8]) * 256 + data[7]) * 256 + data[6];
result.TestModeTime = (((UInt32)data[13] * 256 + data[12]) * 256 + data[11]) * 256 + data[10];
result.EmptyPipeThreshold = (UInt16)(data[15] * 256 + data[14]);
result.PCBNumber[0] = data[16];
result.PCBNumber[1] = data[17];
result.PCBNumber[2] = data[18];
result.PCBNumber[3] = data[19];
result.PCBNumber[4] = data[20];
result.TestModeConfig = data[21];
result.RadioAddress = (((UInt32)data[25] * 256 + data[24]) * 256 + data[23]) * 256 + data[22];
result.TempCalibration = (UInt16)(data[27] * 256 + data[26]);
result.AlarmMask = (UInt16)(data[29] * 256 + data[28]);
result.ConfigCheckSum = (UInt16)(data[31] * 256 + data[30]);
return result;
get
{
return StatusMode;
}
}
/// <summary>
/// Update the configuration structure from an incomplete byte array
/// </summary>
/// <param name="offset">Offset of byte array data in ConfigStruct</param>
/// <param name="data">Byte array data</param>
/// <returns>true when successful, false when data are not appropriate</returns>
public bool Update(int offset, byte[] data)
{
if (offset == 0 && data.Length == 2)
{
/// iPerl mode of function
Version = data[0];
MeterState = (MeterState)data[1];
return true;
}
else if (offset == 0 && data.Length == 4)
{
/// iPerl mode of function and extra 2 bytes
Version = data[0];
MeterState = (MeterState)data[1];
return true;
}
else if (offset == 21 && data.Length == 1)
{
/// TestModeConfig value
TestModeConfig = data[21 - offset];
return true;
}
else if (offset == 0 && data.Length == Length)
{
/// Complete ConfigStruct
Version = data[0];
MeterState = (MeterState)data[1];
TargetTimeVeryLowBatt = (((UInt32)data[5] * 256 + data[4]) * 256 + data[3]) * 256 + data[2];
TargetTimeLowBatt = (((UInt32)data[9] * 256 + data[8]) * 256 + data[7]) * 256 + data[6];
TestModeTime = (((UInt32)data[13] * 256 + data[12]) * 256 + data[11]) * 256 + data[10];
EmptyPipeThreshold = (UInt16)(data[15] * 256 + data[14]);
PCBNumber[0] = data[16];
PCBNumber[1] = data[17];
PCBNumber[2] = data[18];
PCBNumber[3] = data[19];
PCBNumber[4] = data[20];
TestModeConfig = data[21];
RadioAddress = (((UInt32)data[25] * 256 + data[24]) * 256 + data[23]) * 256 + data[22];
TempCalibration = (UInt16)(data[27] * 256 + data[26]);
AlarmMask = (UInt16)(data[29] * 256 + data[28]);
ConfigCheckSum = (UInt16)(data[31] * 256 + data[30]);
return true;
}
else
return false;
}
/// <summary>
/// Returns PCB number string (12 characters, 12 decimal digits)
/// </summary>
/// <returns>PCB number STRING</returns>
public string GetPcbNrString()
{
return PCBNumber2String(this.PCBNumber);
}
public string GetPcbNrString(){
return PCBNumberString;
}
/// <summary>
/// Converts PCBNumber to string (12 characters, 12 decimal digits)
/// </summary>
/// <param name="pcbNumber"></param>
/// <returns>PCB number string</returns>
public static string PCBNumber2String(byte[] pcbNumber)
{
if (pcbNumber.Length != 5) return string.Empty;
Int64 number = 0;
for (int i = 4; i >= 0; i--)
{
number = 256 * number + (Int64)pcbNumber[i];
}
return number.ToString();
}
public string GetStatusModeString()
{
return string.Format(
"Config: StatusMode={0}",
StatusMode
);
}
public string GetActiveModeString()
{
return string.Format(
"Config: StatusMode={0}, OpthoStatusMode={1}",
StatusMode,
OpthoStatusMode
);
}
public override string ToString()
{
return string.Format("Config: V{0} State={1} VLoBattT={2}s LoBattT={3}s TestModeT={4}s EPThld={5} PCB#={6} TMCfg={7} RadioAddr={8} TempCalib={9} AlarmMask={10} CfgCheckSum={11}",
Version,
MeterState,
TargetTimeVeryLowBatt,
TargetTimeLowBatt,
TestModeTime,
EmptyPipeThreshold,
GetPcbNrString(),
TestModeConfig.ToString("X2"),
RadioAddress,
TempCalibration,
AlarmMask.ToString("X4"),
ConfigCheckSum.ToString("X4"));
return string.Format(
"Config: PCB#={0} StatusMode={1} Unit={2} V{3}",
GetPcbNrString(),
StatusMode,
Unit,
Version
);
}
public string ToString(int sel)
{
return string.Format("{1} PCB#={6} TMCfg={7}",
Version,
MeterState,
TargetTimeVeryLowBatt,
TargetTimeLowBatt,
TestModeTime,
EmptyPipeThreshold,
GetPcbNrString(),
TestModeConfig.ToString("X2"),
RadioAddress,
TempCalibration,
AlarmMask.ToString("X4"),
ConfigCheckSum.ToString("X4"));
return string.Format(
"Config: PCB#={0} StatusMode={1} Unit={2} V{3}",
GetPcbNrString(),
StatusMode,
Unit,
Version
);
}
public virtual void WriteBinary(BinaryWriter writer)
{
writer.Write(Version);
writer.Write((byte)MeterState);
writer.Write(TargetTimeVeryLowBatt);
writer.Write(TargetTimeLowBatt);
writer.Write(TestModeTime);
writer.Write(EmptyPipeThreshold);
writer.Write(PCBNumber[0]);
writer.Write(PCBNumber[1]);
writer.Write(PCBNumber[2]);
writer.Write(PCBNumber[3]);
writer.Write(PCBNumber[4]);
writer.Write(TestModeConfig);
writer.Write(RadioAddress);
writer.Write(TempCalibration);
writer.Write(AlarmMask);
writer.Write(ConfigCheckSum);
if (writer == null)
throw new ArgumentNullException(nameof(writer));
// ---- Marker ----
writer.Write((byte)0x11);
// ---- Version ----
if (!string.IsNullOrEmpty(Version))
{
// Convert string to bytes (UTF8 is standard)
byte[] versionBytes = Encoding.UTF8.GetBytes(Version);
// 1) write length
writer.Write(versionBytes.Length);
// 2) write string bytes
writer.Write(versionBytes);
//writer.Write(Version);
}
else
{
writer.Write(0);//Length
}
// ---- StatusMode ----
writer.Write((byte)StatusMode);
// ---- PCB Number ----
if (!string.IsNullOrEmpty(PCBNumberString))
{
byte[] PCBNumberStringBytes = Encoding.UTF8.GetBytes(PCBNumberString);
// 1) write length
writer.Write(PCBNumberStringBytes.Length);
// 2) write string bytes
writer.Write(PCBNumberStringBytes);
}
else
{
writer.Write(0); //Length
}
// ---- Unit ----
if (!string.IsNullOrEmpty(Unit))
{
// Convert string to bytes (UTF8 is standard)
byte[] unitBytes = Encoding.UTF8.GetBytes(Unit);
// 1) write length
writer.Write(unitBytes.Length);
// 2) write string bytes
writer.Write(unitBytes);
//writer.Write(Version);
}
else
{
writer.Write(0); //Length
}
}
public virtual void ReadBinary(BinaryReader reader)
{
Version = reader.ReadByte();
MeterState = (MeterState)reader.ReadByte();
TargetTimeVeryLowBatt = reader.ReadUInt32();
TargetTimeLowBatt = reader.ReadUInt32();
TestModeTime = reader.ReadUInt32();
EmptyPipeThreshold = reader.ReadUInt16();
PCBNumber[0] = reader.ReadByte();
PCBNumber[1] = reader.ReadByte();
PCBNumber[2] = reader.ReadByte();
PCBNumber[3] = reader.ReadByte();
PCBNumber[4] = reader.ReadByte();
TestModeConfig = reader.ReadByte();
RadioAddress = reader.ReadUInt32();
TempCalibration = reader.ReadUInt16();
AlarmMask = reader.ReadUInt16();
ConfigCheckSum = reader.ReadUInt16();
if (reader == null)
throw new ArgumentNullException(nameof(reader));
// ---- Marker ----
byte marker = reader.ReadByte();
if (marker != 0x11)
throw new InvalidDataException($"Invalid config marker: 0x{marker:X2}");
// ---- Version ----
int versionLength = reader.ReadInt32();
if (versionLength < 0)
throw new InvalidDataException("Invalid Version length.");
byte[] versionBytes = reader.ReadBytes(versionLength);
if (versionBytes.Length != versionLength)
throw new EndOfStreamException("Unexpected end of stream while reading Version.");
Version = versionLength > 0
? Encoding.UTF8.GetString(versionBytes)
: string.Empty;
// ---- StatusMode ----
StatusMode = (ProtocolStatuses)reader.ReadByte();
// ---- PCB Number ----
int pcbLength = reader.ReadInt32();
if (pcbLength < 0)
throw new InvalidDataException("Invalid PCB number length.");
byte[] pcbBytes = reader.ReadBytes(pcbLength);
if (pcbBytes.Length != pcbLength)
throw new EndOfStreamException("Unexpected end of stream while reading PCB number.");
PCBNumberString = pcbLength > 0
? Encoding.UTF8.GetString(pcbBytes)
: string.Empty;
// ---- Unit ----
int unitLength = reader.ReadInt32();
if (unitLength < 0)
throw new InvalidDataException("Invalid Unit length.");
byte[] unitBytes = reader.ReadBytes(unitLength);
if (unitBytes.Length != unitLength)
throw new EndOfStreamException("Unexpected end of stream while reading Unit.");
Unit = unitLength > 0
? Encoding.UTF8.GetString(unitBytes)
: string.Empty;
}
}
}
@@ -11,40 +11,35 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
private static readonly ILog log = LogManager.GetLogger(typeof(IperlHead));
const int FIFO_SIZE = 64; /// 8 sec. @ 8Hz
const double MAX_OPTO_DROPOUT = 4.5; /// sec.
const int FIFO_SIZE = 64; // 8 sec @ 8Hz
const double MAX_OPTO_DROPOUT = 4.5; // sec
Int64[] volumeRawFifo; /// Volume FIFO buffer
Int64[] timestampFifo; /// Timestamp FIFO buffer
private readonly double[] volumeRawFifo;
private readonly double[] timestampFifo; // centered timestamps
int fifoCount; /// Number of valid FIFO items
int fifoIx; /// Index of the next FIFO item
DateTime lastFifoWriteTime; /// Time of the last write to FIFO
private int fifoCount;
private int fifoIx;
private DateTime lastFifoWriteTime;
///
/// Sums for linear regression calculation
///
decimal sumXX;
decimal sumX;
decimal sumXY;
decimal sumY;
decimal N;
// regression sums (double is ideal here)
private double sumXX;
private double sumX;
private double sumXY;
private double sumY;
double minSlope; /// max. slope of the regressed line, always positive or 0
double maxSlope; /// min. slope of the regressed line, always negative or 0
private double minSlope;
private double maxSlope;
// timestamp centering for numerical stability
private double firstTimestamp = double.NaN;
public FlowDirectionDetection()
{
volumeRawFifo = new Int64[FIFO_SIZE];
timestampFifo = new Int64[FIFO_SIZE];
volumeRawFifo = new double[FIFO_SIZE];
timestampFifo = new double[FIFO_SIZE];
ClearFifo();
}
/// <summary>
/// Clear FIFO data
/// </summary>
public void ClearFifo()
{
fifoCount = 0;
@@ -55,94 +50,93 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
sumX = 0;
sumXY = 0;
sumY = 0;
N = 0;
minSlope = 0;
maxSlope = 0;
firstTimestamp = double.NaN;
}
/// <summary>
/// Write data to FIFO
/// Add sample to rolling FIFO and update regression sums
/// </summary>
/// <param name="volumeRaw">Volume</param>
/// <param name="timestamp">Time stamp</param>
public void WriteToFifo(Int64 volumeRaw, Int64 timestamp)
public void WriteToFifo(double volumeRaw, double timestamp)
{
///
/// Update sums for linear regression calculation
///
// establish time origin (CRITICAL for double precision)
if (double.IsNaN(firstTimestamp))
firstTimestamp = timestamp;
double x = timestamp - firstTimestamp; // centered time
double y = volumeRaw;
// remove oldest sample if buffer full
if (fifoCount == FIFO_SIZE)
{
/// Buffer is already full, the oldest item will be re-written
sumXX -= timestampFifo[fifoIx] * timestampFifo[fifoIx];
sumX -= timestampFifo[fifoIx];
sumXY -= timestampFifo[fifoIx] * volumeRawFifo[fifoIx];
sumY -= volumeRawFifo[fifoIx];
N--;
double oldX = timestampFifo[fifoIx];
double oldY = volumeRawFifo[fifoIx];
sumXX -= oldX * oldX;
sumX -= oldX;
sumXY -= oldX * oldY;
sumY -= oldY;
}
sumXX += timestamp * timestamp;
sumX += timestamp;
sumXY += timestamp * volumeRaw;
sumY += volumeRaw;
N++;
else
{
fifoCount++;
}
// add new sample
sumXX += x * x;
sumX += x;
sumXY += x * y;
sumY += y;
// store sample
timestampFifo[fifoIx] = x;
volumeRawFifo[fifoIx] = y;
///
/// Save new values to FIFO
///
volumeRawFifo[fifoIx] = volumeRaw;
timestampFifo[fifoIx] = timestamp;
fifoIx = (fifoIx + 1) % FIFO_SIZE;
fifoCount = Math.Min(fifoCount + 1, FIFO_SIZE);
lastFifoWriteTime = DateTime.Now;
}
/// <summary>
/// Determine whether there are enough recent FIFO data
/// </summary>
/// <returns>true when data valid</returns>
public bool AreFifoDataValid()
{
return (DateTime.Now.Subtract(lastFifoWriteTime).TotalSeconds <= MAX_OPTO_DROPOUT) && (fifoCount == FIFO_SIZE);
return (DateTime.Now.Subtract(lastFifoWriteTime).TotalSeconds <= MAX_OPTO_DROPOUT)
&& (fifoCount == FIFO_SIZE);
}
/// <summary>
/// Verify whether the flow direction is correct
/// </summary>
/// <returns>OptoHeadState.OptoAndDirOK, OptoHeadState.OptoNok or OptoHeadState.DirNok</returns>
public OptoHeadState CheckFlowDirection(Counting counting, string iPerlHeadName)
{
if (!AreFifoDataValid()) return OptoHeadState.OptoNok;
if (!AreFifoDataValid())
return OptoHeadState.OptoNok;
try
{
decimal numer = N * sumXY - sumX * sumY;
decimal denom = N * sumXX - sumX * sumX;
double N = fifoCount;
if (denom == 0) return OptoHeadState.DirNok;
double numer = N * sumXY - sumX * sumY;
double denom = N * sumXX - sumX * sumX;
if (Math.Abs(denom) < 1e-12)
return OptoHeadState.DirNok;
double slope = numer / denom;
/// Calculate the slope of the regressed line, determine min. and max.
double slope = (double)(numer / denom);
if (slope > maxSlope) maxSlope = slope;
if (slope < minSlope) minSlope = slope;
if ( counting == Counting.Arbitrary ||
if (counting == Counting.Arbitrary ||
(counting == Counting.Positive && maxSlope > Math.Abs(2 * minSlope)) ||
(counting == Counting.Negative && minSlope < -Math.Abs(2 * maxSlope)))
{
return OptoHeadState.OptoAndDirOK;
}
else
{
return OptoHeadState.DirNok;
}
return OptoHeadState.DirNok;
}
catch (Exception)
catch (Exception ex)
{
log.ErrorFormat("{0} : CheckFlowDirection() failed", iPerlHeadName);
return OptoHeadState.DirNok; /// ???
log.ErrorFormat("{0} : CheckFlowDirection() failed: {1}", iPerlHeadName, ex);
return OptoHeadState.DirNok;
}
}
}
@@ -6,28 +6,36 @@ using System.IO;
using System.IO.Ports;
using log4net;
using Common;
using Common.Iperl;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Rig.GenericDevices;
using Sensus.iPerl.NfcHandler;
using NHibernate;
using Renci.SshNet;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq; // This line is correct and does not need to be changed.
using System.Windows;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using TBF.Rig.TestMethods.iPerlCommunication.communication; // This line is correct and does not need to be changed.
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
using TBF.Rig.TestMethods.iPerlCommunication.communication.Utils;
using OptoTelegramFlags = TBF.Rig.TestMethods.iPerlCommunication.common.OptoTelegramFlags;
using OptoTelegramRaw = TBF.Rig.TestMethods.iPerlCommunication.common.OptoTelegramRaw;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.common;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
/// <summary>
/// This component = instance of this class is a placeholder for a combined main watermeter
/// </summary>
public class IperlHead : ComponentBase, IDevice,IRegReaderDatastream, ISessionDataMngmnt, IOperation, ISmartReader
public class IperlHead : ComponentBase, IDevice,IRegReaderDatastream, ISessionDataMngmnt, IOperation, IRegReaderSmart
{
private static readonly ILog log = LogManager.GetLogger(typeof(IperlHead));
private static readonly ILog logStream = LogManager.GetLogger("StreamData");
public override string ToString() { return string.Format("{0}({1})", ClassName, Cfg.ToString(-1)); }
#if TURA_SPECIAL
@@ -38,63 +46,49 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
public const string OptoDataDirectory = "C:\\TBF\\ProcessData";
public const int StartOptoDataCount = OptoDataBufferSize / 2;
public const int EndOptoDataCount = OptoDataBufferSize - StartOptoDataCount;
public const int StartEndFilterSamplesCount2 = 20; /// StartEndFilterSamplesCount = 2 * StartEndFilterSamplesCount2 + 1
public const int StartEndFilterSamplesCount2 = 2; //20 /// StartEndFilterSamplesCount = 2 * StartEndFilterSamplesCount2 + 1
public const int FeatureVectorSize = 9;
private OptoHeadTest _optoHeadTest;
public OptoHeadTest OptoHeadTest
{
get
{
if (_optoHeadTest == null)
_optoHeadTest = new OptoHeadTest(this);
return _optoHeadTest;
}
set { _optoHeadTest = value; }
}
readonly IperlHeadCfg iperlHeadCfg;
public int RfidComPortNr { get { return iperlHeadCfg.RfidComPortNr; } }
public bool CommFailed { get; set; }
public bool Disabled { get; set; }
public int OptoComPortNr { get { return iperlHeadCfg.OptoComPortNr; } }
public int MuxBoardNrOrGroup14 { get { return iperlHeadCfg.MuxBoardNr; } }
public int Group { get { return iperlHeadCfg.Group; } }
public iPerlHead.MeterType MeterType { get { return iperlHeadCfg.MeterType; } }
public string CommInterface { get { return iperlHeadCfg.CommunicationInterface.ToDescription(); } }
public CommunicationInterface CommInterface { get { return iperlHeadCfg.CommunicationInterface; } }
static int? ExtractPreferredNumber(string input)
{
if (string.IsNullOrEmpty(input))
return null;
// Match all sequences of digits
var matches = Regex.Matches(input, @"\d+");
if (matches.Count == 0)
return null;
// Prefer the last one if there are multiple
string selected = matches[matches.Count - 1].Value; // last element
return int.Parse(selected);
}
/// <summary>
/// this is a hack to get the position from the name
/// name must consist only with digit describing order of the meter
/// </summary>
public int Position
{
get
{
//BUMI this is a hack to get the position from the name
// but it is not working for all cases !!!!!
// - what stupid prediction (what index should be used?? see: 'S4iPerl1' or ...)
int? extractPreferredNumber = ExtractPreferredNumber(Name);
if (extractPreferredNumber.HasValue)
return extractPreferredNumber.Value;
return 0;
int firstDigitPos = Name.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' });
int position;
return (firstDigitPos < 0) ? 0 : (int.TryParse(Name.Substring(firstDigitPos), out position) ? position : 0);
}
}
public RegisterReaderType RegisterReaderType { get { return RegisterReaderType.DataStream; } }
public double PulsesPerLtr {
get { return 1000.0; }
set {PulsesPerLtr = value; }
get { return 1000.0; }
set { }
}
public double LtrsPerPulse { get { return 1 / PulsesPerLtr; } }
public string QuantityUnits { get; set; }
public double CalibTarget { get { return iperlHeadCfg.ProcParams.CalibTarget; } }
public ushort FactorLimitLo { get { return (ushort)iperlHeadCfg.ProcParams.FactorLimitLo; } }
public ushort FactorLimitHi { get { return (ushort)iperlHeadCfg.ProcParams.FactorLimitHi; } }
@@ -118,7 +112,9 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
simulatedPcbNr = value;
}
}
public bool Disabled;
public bool CommFailed;
public int ResultCode;
@@ -132,8 +128,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
/// <summary>
/// Passed to OptoTelegramRaw.UpdateFromString(...)
/// </summary>
Int64 volumeRawExtLast;
Int64 timestampExtLast;
double volumeRawExtLast;
double timestampExtLast;
FlowDirectionDetection flowDirectionDetection;
@@ -190,13 +186,23 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
///
public int WMPulses { get { return wmPulses; } }
public int WMRefPulses { get { return wmRefPulses; } }
public double BeginWMState { get { return beginWMState; } set { beginWMState = value; }}
public double EndWMState { get { return endWMState; } set { endWMState = value;} }
public double WMVolume { get { return wmVolume; } }
public double WMTestTime { get { return wmTestTime; } }
public double BeginWMState { get { return ResolveNaNDouble(beginWMState); } }
public double EndWMState { get { return ResolveNaNDouble(endWMState); } }
public double WMVolume { get { return ResolveNaNDouble(wmVolume); } }
public double WMTestTime { get { return ResolveNaNDouble(wmTestTime); } }
string simulatedPcbNr = null;
double ResolveNaNDouble(double d)
{
if (Double.IsNaN(d))
{
return 0.0;
}
else
return d;
}
int wmPulses;
int wmRefPulses;
double beginWMState;
@@ -269,7 +275,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
const double C = B * 60.0; /// Raw units per hour, 480
double D = C / A; /// ml correction per hour
double F = D / (nominalTestFlowLph * 10.0); /// Error corrected with 8 Raw Units per minute [%]
double G = F / B; /// Error corrected with 1 Raw Unit per minute [%]
double G = F / B; /// Error corrected with 1 Raw Units per minute [%]
/// Do not change the factor for an invalid measurement (q2adjResult.VolumeMeter == 0)
double q2CorrectionFactor = (Math.Abs(currentQ2Result.VolumeMeter) <= float.Epsilon) ? Convert.ToDouble(currentFactor) :
@@ -389,7 +395,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
///
/// Timestamp from the opto telegram
///
private Int64 lastTimestamp;
private double lastTimestamp;
private double timestampSec;
private double timestampSec0;
@@ -412,14 +418,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
///
/// Volume of water from the opto telegram
///
private Int64 lastVolumeRaw; /// Last read raw volume
private double lastVolumeRaw; /// Last read raw volume
private double volumeLtr;
private double volumeLtr0;
/// Test start volume for metrology in liters
public double VolumeLtrStart
{
get { return NoSamples ? 0 : VolumeFromSamples(optoData, optoDataCount, TestStartTelegramIx, ScalingFactor(), StartEndFilterSamplesCount2); }
get { return NoSamples ? 0 : VolumeFromSamples(optoData, optoDataCount, TestStartTelegramIx, ScalingFactor(), 0); }
}
/// Test end volume for metrology in liters
public double VolumeLtrEnd
@@ -473,7 +479,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
/// Check whether head is connected, working
try
{
OpenOptoSerialPort($"COM{iperlHeadCfg.OptoComPortNr}", 9600, Parity.None, 8, StopBits.One, Handshake.None);
OpenOptoSerialPort($"COM{iperlHeadCfg.OptoComPortNr}", 38400, Parity.None, 8, StopBits.One, Handshake.None);
CloseOptoSerialPort();
log.FatalFormat($"{Name} initialized: {this}");
}
@@ -618,10 +624,10 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
ResultCode = 0;
volumeLtr = 0;
volumeLtr0 = 0;
timestampSec = 0;
timestampSec0 = 0;
volumeLtr = Double.NaN;
volumeLtr0 = Double.NaN;
timestampSec = Double.NaN;
timestampSec0 = Double.NaN;
extraDataPath = null;
@@ -887,34 +893,63 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
endWMState = volumeLtr;
wmVolume = Math.Abs(endWMState - beginWMState);
wmPulses = (int)(wmVolume * (double)PulsesPerLtr + 0.5);
log.Debug("wmPulses = " + wmPulses + "wmVolume = " + wmVolume + "PulsesPerLtr = " + PulsesPerLtr + "");
wmRefPulses = StateMachine.ControlBoardMain.RefPulses;
wmTestTime = timestampSec - timestampSec0;
}
private void OpenOptoSerialPort(string comPort, int baudRate, Parity parity, int dataBits, StopBits stopBit, Handshake handshake)
private void OpenOptoSerialPort(
string comPort,
int baudRate,
Parity parity,
int dataBits,
StopBits stopBit,
Handshake handshake,
int openTimeoutMs = 3000)
{
if (DebugLevel == DebugMode.FailureDuringOperation) DebugLevel = DebugMode.Normal;
if (DebugLevel == DebugMode.Normal)
{
/// Open serial port: 9600 Bd, 8 data bits, 1 stop bit, no parity
try
{
CloseOptoSerialPort();
optoSerialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBit);
optoSerialPort.Handshake = handshake;
optoSerialPort.Open();
log.FatalFormat($"{Name} OptoPort opened: {this}");
}
catch (Exception ex)
{
log.FatalFormat($"{Name} OptoPort - error opening port: {this}" + Environment.NewLine + ex.Message);
throw ex;
}
}
else
if (DebugLevel != DebugMode.Normal)
{
optoSerialPort = null;
log.FatalFormat($"{Name} OproPort simulated: {this}");
return;
}
try
{
CloseOptoSerialPort();
var port = new SerialPort(comPort, baudRate, parity, dataBits, stopBit)
{
Handshake = handshake,
NewLine = "\r\n",
Encoding = Encoding.ASCII
};
port.ReadTimeout = 5000;
port.WriteTimeout = 5000;
port.DtrEnable = true;
port.RtsEnable = true;
// Run Open() on separate task
var openTask = Task.Run(() => port.Open());
if (!openTask.Wait(openTimeoutMs))
{
port.Dispose();
throw new TimeoutException(
$"Opening serial port {comPort} timed out after {openTimeoutMs} ms.");
}
optoSerialPort = port;
log.FatalFormat($"{Name} OptoPort opened: {this}");
}
catch (Exception ex)
{
log.FatalFormat($"{Name} OptoPort - error opening port: {this}"
+ Environment.NewLine + ex.Message);
throw; // NEVER use "throw ex;" (destroys stack trace)
}
}
@@ -937,7 +972,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
try
{
OpenOptoSerialPort($"COM{iperlHeadCfg.OptoComPortNr}", 9600, Parity.None, 8, StopBits.One, Handshake.None);
OpenOptoSerialPort($"COM{iperlHeadCfg.OptoComPortNr}", 38400, Parity.None, 8, StopBits.One, Handshake.None);
}
catch (Exception)
{
@@ -961,18 +996,6 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
dataStreamState = DataStreamState.ProcessAndSave;
}
public void SetCommunicationInterface(string commInterface)
{
CommunicationInterface com = (CommunicationInterface)Enum.Parse(typeof(CommunicationInterface), commInterface);
SetCommunicationInterface(com);
}
public void SetCommunicationInterface(RegisterReaders.CommonRR.CommunicationInterface commInterface)
{
CommunicationInterface com = (CommunicationInterface)Enum.Parse(typeof(CommunicationInterface), commInterface.ToDescription());
SetCommunicationInterface(com);
}
/// <summary>
/// Returns true when processing and saving datastream data is in progress
/// </summary>
@@ -981,11 +1004,6 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
return dataStreamState == DataStreamState.ProcessAndSave;
}
void ISmartReader.SetRfidInterface()
{
SetRfidInterface();
}
/// <summary>
/// Stop processing and saving datastream data
/// </summary>
@@ -1001,121 +1019,95 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
bool synchronized;
bool synchronized2;
string partOfTelegram;
private RegisterReaders.CommonRR.CommunicationInterface _commInterface;
private string _commInterface1;
DiagnosticLedParser parser = new DiagnosticLedParser(DiagnosticLedState.State4);
/// <summary>
/// Reads opto-datastream via serial port. Invoked from RunDeviceBefore()
///
/// Telegram description:
/// AAAAAA[tab]BBBB[tab]CCCC[tab]DDDDDD[tab]EEEE[tab]FFFFFFFF[tab]GG[cr][lf] (42 bytes)
/// Example:
/// FFFFFE 51EA 0000 65324E 0087 F6319DFF 86
/// FFDD3A 51F9 0000 65324E 0088 F631A60B 45
/// ...
/// </summary>
/// <param name="optoState">OptoState.Read or OptoState.Flush</param>
void ReadOptoData(DataStreamState optoState)
{
/// Telegram description:
/// AAAAAA[tab]BBBB[tab]CCCC[tab]DDDDDD[tab]EEEE[tab]FFFFFFFF[tab]GG[cr][lf] (42 bytes)
/// Example:
/// FFFFFE 51EA 0000 65324E 0087 F6319DFF 86
/// FFDD3A 51F9 0000 65324E 0088 F631A60B 45
/// ...
/// </summary>
/// <param name="optoState">OptoState.Read or OptoState.Flush</param>
void ReadOptoData(DataStreamState optoState)
{
if (optoSerialPort is null) return;
lock (this)
{
int nrBytes = optoSerialPort.BytesToRead;
if (nrBytes > 0)
try
{
char[] buffer = new char[nrBytes];
optoSerialPort.Read(buffer, 0, nrBytes);
string received = new string(buffer);
string allRcvd = partOfTelegram + received;
while (true)
int nrBytes = optoSerialPort.BytesToRead;
if (nrBytes > 0)
{
int pos = allRcvd.IndexOf("\r\n");
// This will now wait max 3 seconds (ReadTimeout)
string line = optoSerialPort.ReadLine();
if (pos < 0)
byte[] bytes = optoSerialPort.Encoding.GetBytes(line);
log.Debug("ComPort: " + OptoComPortNr + " OPTHO RX ← " + HexFormatter.ToSerialHex(bytes));
if (optoState == DataStreamState.ProcessAndSave)
{
/// No CR+LF found, wait for more characters in the next invocation
partOfTelegram = allRcvd;
return;
DiagnosticLedState4Data data =
(DiagnosticLedState4Data)parser.ParseLine(line, false);
int bufferIx = BufferIdx(optoDataCount);
if (synchronized)
{
optoData[bufferIx].Counter = optoDataCount;
optoData[bufferIx].SetFlags(OptoTelegramFlags.SyncError);
}
if (data != null)
{
log.Debug($"OPTHO {OptoComPortNr} Parsed optho data:" + data);
logStream.Debug($"ID: {OptoComPortNr} " + data);
optoData[bufferIx].UpdateFromSmart(
data,
optoDataCount,
Convert.ToSingle(Sequences.ProcessData.RefFlow.Val),
ref volumeRawExtLast,
ref timestampExtLast);
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
OptoTelegramReceived(
optoDataCount,
true,
volumeRawExtLast,
timestampExtLast);
}
optoDataCount++;
}
else
{
/// CR+LF found
if (optoState == DataStreamState.ProcessAndSave)
{
int bufferIx = BufferIdx(optoDataCount);
// Flush mode
DiagnosticLedState4Data data =
(DiagnosticLedState4Data)parser.ParseLine(line, false);
if (pos < OptoTelegramRaw.Length - 2)
{
/// CR+LF found too early, truncate the beginning incl CR+LF and keep scanning in this loop
allRcvd = allRcvd.Substring(pos + 2);
if (synchronized)
{
optoData[bufferIx].Counter = optoDataCount;
optoData[bufferIx].SetFlags(OptoTelegramFlags.SyncError);
}
synchronized = true;
}
else if (optoData[bufferIx].UpdateFromString(allRcvd.Substring(pos - OptoTelegramRaw.Length + 2),
optoDataCount,
Convert.ToSingle(Sequences.ProcessData.RefFlow.Val),
ref volumeRawExtLast, ref timestampExtLast))
{
/// CR+LF was found && (pos >= OptoTelegramRaw.Length - 2) && the telegram is OK
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
OptoTelegramReceived(optoDataCount, synchronized2, volumeRawExtLast, timestampExtLast);
synchronized2 = synchronized;
allRcvd = allRcvd.Substring(pos + 2);
}
else
{
/// CR+LF was found && (pos >= OptoTelegramRaw.Length - 2) but the telgram was not OK
optoData[bufferIx].Counter = optoDataCount;
optoDataCount++;
allRcvd = allRcvd.Substring(pos + 2);
}
optoDataCount++;
}
else /// optoState == OptoState.Flush
{
if (pos < OptoTelegramRaw.Length - 2)
{
/// CR+LF found too early, truncate the beginning incl CR+LF and keep scanning in this loop
allRcvd = allRcvd.Substring(pos + 2);
synchronized = true;
}
// CR+LF found and (pos >= OptoTelegram.Length - 2)
else if (toBeFlushed.UpdateFromString(allRcvd.Substring(pos - OptoTelegramRaw.Length + 2),
0,
Convert.ToSingle(Sequences.ProcessData.RefFlow.Val),
ref volumeRawExtLast, ref timestampExtLast))
{
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
synchronized2 = synchronized;
allRcvd = allRcvd.Substring(pos + 2);
}
else
{
allRcvd = allRcvd.Substring(pos + 2);
}
}
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
}
}
//OnOptoReceived(this, new OptoReceivedEventArgs(s));
}
else
catch (TimeoutException)
{
//OnOptoReceived(this, new OptoReceivedEventArgs("."));
// ✅ No data received within 3 seconds
log.Debug($"OPTHO {OptoComPortNr} ReadLine timeout (3s) - continuing.");
// Just continue without parsing
}
catch (Exception ex)
{
log.Error($"OPTHO {OptoComPortNr} Read error: {ex.Message}");
}
}
}
void ISmartReader.ResetNfcInterface(bool? nfc_on)
{
ResetNfcInterface(nfc_on);
}
public string ReadOptoData()
@@ -1124,48 +1116,114 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
string received = ".";
lock (this)
{
int nrBytes = optoSerialPort.BytesToRead;
if (nrBytes > 0)
try
{
char[] buffer = new char[nrBytes];
optoSerialPort.Read(buffer, 0, nrBytes);
received = new string(buffer);
string line = optoSerialPort.ReadLine(); // string
byte[] bytes = optoSerialPort.Encoding.GetBytes(line);
received = HexFormatter.ToSerialHex(bytes);
log.Debug("RX ← " + received);
}
catch (TimeoutException)
{
// ✅ No data received within 3 seconds
log.Debug($"ReadOptoData() OPTHO {OptoComPortNr} ReadLine timeout (3s) - continuing.");
// Just continue without parsing
}
catch (Exception ex)
{
log.Error($"ReadOptoData() OPTHO {OptoComPortNr} Read error: {ex.Message}");
}
}
return received;
}
void ISmartReader.SetNfcInterface()
public async Task<string> ReadOptoDataWithTimeoutAsync(int timeoutMs = 5000)
{
SetNfcInterface();
if (optoSerialPort == null)
return string.Empty;
var readTask = Task.Run(() =>
{
lock (this)
{
if (optoSerialPort== null) return string.Empty;
try
{
string line = optoSerialPort.ReadLine();
byte[] bytes = optoSerialPort.Encoding.GetBytes(line);
string received = HexFormatter.ToSerialHex(bytes);
log.Debug("RX ← " + received);
return line;
}
catch (TimeoutException)
{
// ✅ No data received within 3 seconds
log.Debug($"ReadOptoData() OPTHO {OptoComPortNr} ReadLine timeout (3s) - continuing.");
// Just continue without parsing
}
catch (Exception ex)
{
log.Error($"ReadOptoData() OPTHO {OptoComPortNr} Read error: {ex.Message}");
}
return string.Empty;
}
});
var completedTask = await Task.WhenAny(readTask, Task.Delay(timeoutMs));
if (completedTask == readTask)
{
return await readTask; // completed successfully
}
log.Debug("ReadOptoData timeout after " + timeoutMs + " ms");
return string.Empty; // timeout case
}
public string ReadOptoDataWithTimeout(int timeoutMs = 5000)
{
try
{
return ReadOptoDataWithTimeoutAsync(timeoutMs)
.GetAwaiter()
.GetResult();
}
catch
{
return string.Empty;
}
}
void OptoTelegramReceived(int currentIx, bool async, Int64 volumeRawExt, Int64 timestampRawExt)
void OptoTelegramReceived(int currentIx, bool async, double volumeRawExt, double timestampRawExt)
{
currentTelegramIx = currentIx;
lastVolumeRaw = volumeRawExt;
lastTimestamp = timestampRawExt;
if (volumeLtr == 0 && volumeLtr0 == 0)
if (Double.IsNaN(volumeLtr) && Double.IsNaN(volumeLtr0))
{
volumeLtr = (double)lastVolumeRaw * ScalingFactor() / 16000.0;
volumeLtr = lastVolumeRaw;
volumeLtr0 = volumeLtr;
}
else
{
volumeLtr = (double)lastVolumeRaw * ScalingFactor() / 16000.0;
volumeLtr = lastVolumeRaw;
}
if (timestampSec == 0 && timestampSec0 == 0)
if (Double.IsNaN(timestampSec)&& Double.IsNaN(timestampSec0))
{
timestampSec = (double)lastTimestamp / 8192.0;
timestampSec = lastTimestamp;
timestampSec0 = timestampSec;
}
else
{
timestampSec = (double)lastTimestamp / 8192.0;
timestampSec = lastTimestamp;
}
}
@@ -1270,25 +1328,55 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
/// <returns>Filtered volume</returns>
double VolumeFromSamples(OptoTelegramRaw[] optoData, int optoDataCount, int unwrappedIx, double scalingFactor, int samplesCount2 = 0)
{
log.Debug("-- Get VolumeFromSamples() --");
if (samplesCount2 == 0)
{
if (unwrappedIx >= optoDataCount)
{
log.Debug(
$"-- FAILED VolumeFromSamples() - unwrappedIx {unwrappedIx} >= optoDataCount{optoDataCount}--");
return 0;
}
int wrappedIx = BufferIdx(unwrappedIx);
if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
{
log.Debug($"-- Get VolumeFromSamples() - Quit because:{optoData[wrappedIx].Flags}--");
return 0;
}
log.Debug($"Valid data VolumeRawExt: {optoData[wrappedIx].VolumeRawExt}");
return optoData[wrappedIx].VolumeRawExt;
}
//TODO BUMI - do result as average from data - usually 5 samples
if (samplesCount2 < 0) samplesCount2 = 0;
if ((unwrappedIx - samplesCount2) < 0 || (unwrappedIx + samplesCount2) >= optoDataCount) return 0;
Int64 sum = 0;
double sum = 0;
for (int i = unwrappedIx - samplesCount2; i <= unwrappedIx + samplesCount2; i++)
{
int wrappedIx = BufferIdx(i);
if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
{
return 0;
}
sum += optoData[wrappedIx].VolumeRawExt;
}
return 0.0000625 * scalingFactor * sum / (double)(2 * samplesCount2 + 1);
return sum / (double)(2 * samplesCount2 + 1);
//return 0.0000625 * scalingFactor * sum / (double)(2 * samplesCount2 + 1);
}
/// <summary>
@@ -1299,25 +1387,45 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
/// <returns>Filtered time</returns>
double TimeFromSamples(OptoTelegramRaw[] optoData, int optoDataCount, int unwrappedIx, int samplesCount2 = 0)
{
if (samplesCount2 < 0) samplesCount2 = 0;
if ((unwrappedIx - samplesCount2) < 0 || (unwrappedIx + samplesCount2) >= optoDataCount) return 0;
Int64 sum = 0;
for (int i = unwrappedIx - samplesCount2; i <= unwrappedIx + samplesCount2; i++)
log.Debug("-- Get TimeFromSamples() --");
if (unwrappedIx >= optoDataCount)
{
int wrappedIx = BufferIdx(i);
if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
{
return 0;
}
sum += optoData[wrappedIx].TimestampExt;
log.Debug(
$"-- FAILED TimeFromSamples() - unwrappedIx {unwrappedIx} >= optoDataCount{optoDataCount}--");
return 0;
}
int wrappedIx = BufferIdx(unwrappedIx);
return sum / (double)(8192 * (2 * samplesCount2 + 1));
if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
{
log.Debug($"-- Get TimeFromSamples() - Quit because:{optoData[wrappedIx].Flags}--");
return 0;
}
log.Debug($"Valid data TimestampExt: {optoData[wrappedIx].TimestampExt}");
return optoData[wrappedIx].TimestampExt;
// if (samplesCount2 < 0) samplesCount2 = 0;
// if ((unwrappedIx - samplesCount2) < 0 || (unwrappedIx + samplesCount2) >= optoDataCount) return 0;
//
// Int64 sum = 0;
// for (int i = unwrappedIx - samplesCount2; i <= unwrappedIx + samplesCount2; i++)
// {
// int wrappedIx = BufferIdx(i);
//
// if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
// optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
// optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
// {
// return 0;
// }
//
// sum += optoData[wrappedIx].TimestampExt;
// }
//
// return sum / (double)(8192 * (2 * samplesCount2 + 1));
}
/// <summary>
@@ -1536,5 +1644,204 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
return this;
}
public async Task<string> DataEntry_ReadSerialNumber()
{
log.Debug("called DataEntry_ReadSerialNumber()");
if (!string.IsNullOrEmpty(SerialNr)) return SerialNr;
//need to find serial number
SerialNr = await DataEntry_ReadSerialNumberAsync();
return SerialNr;
}
public Task<double> DataEntry_ReadBeginVolume()
{
log.Debug("called DataEntry_ReadBeginVolumer()");
Task<double> readedVolume = DataEntry_BeginVolumeAsync();
return readedVolume;
}
public Task<double> DataEntry_ReadEndVolume()
{
log.Debug("called DataEntry_ReadBeginVolumer()");
Task<double> readedVolume = DataEntry_EndVolumeAsync();
return readedVolume;
}
public async Task<double> DataEntry_EndVolumeAsync()
{
if (optoSerialPort == null || !optoSerialPort.IsOpen)
{
StartDataStreamProcessing();
if (optoSerialPort == null || !optoSerialPort.IsOpen)
{
log.Error($"optoSerialPort COM: {this.OptoComPortNr} is not open - DataEntry_EndVolumeAsync()");
return Double.NaN;
}
}
return await Task.Run(() =>
{
log.Debug($"Try get End Volume! COM: {this.OptoComPortNr}");
volumeLtr = Double.NaN;
int counter = 0;
while (Double.IsNaN(volumeLtr) && counter < 2)
{
counter++;
try
{
string readOptoDataWithTimeout = ReadOptoDataWithTimeout(2000);
if (!string.IsNullOrEmpty(readOptoDataWithTimeout))
{
try
{
DiagnosticLedState4Data data =
(DiagnosticLedState4Data)parser.ParseLine(readOptoDataWithTimeout, false);
volumeLtr = data.RawVolume;
break;
}
catch (Exception ex)
{
log.Warn($"Parsing DiagnosticLedState4Data: {ex.Message}");
}
}
}
catch (Exception ex)
{
break;
}
}
log.Debug($"Try get End Volume! COM: {this.OptoComPortNr}, Volume: {volumeLtr}");
if (optoSerialPort != null && optoSerialPort.IsOpen) CloseOptoSerialPort();
if (!Double.IsNaN(volumeLtr))
{
endWMState = volumeLtr;
if (!Double.IsNaN(beginWMState) && !Double.IsNaN(endWMState))
{
//Solve roll over
if (endWMState < beginWMState)
{
log.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 = endWMState;
ReadPulses();
log.Debug($"Solve roll over! Upgraded endWMState: {endWMState}, beginWMState: {beginWMState}");
}
}
return endWMState;
}
//}
log.Warn("Default NaN value returned! Data Opto stream reading failed!");
return Double.NaN;
}).ConfigureAwait(false);
}
public async Task<double> DataEntry_BeginVolumeAsync()
{
if (ConfigStruct == null)
{
log.Debug("ConfigStruct is null - created new in ReadSerialNr()");
ConfigStruct = new ConfigStruct();
}
return await Task.Run(() =>
{
log.Debug($"Try get Start Volume! COM: {this.OptoComPortNr}");
Start();
volumeLtr0 = Double.NaN;
int counter = 0;
while (Double.IsNaN(volumeLtr0) && counter < 10)
{
counter++;
try
{
string readOptoDataWithTimeout = ReadOptoDataWithTimeout(5000);
if (!string.IsNullOrEmpty(readOptoDataWithTimeout))
{
try
{
DiagnosticLedState4Data data =
(DiagnosticLedState4Data)parser.ParseLine(readOptoDataWithTimeout, false);
volumeLtr0 = data.RawVolume;
break;
}
catch (Exception ex)
{
log.Warn($"Parsing DiagnosticLedState4Data: {ex.Message}");
}
}
}
catch (Exception ex)
{
break;
}
}
log.Debug($"Try get Start Volume! COM: {this.OptoComPortNr}, Volume: {volumeLtr0}");
if (optoSerialPort != null && optoSerialPort.IsOpen) CloseOptoSerialPort();
if (!Double.IsNaN(volumeLtr0))
{
beginWMState = volumeLtr0;
ReadPulses();
return beginWMState;
}
//}
log.Warn("Default NaN value returned! Data Opto stream reading failed!");
return Double.NaN;
}).ConfigureAwait(false);
}
public async Task<string> DataEntry_ReadSerialNumberAsync()
{
if (!string.IsNullOrEmpty(SerialNr))
return SerialNr;
if (ConfigStruct == null)
{
log.Debug("ConfigStruct is null - created new in ReadSerialNr()");
ConfigStruct = new ConfigStruct();
}
if (CommFailed || ConfigStruct == null)
return CommErr.CommFailed.ToString();
return await Task.Run(() =>
{
log.Debug($"Try get ReadSerialNr! COM: {this.RfidComPortNr}");
if (OptoHeadTest.ReadSerialNr())
{
SerialNr = this.ConfigStruct.PCBNumberString;
log.Debug("ReadSerialNr successful");
}
//optoHeadTest.CloseConnection();
return SerialNr;
});
}
}
}
@@ -3,7 +3,7 @@ using System.Threading;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using TBF.Rig.Sequences;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
using TBF.Rig.TestMethods.iPerlCommunication.communication;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
@@ -22,7 +22,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
InitializeComponent();
if (config == null) return;
SmartCommunicationForm.TestMethodCfg = new TestMethodCfg_IPerl(null); // default values for iPerlCommunication
iPerlCommunicationForm.cfg = new TestMethodCfg(null); // default values for iPerlCommunication
foreach(var head in ProcessData.IperlHeads)
{
@@ -78,14 +78,16 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
using (Tools.LogChecker logChecker = new Tools.LogChecker("RfidData", log4net.Core.Level.Debug))
{
ListItem rfidListItem = new ListItem();
rfidListItem.Attributes.Add("style", "font-weight:bold");
rfidListItem.Attributes.Add("style", "font-volume:bold");
//rfidListItem.Attributes.Add("style", "font-weight:bold");
bool isTestModeSuccessful = false;
switch (rfidCommandComboBox.SelectedValue)
{
case "ReadPCB":
rfidListItem.Text = $"PCB: {OpticalHeadTest.ReadRequest_PCB(iPerlHead)}";
rfidListItem.Text = $"PCB: {iPerlHead.OptoHeadTest.ReadRequest_PCB()}";
break;
case "SetTestMode":
rfidListItem.Text = OpticalHeadTest.SetTestMode(iPerlHead);
rfidListItem.Text = iPerlHead.OptoHeadTest.SetTestMode(ref isTestModeSuccessful);
optoListBox.Items.Clear();
stopWorkerThread = false;
optoThread = new Thread(OptoWorker);
@@ -96,7 +98,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
}
break;
case "SetActiveMode":
rfidListItem.Text = OpticalHeadTest.SetActiveMode(iPerlHead);
rfidListItem.Text = iPerlHead.OptoHeadTest.SetActiveMode(ref isTestModeSuccessful);
stopWorkerThread = true;
iPerlHead.StopDataStreamProcessing(); // close opto port
break;
@@ -1,4 +1,4 @@
using log4net;
using log4net;
using Sensus.iPerl.NfcHandler;
using Sensus.iPerl.RfidCom.Exceptions;
using System;
@@ -12,9 +12,9 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
internal class NfcServices
{
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
internal static int ReadRequest(TestMethodCfg_IPerl cfgIPerl, IperlHead iperlHead, MCI_Protocol.StructName structName, int offset, int length, out byte[] buffer)
internal static int ReadRequest(TestMethodCfg cfg, IperlHead iperlHead, MCI_Protocol.StructName structName, int offset, int length, out byte[] buffer)
{
for (int i = 0; i < cfgIPerl.MaxCommRetries; i++)
for (int i = 0; i < cfg.MaxCommRetries; i++)
{
NfcDataHandler _nfcDataHandler = new NfcDataHandler();
@@ -26,9 +26,9 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
try
{
rfidDataLogger.Info($"NFC COM{iperlHead.RfidComPortNr} ReadRequest : {structName}, {offset}, {length}");
OpenConnection(_nfcDataHandler, cfgIPerl, iperlHead);
OpenConnection(_nfcDataHandler, cfg, iperlHead);
buffer = MciRead(_nfcDataHandler, cfgIPerl, structName, (ushort)offset, length);
buffer = MciRead(_nfcDataHandler, cfg, structName, (ushort)offset, length);
_nfcDataHandler.RFProtocolOFF(); // turn off rf antenna due to possible interference
CloseComPort(_nfcDataHandler);
@@ -44,7 +44,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
}
catch (RfidValidationException)
{
Thread.Sleep(cfgIPerl.WaitTimeAfterFailure);
Thread.Sleep(cfg.WaitTimeAfterFailure);
}
catch (Exception ex)
{
@@ -57,7 +57,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
return 3;
}
internal static int WriteRequest(TestMethodCfg_IPerl cfgIPerl, IperlHead iperlHead, MCI_Protocol.StructName structName, int offset, int length, byte[] buffer)
internal static int WriteRequest(TestMethodCfg cfg, IperlHead iperlHead, MCI_Protocol.StructName structName, int offset, int length, byte[] buffer)
{
NfcDataHandler _nfcDataHandler = new NfcDataHandler();
MessageEventHandlers(_nfcDataHandler);
@@ -68,9 +68,9 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
try
{
rfidDataLogger.Info($"NFC COM{iperlHead.RfidComPortNr} WriteRequest : {structName}, {offset}, {length}, {ByteArrayToHexString(buffer)}");
OpenConnection(_nfcDataHandler, cfgIPerl, iperlHead);
OpenConnection(_nfcDataHandler, cfg, iperlHead);
MciWrite(_nfcDataHandler, cfgIPerl, structName, (ushort)offset, length, buffer);
MciWrite(_nfcDataHandler, cfg, structName, (ushort)offset, length, buffer);
_nfcDataHandler.RFProtocolOFF(); // turn off rf antenna due to possible interference
CloseComPort(_nfcDataHandler);
@@ -83,14 +83,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
}
}
private static void OpenConnection(NfcDataHandler nfcDataHandler, TestMethodCfg_IPerl cfgIPerl, IperlHead iperlHead)
private static void OpenConnection(NfcDataHandler nfcDataHandler, TestMethodCfg cfg, IperlHead iperlHead)
{
string comPort = $"COM{iperlHead.RfidComPortNr}";
int retryCount = 0 ;
Open:
nfcDataHandler.Close();
Thread.Sleep(100);
if (nfcDataHandler.OpenConnection(comPort, cfgIPerl.BaudRate, cfgIPerl.DataBits, cfgIPerl.ParityBit, cfgIPerl.StopBits))
if (nfcDataHandler.OpenConnection(comPort, cfg.BaudRate, cfg.DataBits, cfg.ParityBit, cfg.StopBits))
{
rfidDataLogger.Info($"NFC COM{iperlHead.RfidComPortNr} Port Open");
@@ -100,7 +100,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
if (!nfcDataHandler.ConnectDevice())
{
rfidDataLogger.Error($"NFC COM{iperlHead.RfidComPortNr} Error connect device.");
for (int i = 0; i < cfgIPerl.MaxCommRetries; i++)
for (int i = 0; i < cfg.MaxCommRetries; i++)
{
if (nfcDataHandler.Echo()) break;
}
@@ -110,7 +110,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
retryCount++;
rfidDataLogger.Error($"NFC COM{iperlHead.RfidComPortNr} Error connect reader. Reconnect comport {retryCount}");
if (retryCount < cfgIPerl.MaxCommRetries)
if (retryCount < cfg.MaxCommRetries)
{
nfcDataHandler.Close();
iperlHead.ResetNfcInterface(); // reset NFC head via optoport - switch to RFID and back to NFC interface
@@ -127,7 +127,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
nfcDataHandler.Close();
}
private static byte[] MciRead(NfcDataHandler nfcDataHandler, TestMethodCfg_IPerl cfgIPerl, StructName structName, ushort offset, int length)
private static byte[] MciRead(NfcDataHandler nfcDataHandler, TestMethodCfg cfg, StructName structName, ushort offset, int length)
{
bool isReadValues = false;
int retryCount = 0;
@@ -153,14 +153,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
rfidDataLogger.Info($"MCI Error: Unidentified");
retryCount++;
if (retryCount < cfgIPerl.MaxCommRetries)
if (retryCount < cfg.MaxCommRetries)
goto Read;
}
else
{
rfidDataLogger.Info("Last error message: " + nfcDataHandler.LastErrorMessage);
retryCount++;
if (retryCount < cfgIPerl.MaxCommRetries)
if (retryCount < cfg.MaxCommRetries)
goto Read;
}
}
@@ -168,13 +168,13 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
rfidDataLogger.Error("MciRead Last error message: " + ex.Message);
retryCount++;
if (retryCount < cfgIPerl.MaxCommRetries)
if (retryCount < cfg.MaxCommRetries)
goto Read;
}
return new byte[length];
}
private static void MciWrite(NfcDataHandler nfcDataHandler, TestMethodCfg_IPerl cfgIPerl, MCI_Protocol.StructName structName, ushort offset, int length, byte[] payload)
private static void MciWrite(NfcDataHandler nfcDataHandler, TestMethodCfg cfg, MCI_Protocol.StructName structName, ushort offset, int length, byte[] payload)
{
int retryCount = 0;
Write:
@@ -199,7 +199,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
rfidDataLogger.Error("MciWrite error message: " + ex.Message);
retryCount++;
if (retryCount < cfgIPerl.MaxCommRetries)
if (retryCount < cfg.MaxCommRetries)
goto Write;
}
}
@@ -149,16 +149,16 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
return pars;
}
public override bool UpdateFromDbEntity(ComponentProcedure dbEntity)
{
if (dbEntity == null) return false;
try
{
ProcParams tmp = Serializer.Deserialize(new StringReader(dbEntity.Parameters)) as ProcParams;
public override bool UpdateFromDbEntity(ComponentProcedure dbEntity)
{
if (dbEntity == null) return false;
try
{
ProcParams tmp = Serializer.Deserialize(new StringReader(dbEntity.Parameters)) as ProcParams;
procedureParamsEntity = dbEntity;
componentName = dbEntity.CmpntName;
procedure = dbEntity.Procedure;
procedureParamsEntity = dbEntity;
componentName = dbEntity.CmpntName;
procedure = dbEntity.Procedure;
if (tmp != null)
{
@@ -181,7 +181,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
}
}
public ProcParams()
public ProcParams()
{
}
@@ -1,29 +1,28 @@
using Sensus.iPerl.RfidCom.Exceptions;
using Sensus.iPerl.RfidCom.Exceptions;
using Sensus.iPerl.RfidCom.Helper;
using Sensus.iPerl.RfidCom;
using System;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
internal class RfidServices
{
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
private static readonly ILog log = LogManager.GetLogger(typeof(SmartCommunicationForm));
private static readonly ILog log = LogManager.GetLogger(typeof(iPerlCommunicationForm));
internal static int ReadRequest(TestMethodCfg_IPerl cfgIPerl, IperlHead iperlHead, MessageID messageID, int offset, int length, out byte[] buffer)
internal static int ReadRequest(TestMethodCfg cfg, IperlHead iperlHead, MessageID messageID, int offset, int length, out byte[] buffer)
{
for (int i = 0; i < cfgIPerl.MaxCommRetries; i++)
for (int i = 0; i < cfg.MaxCommRetries; i++)
{
rfidDataLogger.Error($"{iperlHead.CommInterface} Start {i} reading: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},{offset}, {length}... timeout {cfgIPerl.CommTimeout})");
rfidDataLogger.Error($"{iperlHead.CommInterface} Start {i} reading: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},{offset}, {length}... timeout {cfg.CommTimeout})");
using (RfidLogic writer = new RfidLogic($"COM{iperlHead.RfidComPortNr}"))
{
try
{
byte[] response = writer.ReadRequest((byte)messageID, offset, length, cfgIPerl.CommTimeout);
byte[] response = writer.ReadRequest((byte)messageID, offset, length, cfg.CommTimeout);
string hexString = RfidHelper.ConvertByteArrayToHexString(response);
string swapHexString = RfidHelper.SwapHexcode(hexString);
string decString = RfidHelper.HexLiteral2Unsigned(RfidHelper.SwapHexcode(hexString)).ToString();
@@ -57,42 +56,42 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
if (/*RfidHelper.IsPassThrough(messageID)*/ messageID == MessageID.ASICRegisterReadTest || messageID == MessageID.RadioPassthrough)
{
rfidDataLogger.Info($"COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...) {(i > 0 ? "<- Error: Invalid Pass-Through data." : "<- Info: Wait for Pass-Through data.")}");
Thread.Sleep(cfgIPerl.PassThroughWaitTime);
Thread.Sleep(cfg.PassThroughWaitTime);
}
else
{
Thread.Sleep(cfgIPerl.WaitTimeAfterFailure);
Thread.Sleep(cfg.WaitTimeAfterFailure);
}
}
catch (RfidValidationException)
{
Thread.Sleep(cfgIPerl.WaitTimeAfterFailure);
Thread.Sleep(cfg.WaitTimeAfterFailure);
}
catch (Exception ex)
{
rfidDataLogger.Error($"COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...) {ex.Message}");
Thread.Sleep(cfgIPerl.WaitTimeAfterFailure);
Thread.Sleep(cfg.WaitTimeAfterFailure);
}
}
}
rfidDataLogger.Error($"{iperlHead.CommInterface} reading failed after {cfgIPerl.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...)");
log.Error($"{iperlHead.CommInterface} reading failed after {cfgIPerl.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...)");
rfidDataLogger.Error($"{iperlHead.CommInterface} reading failed after {cfg.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...)");
log.Error($"{iperlHead.CommInterface} reading failed after {cfg.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...)");
buffer = new byte[length];
return 3;
}
internal static int WriteRequest(TestMethodCfg_IPerl cfgIPerl, IperlHead iperlHead, MessageID messageID, int offset, int length, byte[] buffer)
internal static int WriteRequest(TestMethodCfg cfg, IperlHead iperlHead, MessageID messageID, int offset, int length, byte[] buffer)
{
RfidLogic writer = new RfidLogic($"COM{iperlHead.RfidComPortNr}");
string payload = RfidHelper.ConvertByteArrayToHexString(buffer);
for (var i = 0; i < cfgIPerl.MaxCommRetries; i++)
for (var i = 0; i < cfg.MaxCommRetries; i++)
{
rfidDataLogger.Error($"{iperlHead.CommInterface} Start {i} writting: COM{iperlHead.RfidComPortNr}: WriteRequest ({messageID},{offset}, {length}, {payload}... timeout {cfgIPerl.CommTimeout})");
rfidDataLogger.Error($"{iperlHead.CommInterface} Start {i} writting: COM{iperlHead.RfidComPortNr}: WriteRequest ({messageID},{offset}, {length}, {payload}... timeout {cfg.CommTimeout})");
try
{
if (writer.ClosePort()) writer.OpenPort();
writer.WriteRequest((byte)messageID, offset, length, buffer, cfgIPerl.CommTimeout, false);
writer.WriteRequest((byte)messageID, offset, length, buffer, cfg.CommTimeout, false);
writer.ClosePort();
rfidDataLogger.InfoFormat($"{iperlHead.Name}({iperlHead.SerialNr},COM{iperlHead.RfidComPortNr}): WriteRequestPort({messageID}, {offset}, {length}, {payload})");
return 0;
@@ -106,7 +105,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
else
{
rfidDataLogger.Error($"COM{iperlHead.RfidComPortNr}: Error: {ex.Message}");
Thread.Sleep(cfgIPerl.WaitTimeAfterFailure);
Thread.Sleep(cfg.WaitTimeAfterFailure);
if (i > 1)
{
rfidDataLogger.Error($"COM{iperlHead.RfidComPortNr}: Reopen the com port.");
@@ -116,8 +115,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
}
}
writer.ClosePort();
rfidDataLogger.Error($"RFID writing failed after {cfgIPerl.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: WriteRequestPort ({messageID},...) {System.Text.Encoding.UTF8.GetString(buffer)}");
log.Error($"RFID writing failed after {cfgIPerl.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: WriteRequestPort ({messageID},...) {System.Text.Encoding.UTF8.GetString(buffer)}");
rfidDataLogger.Error($"RFID writing failed after {cfg.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: WriteRequestPort ({messageID},...) {System.Text.Encoding.UTF8.GetString(buffer)}");
log.Error($"RFID writing failed after {cfg.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: WriteRequestPort ({messageID},...) {System.Text.Encoding.UTF8.GetString(buffer)}");
return 2;
}
}
@@ -1,5 +1,8 @@
using System;
using System.IO;
using System.Linq;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
@@ -7,11 +10,34 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
const int Q2CorrFactorsAddr = 0x1878;
internal static int ReadRequest(TestMethodCfg_IPerl cfgIPerl, IperlHead iperlHead, MessageID messageID, int offset, int length, out byte[] buffer)
internal static int ReadRequest(TestMethodCfg cfg, IperlHead iperlHead, MessageID messageID, int offset, int length, out byte[] buffer)
{
byte[] configurationBuffer = new byte[ConfigStruct.Length] { 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 160, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
string pcbStr = iperlHead.RfidComPortNr.ToString().PadRight(10,'0') + iperlHead.Position.ToString("D2");
long decVal = Convert.ToInt64(pcbStr);
string nHexStr = decVal.ToString("X4");
ConfigStruct configStruct = new ConfigStruct();
configStruct.PCBNumberString = nHexStr;
configStruct.StatusMode = ProtocolStatuses.Active;
configStruct.OpthoStatusMode = DiagnosticLedState.State4;
configStruct.Version = "Good Version: 123456";
byte[] configurationBuffer;
using (var ms = new MemoryStream())
using (var writer = new BinaryWriter(ms))
{
configStruct.WriteBinary(writer);
writer.Flush();
configurationBuffer = ms.ToArray(); // ← this is the binary output
}
byte[] calibrationBuffer = new byte[CalibrationStructV4.Length] { 3, 0, 150, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 150, 10 };
buffer = new byte[length];
return 0;//switch off
if (messageID == MessageID.Configuration)
{
@@ -34,7 +60,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
return iperlHead.Name.Equals("iPerl13") ? 2 : 0; /// Simulates an error on position 13
}
internal static int WriteRequest(TestMethodCfg_IPerl cfgIPerl, IperlHead iperlHead, MessageID messageID, int offset, int length, byte[] buffer)
internal static int WriteRequest(TestMethodCfg cfg, IperlHead iperlHead, MessageID messageID, int offset, int length, byte[] buffer)
{
return 0;
}