Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bcb33cde78 | ||
|
|
8229c5eb63 | ||
|
|
6dc9520897 | ||
|
|
90cd53b05f | ||
|
|
aa0d775b8e | ||
|
|
2b3eb5f10a | ||
|
|
010bc7131a | ||
|
|
e22a0767f4 | ||
|
|
66b43350cc |
@@ -29,5 +29,5 @@ using System.Runtime.InteropServices;
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
[assembly: AssemblyVersion("3.9.2147.1")]
|
||||
[assembly: AssemblyFileVersion("3.9.2147.1")]
|
||||
[assembly: AssemblyVersion("3.9.2201.1")]
|
||||
[assembly: AssemblyFileVersion("3.9.2201.1")]
|
||||
|
||||
@@ -8,6 +8,7 @@ using System.IO;
|
||||
using System.IO.Ports;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using log4net;
|
||||
using Common;
|
||||
using Config.Entities;
|
||||
@@ -526,6 +527,17 @@ namespace TBF.Rig.ControlBoard.Uni
|
||||
Bridge.OnStateMachineTick(this, new StateMachineTickEventArgs(route, ProcessData.MsrmntAvailableFlags, ProcessData.MeasuredValues,
|
||||
ProcessData.AltStrings, ProcessData.Setpoints, ProcessData.CustomBitmaps));
|
||||
|
||||
/// Make simulation to finish - count
|
||||
if (cbCfg.DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(5000);
|
||||
Data.State |= (ulong)StatusP.TestCompleted;
|
||||
log.Debug("Simulation StatusP.TestCompleted in background.");
|
||||
});
|
||||
}
|
||||
|
||||
/// Make sure the serial port is open
|
||||
if (cbCfg.DebugLevel == DebugMode.Normal && (serialPort == null || !serialPort.IsOpen))
|
||||
{
|
||||
|
||||
@@ -607,6 +607,11 @@ namespace TBF.Rig.TestMethods.FlyingStart
|
||||
meterRslt.VolumeRef = tstRslt.VolumeCTV * meterRslt.TestTime / tstRslt.TestTime;
|
||||
meterRslt.PulsesMaster = tstRslt.PulsesMaster * meterRslt.TestTime / tstRslt.TestTime;
|
||||
|
||||
log.Debug($"TEST TIME meterRslt.TimestampStart:{meterRslt.TimestampStart}, meterRslt.TimestampEnd:{meterRslt.TimestampEnd}, meterRslt.TestTime:{meterRslt.TestTime}");
|
||||
log.Debug($"TEST VOLUME meterRslt.VolumeStart:{meterRslt.VolumeStart}, meterRslt.VolumeEnd:{meterRslt.VolumeEnd}, meterRslt.VolumeMeter:{meterRslt.VolumeMeter}");
|
||||
log.Debug($"TEST modified by time: meterRslt.VolumeRef:{meterRslt.VolumeRef}, meterRslt.PulsesMaster:{meterRslt.PulsesMaster}");
|
||||
|
||||
|
||||
if (iPerl != null)
|
||||
{
|
||||
if (iPerl.ResultCode != 0 && (meterRslt.WaterMeter.ResultCode & (int)Results.Entities.ResultCode.OptoErrorCodeMask) == 0)
|
||||
|
||||
@@ -635,7 +635,18 @@ namespace TBF.Rig.TestMethods.FlyingStartMassCollection
|
||||
while (!e.Contains(Event.ScaleDone) && !e.Contains(Event.Next));
|
||||
///
|
||||
tMass2 = StateMachine.Time;
|
||||
log.WarnFormat("End mass = {0}kg", EndMass);
|
||||
try
|
||||
{
|
||||
if (EndMass != null)
|
||||
{
|
||||
log.WarnFormat("End mass = {0}kg", EndMass.Val);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
log.ErrorFormat("Error while logging end mass: {0}", ex.Message);
|
||||
}
|
||||
|
||||
TestEndTime = DateTime.Now;
|
||||
|
||||
if (test.DoDrainingAfter)
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
///
|
||||
/// 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) --------
|
||||
const double TS_TICKS_PER_SEC = 4096.0;
|
||||
const double TS_RANGE = (1UL << 32) / TS_TICKS_PER_SEC;
|
||||
//const double TS_HALF = TS_RANGE / 2.0;
|
||||
|
||||
// -------- VOLUME (liters) --------
|
||||
const double GAL_TO_LITER = 3.785411784;
|
||||
const double VOL_LITERS_PER_TICK =
|
||||
(4.0 / 1000.0) / GAL_TO_LITER / 2.0;
|
||||
|
||||
const double VOL_RANGE = (1 << 24) * VOL_LITERS_PER_TICK;
|
||||
//const double VOL_HALF = VOL_RANGE / 2.0;
|
||||
|
||||
//New IPERL ASIC
|
||||
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 = data.AsicTimestamp;
|
||||
|
||||
// ---------- VOLUME UNWRAP ----------
|
||||
double uncorrected = VolumeRaw;
|
||||
|
||||
if (double.IsNaN(volumeRawExtLast))
|
||||
{
|
||||
VolumeRawExt = volumeRawExtLast = uncorrected;
|
||||
}
|
||||
else
|
||||
{
|
||||
double k = Math.Round((volumeRawExtLast - uncorrected) / VOL_RANGE);
|
||||
VolumeRawExt = volumeRawExtLast = uncorrected + k * VOL_RANGE;
|
||||
}
|
||||
|
||||
// ---------- TIMESTAMP UNWRAP ----------
|
||||
uncorrected = Timestamp;
|
||||
|
||||
if (double.IsNaN(timestampExtLast))
|
||||
{
|
||||
TimestampExt = timestampExtLast = uncorrected;
|
||||
}
|
||||
else
|
||||
{
|
||||
double k = Math.Round((timestampExtLast - uncorrected) / TS_RANGE);
|
||||
TimestampExt = timestampExtLast = uncorrected + k * TS_RANGE;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+132
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+10
@@ -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
|
||||
}
|
||||
}
|
||||
+15
@@ -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;
|
||||
}
|
||||
}
|
||||
+94
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+75
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+100
@@ -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,
|
||||
}
|
||||
}
|
||||
+114
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+89
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+104
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+111
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+152
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+155
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+11
@@ -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
|
||||
}
|
||||
|
||||
}
|
||||
+11
@@ -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
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -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";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -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(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
+140
@@ -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,
|
||||
}
|
||||
}
|
||||
+203
@@ -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
|
||||
}
|
||||
}
|
||||
+13
@@ -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
|
||||
}
|
||||
}
|
||||
+27
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+125
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+63
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+10
@@ -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
|
||||
}
|
||||
}
|
||||
+34
@@ -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,328 @@
|
||||
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;
|
||||
}
|
||||
|
||||
private void CloseConnection()
|
||||
{
|
||||
if (serialDriver != null)
|
||||
serialDriver.CloseConnection();
|
||||
serialDriver = null;
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
{
|
||||
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 && 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)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
|
||||
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,296 @@
|
||||
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 SerialDriver serialDriver;
|
||||
public RadioService(SerialDriver 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);
|
||||
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, 2000);
|
||||
if (rawData == null)
|
||||
return false;
|
||||
|
||||
|
||||
// parse rawData
|
||||
var parser = new IperlHatFrameParser();
|
||||
IperlHatResponse decoded = parser.Parse(rawData);
|
||||
log.Debug("SetActivityMode_Idle isOK: " + decoded.IsOk);
|
||||
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);
|
||||
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);
|
||||
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,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
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -24,7 +24,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
|
||||
|
||||
public override void InitializeAll()
|
||||
{
|
||||
Activity = "Read Configuration";
|
||||
Activity = iPerlCommunicationForm.ReadConfigurationStr;
|
||||
SimultWithPrevious = false;
|
||||
SimultWithNext = false;
|
||||
}
|
||||
|
||||
@@ -3,264 +3,165 @@
|
||||
///
|
||||
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>
|
||||
|
||||
/// <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;
|
||||
}
|
||||
// public bool Update(int offset, )
|
||||
// {
|
||||
//
|
||||
// /// 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]);
|
||||
// PCBNumberString
|
||||
// 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 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);
|
||||
writer.Write(0x11); // mark new type of verison
|
||||
// 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);
|
||||
|
||||
writer.Write((byte)StatusMode);
|
||||
|
||||
byte[] PCBNumberStringBytes = Encoding.UTF8.GetBytes(PCBNumberString);
|
||||
// 1) write length
|
||||
writer.Write(PCBNumberStringBytes.Length);
|
||||
// 2) write string bytes
|
||||
writer.Write(PCBNumberStringBytes);
|
||||
|
||||
// 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);
|
||||
|
||||
}
|
||||
|
||||
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();
|
||||
int ReadBytesCount = 0;
|
||||
// ---- Test Data type ----
|
||||
var readByte = reader.ReadByte();
|
||||
if (readByte != 0x11) return; // not correct version
|
||||
ReadBytesCount++;
|
||||
// ---- Version ----
|
||||
// 1) read length
|
||||
int length = reader.ReadInt32();
|
||||
ReadBytesCount += 4 + length;
|
||||
// 2) read string bytes
|
||||
byte[] versionBytes = reader.ReadBytes(length);
|
||||
// 3) convert back to string
|
||||
Version = Encoding.UTF8.GetString(versionBytes);
|
||||
// ---- PCB Number ----
|
||||
// 1) read length
|
||||
int lengthPCB = reader.ReadInt32();
|
||||
ReadBytesCount += 4 + lengthPCB;
|
||||
// 2) read string bytes
|
||||
byte[] bytesPCB = reader.ReadBytes(lengthPCB);
|
||||
// 3) convert back to string
|
||||
PCBNumberString = Encoding.UTF8.GetString(bytesPCB);
|
||||
// ---- Unit ----
|
||||
// 1) read length
|
||||
int lengthUnit = reader.ReadInt32();
|
||||
ReadBytesCount += 4 + lengthUnit;
|
||||
// 2) read string bytes
|
||||
byte[] bytesUnit = reader.ReadBytes(lengthUnit);
|
||||
// 3) convert back to string
|
||||
Unit = Encoding.UTF8.GetString(bytesUnit);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,17 +6,22 @@ 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.Xml;
|
||||
using System.Xml.Linq; // This line is correct and does not need to be changed.
|
||||
using System.Windows;
|
||||
using System.Text;
|
||||
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;
|
||||
|
||||
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
{
|
||||
@@ -26,6 +31,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
public class IperlHead : ComponentBase, IDevice,IRegReaderDatastream, ISessionDataMngmnt, IOperation
|
||||
{
|
||||
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
|
||||
@@ -39,6 +45,19 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
public const int StartEndFilterSamplesCount2 = 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;
|
||||
|
||||
@@ -101,8 +120,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
/// <summary>
|
||||
/// Passed to OptoTelegramRaw.UpdateFromString(...)
|
||||
/// </summary>
|
||||
Int64 volumeRawExtLast;
|
||||
Int64 timestampExtLast;
|
||||
double volumeRawExtLast;
|
||||
double timestampExtLast;
|
||||
|
||||
FlowDirectionDetection flowDirectionDetection;
|
||||
|
||||
@@ -358,7 +377,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
///
|
||||
/// Timestamp from the opto telegram
|
||||
///
|
||||
private Int64 lastTimestamp;
|
||||
private double lastTimestamp;
|
||||
private double timestampSec;
|
||||
private double timestampSec0;
|
||||
|
||||
@@ -381,7 +400,7 @@ 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;
|
||||
|
||||
@@ -442,7 +461,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}");
|
||||
}
|
||||
@@ -587,10 +606,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;
|
||||
|
||||
@@ -856,6 +875,7 @@ 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;
|
||||
}
|
||||
@@ -865,12 +885,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
if (DebugLevel == DebugMode.FailureDuringOperation) DebugLevel = DebugMode.Normal;
|
||||
if (DebugLevel == DebugMode.Normal)
|
||||
{
|
||||
/// Open serial port: 9600 Bd, 8 data bits, 1 stop bit, no parity
|
||||
/// Open serial port: 38400 Bd, 8 data bits, 1 stop bit, no parity
|
||||
try
|
||||
{
|
||||
CloseOptoSerialPort();
|
||||
optoSerialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBit);
|
||||
optoSerialPort.Handshake = handshake;
|
||||
optoSerialPort.NewLine = "\r\n";
|
||||
optoSerialPort.Encoding = Encoding.ASCII; // or UTF8 if needed
|
||||
optoSerialPort.Open();
|
||||
log.FatalFormat($"{Name} OptoPort opened: {this}");
|
||||
}
|
||||
@@ -906,7 +928,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)
|
||||
{
|
||||
@@ -954,6 +976,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
bool synchronized2;
|
||||
string partOfTelegram;
|
||||
|
||||
DiagnosticLedParser parser = new DiagnosticLedParser(DiagnosticLedState.State4);
|
||||
/// <summary>
|
||||
/// Reads opto-datastream via serial port. Invoked from RunDeviceBefore()
|
||||
///
|
||||
@@ -973,86 +996,66 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
int nrBytes = optoSerialPort.BytesToRead;
|
||||
if (nrBytes > 0)
|
||||
{
|
||||
char[] buffer = new char[nrBytes];
|
||||
optoSerialPort.Read(buffer, 0, nrBytes);
|
||||
string received = new string(buffer);
|
||||
string line = optoSerialPort.ReadLine(); // string
|
||||
byte[] bytes = optoSerialPort.Encoding.GetBytes(line);
|
||||
|
||||
log.Debug("ComPort: "+ OptoComPortNr +" OPTHO RX ← " + HexFormatter.ToSerialHex(bytes));
|
||||
|
||||
string allRcvd = partOfTelegram + received;
|
||||
|
||||
while (true)
|
||||
try
|
||||
{
|
||||
int pos = allRcvd.IndexOf("\r\n");
|
||||
/// CR+LF found
|
||||
if (optoState == DataStreamState.ProcessAndSave)
|
||||
{
|
||||
DiagnosticLedState4Data data = (DiagnosticLedState4Data)parser.ParseLine(line, false);
|
||||
//DiagnostigLedDataByUnit unitData = new DiagnostigLedDataByUnit(Common.Unit.m3, Common.Unit.m3, data);
|
||||
int bufferIx = BufferIdx(optoDataCount);
|
||||
|
||||
if (pos < 0)
|
||||
{
|
||||
/// No CR+LF found, wait for more characters in the next invocation
|
||||
partOfTelegram = allRcvd;
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
/// CR+LF found
|
||||
if (optoState == DataStreamState.ProcessAndSave)
|
||||
if (synchronized)
|
||||
{
|
||||
int bufferIx = BufferIdx(optoDataCount);
|
||||
optoData[bufferIx].Counter = optoDataCount;
|
||||
optoData[bufferIx].SetFlags(OptoTelegramFlags.SyncError);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
if (data != null)
|
||||
{
|
||||
//TODO BUMI UNITS
|
||||
// apply units
|
||||
log.Debug($"OPTHO {OptoComPortNr} Parsed optho data:" + data.ToString());
|
||||
logStream.Debug($"ID: {OptoComPortNr} " + data.ToString());
|
||||
|
||||
optoData[bufferIx].UpdateFromSmart(data, optoDataCount,
|
||||
Convert.ToSingle(Sequences.ProcessData.RefFlow.Val), ref volumeRawExtLast,
|
||||
ref timestampExtLast);
|
||||
|
||||
log.Debug("OPTHO UpdateFromSmart() volumeRawExtLast:" + volumeRawExtLast + " timestampExtLast:" + timestampExtLast);
|
||||
|
||||
/// CR+LF was found && (pos >= OptoTelegramRaw.Length - 2) && the telegram is OK
|
||||
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
|
||||
OptoTelegramReceived(optoDataCount, true, volumeRawExtLast,
|
||||
timestampExtLast);
|
||||
}
|
||||
else
|
||||
{
|
||||
/// CR+LF was found && (pos >= OptoTelegramRaw.Length - 2) but the telgram was not OK
|
||||
optoData[bufferIx].Counter = optoDataCount;
|
||||
optoDataCount++;
|
||||
}
|
||||
else /// optoState == OptoState.Flush
|
||||
|
||||
optoDataCount++;
|
||||
}
|
||||
else /// optoState == OptoState.Flush
|
||||
{
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
//OnOptoReceived(this, new OptoReceivedEventArgs(s));
|
||||
}
|
||||
@@ -1069,43 +1072,40 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
string received = ".";
|
||||
lock (this)
|
||||
{
|
||||
int nrBytes = optoSerialPort.BytesToRead;
|
||||
if (nrBytes > 0)
|
||||
{
|
||||
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);
|
||||
}
|
||||
return received;
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1210,25 +1210,50 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
/// <returns>Filtered volume</returns>
|
||||
double VolumeFromSamples(OptoTelegramRaw[] optoData, int optoDataCount, int unwrappedIx, double scalingFactor, 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 VolumeFromSamples() --");
|
||||
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].VolumeRawExt;
|
||||
log.Debug(
|
||||
$"-- FAILED VolumeFromSamples() - unwrappedIx {unwrappedIx} >= optoDataCount{optoDataCount}--");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int wrappedIx = BufferIdx(unwrappedIx);
|
||||
|
||||
return 0.0000625 * scalingFactor * sum / (double)(2 * samplesCount2 + 1);
|
||||
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;
|
||||
|
||||
|
||||
|
||||
//
|
||||
// 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].VolumeRawExt;
|
||||
// }
|
||||
//
|
||||
// return 0.0000625 * scalingFactor * sum / (double)(2 * samplesCount2 + 1);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1239,25 +1264,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>
|
||||
@@ -1476,5 +1521,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Threading;
|
||||
using System.Web.UI.WebControls;
|
||||
using System.Windows.Forms;
|
||||
using TBF.Rig.Sequences;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication;
|
||||
|
||||
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
{
|
||||
@@ -78,13 +79,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
{
|
||||
ListItem rfidListItem = new ListItem();
|
||||
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);
|
||||
@@ -95,7 +97,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,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
|
||||
{
|
||||
@@ -9,9 +12,32 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
|
||||
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)
|
||||
{
|
||||
|
||||
+51
-6
@@ -39,7 +39,7 @@
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>TRACE;DEBUG;CAMERA;LANG_PL</DefineConstants>
|
||||
<DefineConstants>TRACE;DEBUG;CAMERA;LANG_PL;IPERL</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
@@ -50,7 +50,7 @@
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;CAMERA;LANG_PL</DefineConstants>
|
||||
<DefineConstants>TRACE;CAMERA;LANG_PL;IPERL</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
@@ -60,7 +60,7 @@
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>TRACE;DEBUG;CAMERA;LANG_PL</DefineConstants>
|
||||
<DefineConstants>TRACE;DEBUG;CAMERA;LANG_PL;IPERL</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
@@ -70,7 +70,7 @@
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
||||
<OutputPath>bin\x86\Release\</OutputPath>
|
||||
<DefineConstants>TRACE;CAMERA;LANG_PL</DefineConstants>
|
||||
<DefineConstants>TRACE;CAMERA;LANG_PL;IPERL</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
@@ -110,8 +110,8 @@
|
||||
<Reference Include="Iesi.Collections">
|
||||
<HintPath>..\packages\Iesi.Collections.4.0.0.4000\lib\net40\Iesi.Collections.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
|
||||
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="mscorlib" />
|
||||
<Reference Include="MySql.Data">
|
||||
@@ -1444,6 +1444,51 @@
|
||||
<SubType>Component</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\CommCompletedEventArgs.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\common\OptoTelegramRaw.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\DiagnosticLedParser.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\DiagnosticLedState.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedData.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedFrameSpec.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedState1Data.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedState2Data.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedState3Data.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedState4Data.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedState5Data.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedState6Data.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\DiagnosticLedState7Data.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\PipeStatus.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\parserer\SpikeDetectionStatus.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\utils\DiagnosticChecksum.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\utils\DiagnosticHex.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\diagnosticLed\utils\DiagnostigLedDataByUnit.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\hexLogger\HexFormatter.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\hexLogger\IpelHatCommandDecoder.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\hexLogger\IperlHatLogger.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\hexLogger\TouchReadControlDecoder.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\hexLogger\TouchReadLogger.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\IperlHatProtocol\IperlHatProtocolConstants.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\IperlHatProtocol\IperlHatFrame.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\IperlHatProtocol\IperlHatFrameBuilder.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\IperlHatProtocol\IperlHatFrameParser.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\IperlHatProtocol\IperlHatProtocol.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\IperlHatProtocol\IperlHatResponse.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\led\ITouchReadLedParser.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\led\ShortVariableLedParser.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\led\TouchReadLedData.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\led\TouchReadLedMessage.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\protocolCommons\ProtocolCommand.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\protocolCommons\ProtocolDeviceSubCommand.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\protocolCommons\ProtocolStatuses.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\wiredProtocol\TouchReadFrame.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\wiredProtocol\TouchReadFrameBuilder.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\wiredProtocol\TouchReadFrameParser.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\wiredProtocol\TouchReadProtocol.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\C4\wiredProtocol\TouchReadResponse.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\OpthoHeadService.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\OptoHeadTest.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\RadioService.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\Utils\SerialDriver.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\communication\Utils\SerialDriverBuilder.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\iPerlCommunicationForm.cs">
|
||||
<SubType>Form</SubType>
|
||||
</Compile>
|
||||
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.IperlHatProtocol
|
||||
{
|
||||
[TestClass]
|
||||
public class IperlHatFrameBuilderTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Encode_ViewFactoryId_Command()
|
||||
{
|
||||
byte[] frame = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.ViewFactoryId)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected =
|
||||
{
|
||||
IperlHatProtocolConstants.Start, // START
|
||||
IperlHatProtocolConstants.Write, // DIRECTION
|
||||
0x05, // LEN
|
||||
(byte)ProtocolCommand.ViewFactoryId, // COMMAND
|
||||
IperlHatProtocolConstants.End // END
|
||||
};
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_VERS_Command()
|
||||
{
|
||||
byte[] frame = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.Question)
|
||||
.AddPayload(IperlHatProtocolConstants.Version)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected = HexFormatter.HexStringToByteArray("53 57 3F 76 65 72 73 0D");
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_VERS2_Command()
|
||||
{
|
||||
byte[] frame = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.SetVersionCommand()
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected = HexFormatter.HexStringToByteArray("53 57 3F 76 65 72 73 0D");
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_ViewProgrammableId_Command()
|
||||
{
|
||||
byte[] frame = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.ViewProgrammableId)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected = HexFormatter.HexStringToByteArray("53 57 05 03 0D");
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_ViewState_Command()
|
||||
{
|
||||
byte[] frame = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.ViewState)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected = HexFormatter.HexStringToByteArray("53 57 05 19 0D");
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_SetState_Idle_Command()
|
||||
{
|
||||
byte[] frame = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.SetState)
|
||||
.AddSubCommand(ProtocolStatuses.Idle) // Idle
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected = HexFormatter.HexStringToByteArray("53 57 06 1A 01 0D");
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_SetState_Active_Command()
|
||||
{
|
||||
byte[] frame = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.SetState)
|
||||
.AddSubCommand(ProtocolStatuses.Active) // Active
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected = HexFormatter.HexStringToByteArray("53 57 06 1A 02 0D");
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_SetDiagnosticLEDState_Status4_Command()
|
||||
{
|
||||
// ----------- Arrange -----------
|
||||
byte[] request = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
|
||||
.AddPayload(DiagnosticLedState.State4)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected = HexFormatter.HexStringToByteArray("53 57 07 FD 60 04 0D");
|
||||
|
||||
CollectionAssert.AreEqual(expected, request);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(request);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(request));
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void AddDiagnosticLedState()
|
||||
{
|
||||
// ----------- Arrange -----------
|
||||
byte[] request = new IperlHatFrameBuilder()
|
||||
.AddDiagnosticLedState(DiagnosticLedState.State4)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected = HexFormatter.HexStringToByteArray("53 57 07 FD 60 04 0D");
|
||||
|
||||
CollectionAssert.AreEqual(expected, request);
|
||||
|
||||
string log = IperlHatLogger.DescribeTx(request);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(request));
|
||||
}
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.IperlHatProtocol
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(IperlHatFrameParser))]
|
||||
public class IperlHatFrameParserTest
|
||||
{
|
||||
[TestMethod]
|
||||
public void ParseTest_FactoryID()
|
||||
{
|
||||
IperlHatFrameParser parser = new IperlHatFrameParser();
|
||||
byte[] result1 = HexFormatter.HexStringToByteArray("53 52 0F 01 31 30 30 31 30 34 30 35 31 00 0D");
|
||||
IperlHatResponse iperlHatResponse = parser.Parse(result1);
|
||||
|
||||
Assert.IsNotNull(iperlHatResponse);
|
||||
Assert.IsTrue(iperlHatResponse.IsOk);
|
||||
Assert.IsTrue(iperlHatResponse.Payload.Length > 0);
|
||||
Assert.AreEqual("100104051", iperlHatResponse.GetAsciiPayload());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseTest_VERS()
|
||||
{
|
||||
IperlHatFrameParser parser = new IperlHatFrameParser();
|
||||
byte[] versionResult = HexFormatter.HexStringToByteArray("3F 76 65 72 73 3A 20 48 61 72 72 79 20 54 3A 42 38 30 30 2C 20 56 3A 30 36 2E 30 36 2E 30 31 2C 20 46 57 3A 31 39 30 32 31 35 2C 20 37 45 43 45 2C 20 42 31 2E 36 2E 30 31 2C 20 48 57 3A 34 2C 20 53 65 72 69 61 6C 3A 30 0D");
|
||||
IperlHatResponse iperlHatResponse = parser.Parse(versionResult);
|
||||
|
||||
Assert.IsNotNull(iperlHatResponse);
|
||||
Assert.IsTrue(iperlHatResponse.IsOk);
|
||||
Assert.IsTrue(iperlHatResponse.Payload.Length > 0);
|
||||
Assert.AreEqual(IperlHatProtocolConstants.Question, iperlHatResponse.Control);
|
||||
|
||||
Assert.AreEqual("vers: Harry T:B800, V:06.06.01, FW:190215, 7ECE, B1.6.01, HW:4, Serial:0", iperlHatResponse.GetAsciiPayload());
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void ParseTest_Response_OK ()
|
||||
{
|
||||
IperlHatFrameParser parser = new IperlHatFrameParser();
|
||||
byte[] versionResult = HexFormatter.HexStringToByteArray("53 52 05 01 0D");
|
||||
IperlHatResponse iperlHatResponse = parser.Parse(versionResult);
|
||||
|
||||
Assert.IsNotNull(iperlHatResponse);
|
||||
Assert.IsTrue(iperlHatResponse.IsOk);
|
||||
Assert.AreEqual(null, iperlHatResponse.GetAsciiPayload());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseTest_Response_NOK ()
|
||||
{
|
||||
IperlHatFrameParser parser = new IperlHatFrameParser();
|
||||
byte[] versionResult = HexFormatter.HexStringToByteArray("53 52 05 FD 0D");
|
||||
IperlHatResponse iperlHatResponse = parser.Parse(versionResult);
|
||||
|
||||
Assert.IsNotNull(iperlHatResponse);
|
||||
Assert.IsFalse(iperlHatResponse.IsOk);
|
||||
Assert.AreEqual(null, iperlHatResponse.GetAsciiPayload());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseTest_Response_State ()
|
||||
{
|
||||
IperlHatFrameParser parser = new IperlHatFrameParser();
|
||||
// IDLE
|
||||
byte[] versionResult = HexFormatter.HexStringToByteArray("53 52 06 01 01 0D");
|
||||
IperlHatResponse iperlHatResponse = parser.Parse(versionResult);
|
||||
|
||||
Assert.IsNotNull(iperlHatResponse);
|
||||
Assert.IsFalse(iperlHatResponse.IsOk);
|
||||
|
||||
ProtocolStatuses status = iperlHatResponse.GetResponse<ProtocolStatuses>(out bool isOk);
|
||||
Assert.AreEqual(true, isOk);
|
||||
Assert.AreEqual(ProtocolStatuses.Idle, status);
|
||||
|
||||
//ACTIVE
|
||||
versionResult = HexFormatter.HexStringToByteArray("53 52 06 01 02 0D");
|
||||
iperlHatResponse = parser.Parse(versionResult);
|
||||
|
||||
Assert.IsNotNull(iperlHatResponse);
|
||||
Assert.IsFalse(iperlHatResponse.IsOk);
|
||||
|
||||
status = iperlHatResponse.GetResponse<ProtocolStatuses>(out isOk);
|
||||
Assert.AreEqual(true, isOk);
|
||||
Assert.AreEqual(ProtocolStatuses.Active, status);
|
||||
|
||||
//EndOfLife
|
||||
versionResult = HexFormatter.HexStringToByteArray("53 52 06 01 03 0D");
|
||||
iperlHatResponse = parser.Parse(versionResult);
|
||||
|
||||
Assert.IsNotNull(iperlHatResponse);
|
||||
Assert.IsFalse(iperlHatResponse.IsOk);
|
||||
|
||||
status = iperlHatResponse.GetResponse<ProtocolStatuses>(out isOk);
|
||||
Assert.AreEqual(true, isOk);
|
||||
Assert.AreEqual(ProtocolStatuses.EndOfLife, status);
|
||||
|
||||
//MeterTest
|
||||
versionResult = HexFormatter.HexStringToByteArray("53 52 06 01 04 0D");
|
||||
iperlHatResponse = parser.Parse(versionResult);
|
||||
|
||||
Assert.IsNotNull(iperlHatResponse);
|
||||
Assert.IsFalse(iperlHatResponse.IsOk);
|
||||
|
||||
status = iperlHatResponse.GetResponse<ProtocolStatuses>(out isOk);
|
||||
Assert.AreEqual(true, isOk);
|
||||
Assert.AreEqual(ProtocolStatuses.MeterTest, status);
|
||||
}
|
||||
}
|
||||
}
|
||||
+542
@@ -0,0 +1,542 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Ports;
|
||||
using System.Text;
|
||||
using log4net;
|
||||
using log4net.Appender;
|
||||
using log4net.Layout;
|
||||
using log4net.Repository.Hierarchy;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.IperlHatProtocol
|
||||
{
|
||||
[TestClass]
|
||||
public class IperlHatIntegrationTests
|
||||
{
|
||||
|
||||
public static class LogConfig
|
||||
{
|
||||
public static void Configure()
|
||||
{
|
||||
var hierarchy = (Hierarchy)LogManager.GetRepository();
|
||||
hierarchy.Root.RemoveAllAppenders();
|
||||
|
||||
var patternLayout = new PatternLayout
|
||||
{
|
||||
ConversionPattern = "%date{yyyy-MM-dd HH:mm:ss.fff} [%thread] %-5level %logger - %message%newline"
|
||||
};
|
||||
patternLayout.ActivateOptions();
|
||||
|
||||
var consoleAppender = new ConsoleAppender
|
||||
{
|
||||
Layout = patternLayout
|
||||
};
|
||||
consoleAppender.ActivateOptions();
|
||||
|
||||
hierarchy.Root.AddAppender(consoleAppender);
|
||||
hierarchy.Root.Level = log4net.Core.Level.Debug;
|
||||
hierarchy.Configured = true;
|
||||
}
|
||||
}
|
||||
ILog log = LogManager.GetLogger(typeof(IperlHatIntegrationTests));
|
||||
|
||||
private const string ComPort = "COM3"; // CHANGE THIS
|
||||
private const int BaudRate = 2400;
|
||||
private const int BaudRateOpto = 38400;
|
||||
private const int ReadTimeoutMs = 2000;
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Hardware")]
|
||||
[TestCategory("Serial")]
|
||||
public void Serial_ViewFactoryId_ReadSerialNumber()
|
||||
{
|
||||
// -------- Arrange --------
|
||||
byte[] request = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.ViewFactoryId)
|
||||
.BuildBytes();
|
||||
|
||||
var parser = new IperlHatFrameParser();
|
||||
|
||||
using (var port = new SerialPort(ComPort, BaudRate, Parity.None, 8, StopBits.One))
|
||||
{
|
||||
port.Handshake = Handshake.None;
|
||||
port.ReadTimeout = 5000;
|
||||
port.Open();
|
||||
|
||||
DateTime end = DateTime.Now.AddSeconds(10);
|
||||
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(request));
|
||||
port.Write(request, 0, request.Length);
|
||||
|
||||
Console.WriteLine("Listening for 10 seconds...");
|
||||
byte[] response = null;
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
response = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(response));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
IperlHatResponse iperlHatResponse = parser.Parse(response);
|
||||
|
||||
Assert.IsTrue(iperlHatResponse.IsOk);
|
||||
Assert.IsFalse(iperlHatResponse.Payload.Length < 8);
|
||||
|
||||
Console.WriteLine("\nDone.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Hardware")]
|
||||
[TestCategory("Serial")]
|
||||
public void Serial_SetStatus_Idle_Active()
|
||||
{
|
||||
|
||||
byte[] requestStatus = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.ViewState)
|
||||
.BuildBytes();
|
||||
|
||||
|
||||
|
||||
var parser = new IperlHatFrameParser();
|
||||
|
||||
using (var port = new SerialPort(ComPort, BaudRate, Parity.None, 8, StopBits.One))
|
||||
{
|
||||
port.Handshake = Handshake.None;
|
||||
port.ReadTimeout = 5000;
|
||||
port.Open();
|
||||
|
||||
|
||||
DateTime end = DateTime.Now.AddSeconds(10);
|
||||
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(requestStatus));
|
||||
port.Write(requestStatus, 0, requestStatus.Length);
|
||||
|
||||
Console.WriteLine("Listening for 10 seconds...");
|
||||
byte[] resStart = null;
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
resStart = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(resStart));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
IperlHatResponse iperlHatResponseOld = parser.Parse(resStart);
|
||||
Assert.IsTrue(iperlHatResponseOld.IsOk, "Idle No set!");
|
||||
Console.WriteLine("We start with status: " + HexFormatter.ToHex(iperlHatResponseOld.Payload[0]));
|
||||
//----------------------------------------------------------------
|
||||
|
||||
// -------- Arrange --------
|
||||
byte[] request = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.SetState)
|
||||
.AddSubCommand(ProtocolStatuses.Idle)
|
||||
.BuildBytes();
|
||||
|
||||
// -- set idle
|
||||
end = DateTime.Now.AddSeconds(10);
|
||||
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(request));
|
||||
port.Write(request, 0, request.Length);
|
||||
|
||||
Console.WriteLine("Listening for 10 seconds...");
|
||||
byte[] response = null;
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
response = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(response));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
IperlHatResponse iperlHatResponse = parser.Parse(response);
|
||||
Assert.IsTrue(iperlHatResponse.IsOk, "Idle No set!");
|
||||
//----------------------------------------------------------------
|
||||
|
||||
request = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.SetState)
|
||||
.AddSubCommand(ProtocolStatuses.Active)
|
||||
.BuildBytes();
|
||||
|
||||
end = DateTime.Now.AddSeconds(10);
|
||||
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(request));
|
||||
port.Write(request, 0, request.Length);
|
||||
|
||||
Console.WriteLine("Listening for 10 seconds...");
|
||||
response = null;
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
response = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(response));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
iperlHatResponse = parser.Parse(response);
|
||||
Assert.IsTrue(iperlHatResponse.IsOk, "Idle No set!");
|
||||
//--------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
|
||||
Console.WriteLine("\nDone.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Hardware")]
|
||||
public void Serial_RawSniff()
|
||||
{
|
||||
using (var port = new SerialPort(ComPort, BaudRate, Parity.None, 8, StopBits.One))
|
||||
{
|
||||
port.Handshake = Handshake.None;
|
||||
port.ReadTimeout = 5000;
|
||||
port.Open();
|
||||
|
||||
DateTime end = DateTime.Now.AddSeconds(10);
|
||||
//welcome message
|
||||
byte[] frame = HexFormatter.HexStringToByteArray("53 57 3F 76 65 72 73 0D");
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(frame));
|
||||
port.Write(frame, 0, frame.Length);
|
||||
|
||||
Console.WriteLine("Listening for 10 seconds...");
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] response = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(response));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ",e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
end = DateTime.Now.AddSeconds(10);
|
||||
byte[] frameID = HexFormatter.HexStringToByteArray("53 57 05 01 0D");
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(frameID));
|
||||
port.Write(frameID, 0, frameID.Length);
|
||||
|
||||
Console.WriteLine("Listening for 10 seconds...");
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] response = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(response));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ",e);
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine("\nDone.");
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] ReadResponse(SerialPort port)
|
||||
{
|
||||
var result = new List<byte>();
|
||||
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int value = port.ReadByte(); // blocks until byte or timeout
|
||||
|
||||
if (value < 0)
|
||||
throw new IOException("Serial port returned end of stream.");
|
||||
|
||||
byte b = HexFormatter.ToHexByte(value);
|
||||
result.Add(b);
|
||||
|
||||
// stop when CR received
|
||||
if (b == 0x0D)
|
||||
break;
|
||||
}
|
||||
|
||||
return result.ToArray();
|
||||
}
|
||||
catch (TimeoutException ex)
|
||||
{
|
||||
if (result.Count > 0)
|
||||
return result.ToArray();
|
||||
|
||||
throw new TimeoutException("Timeout reading response from serial port.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Hardware")]
|
||||
public void OptoCommunicationON_ReadOpto_CommunicatonOFF()
|
||||
{
|
||||
//OPEN COMMUNICATION to Iperl Hat
|
||||
|
||||
var parser = new IperlHatFrameParser();
|
||||
|
||||
using (var port = new SerialPort(ComPort, BaudRate, Parity.None, 8, StopBits.One))
|
||||
{
|
||||
port.Handshake = Handshake.None;
|
||||
port.ReadTimeout = 5000;
|
||||
port.Open();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
// ------ Set active mode ------
|
||||
//----------------------------------------------------------------
|
||||
|
||||
byte[] requestStatus = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.SetState)
|
||||
.AddSubCommand(ProtocolStatuses.Active)
|
||||
.BuildBytes();
|
||||
|
||||
DateTime end = DateTime.Now.AddSeconds(10);
|
||||
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(requestStatus));
|
||||
port.Write(requestStatus, 0, requestStatus.Length);
|
||||
|
||||
Console.WriteLine("Set active mode - Listening for 10 seconds...");
|
||||
byte[] resStart = null;
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
resStart = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(resStart));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
IperlHatResponse iperlHatResponseOld = parser.Parse(resStart);
|
||||
Assert.IsTrue(iperlHatResponseOld.IsOk, "Active No set!");
|
||||
//----------------------------------------------------------------
|
||||
// ------ Enable Opto data ------
|
||||
//----------------------------------------------------------------
|
||||
|
||||
// ----------- Arrange -----------
|
||||
byte[] request = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
|
||||
.AddPayload(DiagnosticLedState.State4)
|
||||
.BuildBytes();
|
||||
|
||||
end = DateTime.Now.AddSeconds(10);
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(request));
|
||||
port.Write(request, 0, request.Length);
|
||||
|
||||
Console.WriteLine("Enable Opto data - Listening for 10 seconds...");
|
||||
byte[] response = null;
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
response = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(response));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
IperlHatResponse iperlHatResponse = parser.Parse(response);
|
||||
Assert.IsTrue(iperlHatResponse.IsOk, "Opto data not set!");
|
||||
|
||||
//----------------------------------------------------------------
|
||||
// ------ Test Opto data ------
|
||||
//----------------------------------------------------------------
|
||||
//Now try test opto data
|
||||
Serial_OptoRawSniff();
|
||||
|
||||
//----------------------------------------------------------------
|
||||
// ------ Disable Opto data ------
|
||||
//----------------------------------------------------------------
|
||||
|
||||
// ----------- Arrange -----------
|
||||
request = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
|
||||
.AddPayload(DiagnosticLedState.StateOFF)
|
||||
.BuildBytes();
|
||||
|
||||
end = DateTime.Now.AddSeconds(10);
|
||||
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(request));
|
||||
port.Write(request, 0, request.Length);
|
||||
|
||||
Console.WriteLine("Disable Opto data - Listening for 10 seconds...");
|
||||
response = null;
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
response = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(response));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
iperlHatResponse = parser.Parse(response);
|
||||
Assert.IsTrue(iperlHatResponse.IsOk, "Disabled opto LED not set!");
|
||||
|
||||
//----------------------------------------------------------------
|
||||
// ------ Set Idle mode ------
|
||||
//----------------------------------------------------------------
|
||||
|
||||
// ----------- Arrange -----------
|
||||
request = new IperlHatFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.SetState)
|
||||
.AddSubCommand(ProtocolStatuses.Idle)
|
||||
.BuildBytes();
|
||||
|
||||
end = DateTime.Now.AddSeconds(10);
|
||||
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHexWithAscii(request));
|
||||
port.Write(request, 0, request.Length);
|
||||
|
||||
Console.WriteLine("Set Idle mode - Listening for 10 seconds...");
|
||||
response = null;
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
response = ReadResponse(port);
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHexWithAscii(response));
|
||||
break;
|
||||
}
|
||||
catch (TimeoutException e)
|
||||
{
|
||||
Assert.Fail("Timeout: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
iperlHatResponse = parser.Parse(response);
|
||||
Assert.IsTrue(iperlHatResponse.IsOk, "Idle status not set!");
|
||||
|
||||
//----------------------------------------------------------------
|
||||
// ------ Test finished ------
|
||||
//----------------------------------------------------------------
|
||||
Console.WriteLine("\nDone.");
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This test work only if Opto data are active
|
||||
/// Use OptoCommunicationON_ReadOpto_CommunicatonOFF() test method
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
[TestCategory("Hardware")]
|
||||
public void Serial_OptoRawSniff_Standalone()
|
||||
{
|
||||
Serial_OptoRawSniff();
|
||||
}
|
||||
|
||||
//method test connection to optho head
|
||||
private void Serial_OptoRawSniff()
|
||||
{
|
||||
using (var port = new SerialPort("COM15", BaudRateOpto, Parity.None, 8, StopBits.One))
|
||||
{
|
||||
port.Handshake = Handshake.None;
|
||||
port.ReadTimeout = 10000;
|
||||
|
||||
// 🔑 CRLF handling
|
||||
port.NewLine = "\r\n";
|
||||
port.Encoding = Encoding.ASCII; // or UTF8 if needed
|
||||
|
||||
port.Open();
|
||||
|
||||
Console.WriteLine("Listening for 10 seconds...");
|
||||
DateTime end = DateTime.Now.AddSeconds(10);
|
||||
|
||||
var parser = new DiagnosticLedParser(DiagnosticLedState.State4);
|
||||
|
||||
while (DateTime.Now < end)
|
||||
{
|
||||
try
|
||||
{
|
||||
string line = port.ReadLine(); // string
|
||||
byte[] bytes = port.Encoding.GetBytes(line);
|
||||
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHex(bytes));
|
||||
|
||||
try
|
||||
{
|
||||
var data = (DiagnosticLedState4Data)parser.ParseLine(line,false);
|
||||
Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] Time: Parsed: {data}");
|
||||
log.Info("Parsed: " + data);
|
||||
}catch(Exception e)
|
||||
{
|
||||
Console.WriteLine("Failed to parse: " + e.Message);
|
||||
}
|
||||
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Assert.Fail("Serial read timeout");
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine("\nDone.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(DiagnosticLedParser))]
|
||||
public class DiagnosticLedParserTest
|
||||
{
|
||||
private static string WithChecksum(string bodyWithoutChecksum)
|
||||
{
|
||||
byte sum = 0;
|
||||
foreach (char c in bodyWithoutChecksum)
|
||||
sum += (byte)c;
|
||||
|
||||
return bodyWithoutChecksum + sum.ToString("X2") + "\r\n";
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_DiagnosticLed_State1()
|
||||
{
|
||||
string body =
|
||||
"FFFF9C\t" + // signed 24-bit ADC = -100
|
||||
"2020\t" + // field strength
|
||||
"FFFA\t" + // raw flow (-6)
|
||||
"0050FC\t" + // raw volume
|
||||
"0054\t"; // capacitor mV
|
||||
|
||||
string line = WithChecksum(body);
|
||||
|
||||
var parser = new DiagnosticLedParser(DiagnosticLedState.State1);
|
||||
var data = (DiagnosticLedState1Data)parser.ParseLine(line);
|
||||
|
||||
Assert.AreEqual(-100, data.Adc24);
|
||||
Assert.AreEqual((ushort)0x2020, data.FieldStrength);
|
||||
Assert.AreEqual((short)-6, data.RawFlow);
|
||||
Assert.AreEqual((uint)0x0050FC, data.RawVolume);
|
||||
Assert.AreEqual((ushort)0x0054, data.CapacitorMv);
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_DiagnosticLed_State2()
|
||||
{
|
||||
string line =
|
||||
"00004F\t029A\t0000\tFFD3B1\t005C\t3B9AC9B1\t02\t01\t0D\r\n";
|
||||
|
||||
var parser = new DiagnosticLedParser(DiagnosticLedState.State2);
|
||||
var data = (DiagnosticLedState2Data)parser.ParseLine(line);
|
||||
|
||||
Assert.AreEqual(79, data.Adc24);
|
||||
Assert.AreEqual((ushort)666, data.FieldStrength);
|
||||
Assert.AreEqual((short)0, data.RawFlow);
|
||||
Assert.AreEqual(0xFFD3B1u, data.RawVolume);
|
||||
Assert.AreEqual((ushort)92, data.CapacitorMv);
|
||||
Assert.AreEqual(0x3B9AC9B1u, data.LcdVolume);
|
||||
Assert.AreEqual((byte)0x02, data.MeterState);
|
||||
Assert.IsTrue(data.IsLowFlowCutoff);
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_DiagnosticLed_State3()
|
||||
{
|
||||
string body =
|
||||
"FFCC09\t2020\tFFFA\t0050FC\t0054\t0B01\t048000\tA7\t";
|
||||
|
||||
string line = WithChecksum(body);
|
||||
|
||||
var parser = new DiagnosticLedParser(DiagnosticLedState.State3);
|
||||
var data = (DiagnosticLedState3Data)parser.ParseLine(line);
|
||||
|
||||
Assert.AreEqual(-13303, data.Adc24);
|
||||
Assert.AreEqual((ushort)0x2020, data.FieldStrength);
|
||||
Assert.AreEqual((short)-6, data.RawFlow);
|
||||
Assert.AreEqual((uint)0x0050FC, data.RawVolume);
|
||||
Assert.AreEqual((ushort)0x0054, data.CapacitorMv);
|
||||
Assert.AreEqual((ushort)0x0B01, data.FieldCalibration);
|
||||
Assert.AreEqual((uint)0x048000, data.AsicTimestamp);
|
||||
Assert.AreEqual((byte)0xA7, data.FieldDriveTimeUs);
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_DiagnosticLed_State4()
|
||||
{
|
||||
string body =
|
||||
"000ABC\t2020\tFFFA\t0050FC\t0054\t0B01\t048000\tA7\t" +
|
||||
"00001234\t00F0\t00F1\t0100\t0200\t03\t";
|
||||
|
||||
string line = WithChecksum(body);
|
||||
|
||||
var parser = new DiagnosticLedParser(DiagnosticLedState.State4);
|
||||
var data = (DiagnosticLedState4Data)parser.ParseLine(line);
|
||||
|
||||
Assert.AreEqual(2748, data.Adc24);
|
||||
Assert.AreEqual((ushort)0x2020, data.FieldStrength);
|
||||
Assert.AreEqual((short)-6, data.RawFlow);
|
||||
Assert.AreEqual((uint)0x0050FC, data.RawVolume);
|
||||
Assert.AreEqual((ushort)0x0054, data.CapacitorMv);
|
||||
|
||||
Assert.AreEqual((ushort)0x0B01, data.FieldCalibration);
|
||||
Assert.AreEqual((uint)0x048000, data.AsicTimestamp);
|
||||
Assert.AreEqual((byte)0xA7, data.FieldDriveTimeUs);
|
||||
|
||||
Assert.AreEqual(0x00001234, data.MeanFlowRate);
|
||||
Assert.AreEqual((ushort)0x00F0, data.Field1Measurement);
|
||||
Assert.AreEqual((ushort)0x00F1, data.Field2Measurement);
|
||||
Assert.AreEqual((ushort)0x0100, data.IntegratorCalibrationPositive);
|
||||
Assert.AreEqual((ushort)0x0200, data.IntegratorCalibrationNegative);
|
||||
Assert.AreEqual((byte)0x03, data.AsicState);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_DiagnosticLed_State5()
|
||||
{
|
||||
string body =
|
||||
"FFCC09\t2020\tFFFA\t0050FC\t0054\t0B01\t048000\tA7\t" +
|
||||
"00001234\t00F0\t00F1\t0100\t0200\t03\tFFEC\t";
|
||||
|
||||
string line = WithChecksum(body);
|
||||
|
||||
var parser = new DiagnosticLedParser(DiagnosticLedState.State5);
|
||||
var data = (DiagnosticLedState5Data)parser.ParseLine(line);
|
||||
|
||||
Assert.AreEqual((short)-20, data.WaterImpedance);
|
||||
Assert.AreEqual((byte)0x03, data.AsicState);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_DiagnosticLed_State6()
|
||||
{
|
||||
string body =
|
||||
"FFCC09\t2020\tFFFA\t0050FC\t0054\t0B01\t048000\tA7\t" +
|
||||
"00001234\t00F0\t00F1\t0100\t0200\t03\tFFEC\t0010\t" +
|
||||
"02\t" + // pp spike detection
|
||||
"02\t" + // ll pipe status
|
||||
"00000099\t" + // LCD volume
|
||||
"01\t"; // ASIC state1
|
||||
|
||||
|
||||
string line = WithChecksum(body);
|
||||
|
||||
var parser = new DiagnosticLedParser(DiagnosticLedState.State6);
|
||||
var data = (DiagnosticLedState6Data)parser.ParseLine(line);
|
||||
|
||||
Assert.AreEqual((short)-20, data.WaterImpedance);
|
||||
Assert.AreEqual((short)0x0010, data.ElectrodeDeltaMv);
|
||||
Assert.AreEqual((byte)0x02, data.SpikeDetection);
|
||||
Assert.AreEqual((byte)0x02, data.PipeStatus);
|
||||
Assert.AreEqual((uint)0x99, data.LcdVolume);
|
||||
Assert.AreEqual((byte)0x01, data.AsicState1);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_DiagnosticLed_State7()
|
||||
{
|
||||
string body =
|
||||
"FFCC09\t2020\tFFFA\t0050FC\t0054\t0B01\t048000\tA7\t" +
|
||||
"00001234\t00F0\t00F1\t0100\t0200\t03\tFFEC\t0010\t" +
|
||||
"02\t" + // pp spike detection
|
||||
"02\t" + // ll pipe status
|
||||
"00000099\t" + // LCD volume
|
||||
"01\t" + // ASIC state1
|
||||
"FFAA10\t" + // raw ADC before offset
|
||||
"000123\t" + // detrended ADC
|
||||
"FFEE\t" + // imaginary water impedance
|
||||
"0011\t" + // electrode voltage noise
|
||||
"03\t"; // ADC offset learning status
|
||||
|
||||
string line = WithChecksum(body);
|
||||
|
||||
var parser = new DiagnosticLedParser(DiagnosticLedState.State7);
|
||||
var data = (DiagnosticLedState7Data)parser.ParseLine(line);
|
||||
|
||||
Assert.AreEqual(-22000, data.RawAdcBeforeOffset);
|
||||
Assert.AreEqual(0x000123, data.DetrendedAdc);
|
||||
Assert.AreEqual((short)-18, data.ImaginaryWaterImpedance);
|
||||
Assert.AreEqual((ushort)0x0011, data.ElectrodeVoltageNoise);
|
||||
Assert.AreEqual((byte)0x03, data.AdcOffsetLearningStatus);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.hexLogger
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(HexFormatter))]
|
||||
public class HexFormatterTest
|
||||
{
|
||||
|
||||
// -----------------------------
|
||||
// ToHex(byte)
|
||||
// -----------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void ToHex_FormatsSingleByte()
|
||||
{
|
||||
var result = HexFormatter.ToHex(0x0D);
|
||||
Assert.AreEqual("0x0D", result);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// ToHex(byte[])
|
||||
// -----------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void ToHex_FormatsByteArray()
|
||||
{
|
||||
byte[] data = { 0x01, 0x0D, 0xFF };
|
||||
var result = HexFormatter.ToHex(data);
|
||||
|
||||
Assert.AreEqual("0x01 0x0D 0xFF", result);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ToHex_EmptyArray_ReturnsEmptyMarker()
|
||||
{
|
||||
var result = HexFormatter.ToHex(Array.Empty<byte>());
|
||||
Assert.AreEqual("<empty>", result);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ToHex_Null_ReturnsEmptyMarker()
|
||||
{
|
||||
var result = HexFormatter.ToHex(null);
|
||||
Assert.AreEqual("<empty>", result);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// ToSerialHex(byte[])
|
||||
// -----------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void ToSerialHex_FormatsCorrectly()
|
||||
{
|
||||
byte[] data = { 0x0D, 0x04, 0x08, 0x01, 0x00, 0x1A };
|
||||
var result = HexFormatter.ToSerialHex(data);
|
||||
|
||||
Assert.AreEqual("0D 04 08 01 00 1A", result);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ToSerialHex_Empty_ReturnsEmptyString()
|
||||
{
|
||||
var result = HexFormatter.ToSerialHex(Array.Empty<byte>());
|
||||
Assert.AreEqual(string.Empty, result);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// ToHexWithAscii(byte)
|
||||
// -----------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void ToHexWithAscii_PrintableAscii()
|
||||
{
|
||||
var result = HexFormatter.ToHexWithAscii(0x41); // 'A'
|
||||
Assert.AreEqual("0x41 ('A')", result);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ToHexWithAscii_ControlChar()
|
||||
{
|
||||
var result = HexFormatter.ToHexWithAscii(0x0D); // CR
|
||||
Assert.AreEqual("0x0D ('.')", result);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// ToSerialHexWithAscii(byte[])
|
||||
// -----------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void ToSerialHexWithAscii_MixedData()
|
||||
{
|
||||
byte[] data = Encoding.ASCII.GetBytes("OK\r\n");
|
||||
var result = HexFormatter.ToSerialHexWithAscii(data);
|
||||
|
||||
Assert.AreEqual("4F 4B 0D 0A | OK..", result);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// IntToBytesBE
|
||||
// -----------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void IntToBytesBE_TwoBytes()
|
||||
{
|
||||
var result = HexFormatter.IntToBytesBE(0x1234, 2);
|
||||
|
||||
CollectionAssert.AreEqual(
|
||||
new byte[] { 0x12, 0x34 },
|
||||
result
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// IntToBytesLE
|
||||
// -----------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void IntToBytesLE_TwoBytes()
|
||||
{
|
||||
var result = HexFormatter.IntToBytesLE(0x1234, 2);
|
||||
|
||||
CollectionAssert.AreEqual(
|
||||
new byte[] { 0x34, 0x12 },
|
||||
result
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// AsciiToBytes
|
||||
// -----------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void AsciiToBytes_ConvertsString()
|
||||
{
|
||||
var result = HexFormatter.AsciiToBytes("AB");
|
||||
|
||||
CollectionAssert.AreEqual(
|
||||
new byte[] { 0x41, 0x42 },
|
||||
result
|
||||
);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AsciiToBytes_EmptyString_ReturnsEmpty()
|
||||
{
|
||||
var result = HexFormatter.AsciiToBytes(string.Empty);
|
||||
Assert.AreEqual(0, result.Length);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AsciiToBytes_Null_ReturnsEmpty()
|
||||
{
|
||||
var result = HexFormatter.AsciiToBytes(null);
|
||||
Assert.AreEqual(0, result.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led;
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.led
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(ShortVariableLedParser))]
|
||||
public class ShortVariableLedParserTest
|
||||
{
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_ValidShortVariableMessage()
|
||||
{
|
||||
// Arrange
|
||||
string raw = ";12345678,00012345.67;";
|
||||
var message = new TouchReadLedMessage(raw);
|
||||
var parser = new ShortVariableLedParser();
|
||||
|
||||
// Act
|
||||
TouchReadLedData data = parser.Parse(message);
|
||||
|
||||
// Assert
|
||||
Assert.IsNotNull(data);
|
||||
Assert.AreEqual(raw, data.Raw);
|
||||
Assert.AreEqual("12345678", data.MeterId);
|
||||
Assert.AreEqual(12345.67m, data.Reading);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void Parse_InvalidDecimal_Throws()
|
||||
{
|
||||
// Arrange
|
||||
string raw = ";12345678,ABCDEF;";
|
||||
var message = new TouchReadLedMessage(raw);
|
||||
var parser = new ShortVariableLedParser();
|
||||
|
||||
// Act
|
||||
parser.Parse(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.led
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(TouchReadLedMessage))]
|
||||
public class TouchReadLedMessageTest
|
||||
{
|
||||
|
||||
[TestMethod]
|
||||
public void Parse_LedMessage_Basic()
|
||||
{
|
||||
string raw = ";12345678,00012345.67;";
|
||||
|
||||
var msg = new TouchReadLedMessage(raw);
|
||||
|
||||
Assert.AreEqual(2, msg.Fields.Length);
|
||||
Assert.AreEqual("12345678", msg.Fields[0]);
|
||||
Assert.AreEqual("00012345.67", msg.Fields[1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TouchReadLedData_Parse_Extended()
|
||||
{
|
||||
string raw = ";12345678,ABC123,00012345.67,m3;";
|
||||
|
||||
var msg = new TouchReadLedMessage(raw);
|
||||
|
||||
var data = new TouchReadLedData(raw)
|
||||
{
|
||||
MeterId = msg.Fields[0],
|
||||
CustomerId = msg.Fields[1],
|
||||
Reading = TouchReadLedData.ParseDecimal(msg.Fields[2]),
|
||||
Units = msg.Fields[3]
|
||||
};
|
||||
|
||||
Assert.AreEqual("12345678", data.MeterId);
|
||||
Assert.AreEqual("ABC123", data.CustomerId);
|
||||
Assert.AreEqual(12345.67m, data.Reading);
|
||||
Assert.AreEqual("m3", data.Units);
|
||||
}
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.wiredProtocol
|
||||
{
|
||||
[TestClass]
|
||||
public class TouchReadBaudRateDetectionTests
|
||||
{
|
||||
private const string ComPort = "COM3"; // COM PORT OF THE ASIC
|
||||
private const int ReadTimeoutMs = 1500;
|
||||
|
||||
private static readonly int[] StandardBaudRates =
|
||||
{
|
||||
115200, 9600//, 10400, 15625, 18432, 19200, 31250, 36864,
|
||||
//38400, 50000, 57600, 62500, 76800,
|
||||
//1200, 2400, 4800, 7812
|
||||
};
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory("Hardware")]
|
||||
[TestCategory("Serial")]
|
||||
public void Detect_BaudRate_By_ViewFactoryId()
|
||||
{
|
||||
byte[] request = new TouchReadFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.Simple)
|
||||
.BuildBytes();
|
||||
|
||||
var parser = new TouchReadFrameParser();
|
||||
|
||||
foreach (int baud in StandardBaudRates)
|
||||
{
|
||||
Console.WriteLine($"--- Testing baud rate: {baud} ---");
|
||||
|
||||
try
|
||||
{
|
||||
using (var port = new SerialPort(ComPort, baud, Parity.None, 8, StopBits.One))
|
||||
{
|
||||
port.ReadTimeout = ReadTimeoutMs;
|
||||
port.WriteTimeout = 500;
|
||||
port.Open();
|
||||
|
||||
port.DiscardInBuffer();
|
||||
port.DiscardOutBuffer();
|
||||
|
||||
Console.WriteLine("TX → " + HexFormatter.ToSerialHex(request));
|
||||
port.Write(request, 0, request.Length);
|
||||
|
||||
byte[] response = ReadFullFrame(port);
|
||||
|
||||
Console.WriteLine("RX ← " + HexFormatter.ToSerialHex(response));
|
||||
|
||||
TouchReadResponse decoded = parser.Parse(response);
|
||||
|
||||
if (decoded.IsOk)
|
||||
{
|
||||
string factoryId = decoded.GetAsciiPayload();
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("VALID RESPONSE");
|
||||
Console.WriteLine("Baud rate : " + baud);
|
||||
Console.WriteLine("Factory ID : " + factoryId);
|
||||
Console.WriteLine();
|
||||
|
||||
Assert.IsFalse(string.IsNullOrEmpty(factoryId),
|
||||
"Factory ID is empty");
|
||||
|
||||
return; // SUCCESS → stop scanning
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Console.WriteLine("Timeout");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Error: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Fail("No valid baud rate detected.");
|
||||
}
|
||||
|
||||
private static byte[] ReadFullFrame(SerialPort port)
|
||||
{
|
||||
byte start = (byte)port.ReadByte();
|
||||
if (start != 0x0D)
|
||||
throw new InvalidOperationException("Invalid START byte");
|
||||
|
||||
byte length = (byte)port.ReadByte();
|
||||
|
||||
int remaining = length;
|
||||
byte[] buffer = new byte[2 + remaining];
|
||||
|
||||
buffer[0] = start;
|
||||
buffer[1] = length;
|
||||
|
||||
int offset = 2;
|
||||
while (remaining > 0)
|
||||
{
|
||||
int read = port.Read(buffer, offset, remaining);
|
||||
offset += read;
|
||||
remaining -= read;
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ConvertTest()
|
||||
{
|
||||
byte[] input = { 0x53, 0x57, 0x05, 0x01, 0x0D };
|
||||
Console.WriteLine(HexFormatter.ToSerialHex(input));
|
||||
Console.WriteLine(HexFormatter.ToHex(input));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.wiredProtocol
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(TouchReadFrameBuilder))]
|
||||
public class TouchReadFrameBuilderTest
|
||||
{
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_ViewFactoryId_Command()
|
||||
{
|
||||
byte[] frame = new TouchReadFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.ViewFactoryId)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected =
|
||||
{
|
||||
0x0D, // START
|
||||
0x04, // LEN
|
||||
0x08, // CONTROL (RF)
|
||||
0x01, // COMMAND
|
||||
0x00, // CHECKSUM HI
|
||||
0x1A // CHECKSUM LO
|
||||
};
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = TouchReadLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: < {0} >", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_ViewProgrammableId_Command()
|
||||
{
|
||||
byte[] frame = new TouchReadFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.ViewProgrammableId)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected =
|
||||
{
|
||||
0x0D, // START
|
||||
0x04, // LEN
|
||||
0x08, // CONTROL (RF)
|
||||
0x03, // COMMAND
|
||||
0x00, // CHECKSUM HI
|
||||
0x1C // CHECKSUM LO
|
||||
};
|
||||
|
||||
CollectionAssert.AreEqual(expected, frame);
|
||||
|
||||
string log = TouchReadLogger.DescribeTx(frame);
|
||||
Console.WriteLine(log);
|
||||
Console.WriteLine(@"Raw: <{0}>", HexFormatter.ToSerialHex(frame));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Encode_SetState_Idle()
|
||||
{
|
||||
// Arrange
|
||||
byte[] frame = new TouchReadFrameBuilder()
|
||||
.RequestResponse(true)
|
||||
.AddCommand(ProtocolCommand.SetState)
|
||||
.AddPayload(new byte[] { 0x01 }) // Idle
|
||||
.BuildBytes();
|
||||
|
||||
byte[] expected =
|
||||
{
|
||||
0x0D, // START
|
||||
0x05, // LEN
|
||||
0x08, // CONTROL (RF)
|
||||
0x1A, // COMMAND (Set State)
|
||||
0x01, // PAYLOAD (Idle)
|
||||
0x00, // CHECKSUM HI
|
||||
0x35 // CHECKSUM LO
|
||||
};
|
||||
|
||||
// Assert
|
||||
CollectionAssert.AreEqual(expected, frame,
|
||||
$"Encoded frame mismatch.\nExpected: {HexFormatter.ToSerialHex(expected)}\nActual: {HexFormatter.ToSerialHex(frame)}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[ExpectedException(typeof(FormatException))]
|
||||
public void Decode_InvalidStart_Throws()
|
||||
{
|
||||
byte[] response =
|
||||
{
|
||||
0x00, // invalid START
|
||||
0x04,
|
||||
0x00,
|
||||
0x01,
|
||||
0x00,
|
||||
0x12
|
||||
};
|
||||
|
||||
var parser = new TouchReadFrameParser();
|
||||
|
||||
parser.Parse(response);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BuildBytes()
|
||||
{
|
||||
// Reserve space for checksum at [0] and [1]
|
||||
var frame = new List<byte>
|
||||
{
|
||||
0x00, // checksum high (placeholder)
|
||||
0x00, // checksum low (placeholder)
|
||||
|
||||
0x05, // length
|
||||
0x01, // command
|
||||
0x0D // start
|
||||
};
|
||||
|
||||
// Calculate checksum over payload only (skip checksum bytes)
|
||||
ushort checksum = TouchReadFrameBuilder.CalculateChecksum(
|
||||
frame.Skip(2)
|
||||
);
|
||||
|
||||
// Write checksum into first two positions
|
||||
frame[0] = (byte)(checksum >> 8); // high byte
|
||||
frame[1] = (byte)(checksum & 0xFF); // low byte
|
||||
|
||||
Console.WriteLine(HexFormatter.ToHex(frame.ToArray()));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ByteConversion()
|
||||
{
|
||||
byte[] frame = { 0x53, 0x57,0x05, 0x01, 0x0D};
|
||||
Console.WriteLine(@"1: " + HexFormatter.ToHex(frame.ToArray()));
|
||||
|
||||
byte[] payload = { 0x31, 0x30, 0x30, 0x31, 0x30, 0x34, 0x30, 0x35, 0x31, 0x00 };
|
||||
Console.WriteLine(@"Payload: " + HexFormatter.ToSerialHexWithAscii(payload.ToArray()));
|
||||
|
||||
//Connect
|
||||
//2026-02-04 14:06:22.515 TX (8) 53 57 3F 76 65 72 73 0D
|
||||
//2026-02-04 14:06:22.906 RX (74) 3F 76 65 72 73 3A 20 48 61 72 72 79 20 54 3A 42 38 30 30 2C 20 56 3A 30 36 2E 30 36 2E 30 31 2C 20 46 57 3A 31 39 30 32 31 35 2C 20 37 45 43 45 2C 20 42 31 2E 36 2E 30 31 2C 20 48 57 3A 34 2C 20 53 65 72 69 61 6C 3A 30 0D
|
||||
|
||||
string msg = "53 57 3F 76 65 72 73 0D";
|
||||
byte[] activationMsg = HexFormatter.HexStringToByteArray(msg);
|
||||
Console.WriteLine(@"ActivationMsg MSG: " + HexFormatter.ToSerialHexWithAscii(activationMsg.ToArray()));
|
||||
|
||||
string str =
|
||||
"3F 76 65 72 73 3A 20 48 61 72 72 79 20 54 3A 42 38 30 30 2C 20 56 3A 30 36 2E 30 36 2E 30 31 2C 20 46 57 3A 31 39 30 32 31 35 2C 20 37 45 43 45 2C 20 42 31 2E 36 2E 30 31 2C 20 48 57 3A 34 2C 20 53 65 72 69 61 6C 3A 30 0D";
|
||||
byte[] activationMsgRes = HexFormatter.HexStringToByteArray(str);
|
||||
Console.WriteLine(@"ActivationMsg RES: " + HexFormatter.ToSerialHexWithAscii(activationMsgRes.ToArray()));
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
|
||||
|
||||
|
||||
namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(OptoHeadTest))]
|
||||
public class OptoHeadTestTest
|
||||
{
|
||||
|
||||
[TestMethod]
|
||||
public void ReadRequest_PCB_Test()
|
||||
{
|
||||
IperlHead iHead = new IperlHead();
|
||||
OptoHeadTest optoHeadTest = new OptoHeadTest(iHead);
|
||||
|
||||
optoHeadTest.ReadRequest_PCB();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.common;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
|
||||
|
||||
namespace TBFTests.Rig.TestMethods.iPerlCommunication.common
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(OptoTelegramRaw))]
|
||||
public class OptoTelegramRawTest
|
||||
{
|
||||
private const double EPS = 1e-6;
|
||||
|
||||
private static OptoTelegramRaw Create() => new OptoTelegramRaw();
|
||||
|
||||
private static DiagnosticLedState4Data CreateTelegram(uint rawVolume24, uint timestamp32)
|
||||
{
|
||||
string HexU(uint value, int bytes) => value.ToString($"X{bytes * 2}");
|
||||
string[] fields =
|
||||
{
|
||||
"000000","0000","0000",
|
||||
HexU(rawVolume24,3),"0000","0000",
|
||||
HexU(timestamp32,4),"00","00000000",
|
||||
"0000","0000","0000","0000","00"
|
||||
};
|
||||
|
||||
return new DiagnosticLedState4Data("TEST", fields);
|
||||
}
|
||||
|
||||
// helper: compute liters per tick exactly as production
|
||||
private static double LitersPerTick =>
|
||||
(4.0 / 1000.0) / 3.785411784 / 2.0;
|
||||
|
||||
private static double TimestampPerTick => 1.0 / 4096.0;
|
||||
|
||||
[TestMethod]
|
||||
public void NormalProgression_NoWrap()
|
||||
{
|
||||
var sample = Create();
|
||||
|
||||
var d1 = CreateTelegram(1000, 2000);
|
||||
double volLast = d1.RawVolume;
|
||||
double tsLast = d1.AsicTimestamp;
|
||||
|
||||
var d2 = CreateTelegram(1010, 2010);
|
||||
|
||||
sample.UpdateFromSmart(d2, 0, 0, ref volLast, ref tsLast);
|
||||
|
||||
Assert.AreEqual(d2.RawVolume, sample.VolumeRawExt, EPS);
|
||||
Assert.AreEqual(d2.AsicTimestamp, sample.TimestampExt, EPS);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void VolumeForwardWrap_AddsOneFullVolumeRange()
|
||||
{
|
||||
var sample = Create();
|
||||
|
||||
var dLast = CreateTelegram((uint)((1 << 24) - 5), 0);
|
||||
double volLast = dLast.RawVolume;
|
||||
double tsLast = dLast.AsicTimestamp;
|
||||
|
||||
var dNew = CreateTelegram(3u, 0u);
|
||||
|
||||
sample.UpdateFromSmart(dNew, 0, 0, ref volLast, ref tsLast);
|
||||
|
||||
double expectedIncrease = (1 << 24) * LitersPerTick;
|
||||
|
||||
Assert.AreEqual(dNew.RawVolume + expectedIncrease, sample.VolumeRawExt, 1e-3);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TimestampForwardWrap_AddsOneFullTimeRange()
|
||||
{
|
||||
var sample = Create();
|
||||
|
||||
var dLast = CreateTelegram(0, (uint)((1UL << 32) - 10));
|
||||
double volLast = dLast.RawVolume;
|
||||
double tsLast = dLast.AsicTimestamp;
|
||||
|
||||
var dNew = CreateTelegram(0, 5);
|
||||
|
||||
sample.UpdateFromSmart(dNew, 0, 0, ref volLast, ref tsLast);
|
||||
|
||||
double expectedIncrease = (1UL << 32) * TimestampPerTick;
|
||||
|
||||
Assert.AreEqual(dNew.AsicTimestamp + expectedIncrease, sample.TimestampExt, 1e-3);
|
||||
}
|
||||
|
||||
|
||||
[TestMethod]
|
||||
public void HugeJump_UsesFallback()
|
||||
{
|
||||
var sample = Create();
|
||||
|
||||
var dLast = CreateTelegram(1000, 1000);
|
||||
double volLast = dLast.RawVolume;
|
||||
double tsLast = dLast.AsicTimestamp;
|
||||
|
||||
var dNew = CreateTelegram((uint)(1 << 23), (uint)(1UL << 31));
|
||||
|
||||
sample.UpdateFromSmart(dNew, 0, 0, ref volLast, ref tsLast);
|
||||
|
||||
Assert.AreEqual(dNew.RawVolume, sample.VolumeRawExt, EPS);
|
||||
Assert.AreEqual(dNew.AsicTimestamp, sample.TimestampExt, EPS);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LongRun_MultipleWraps_RemainsMonotonic()
|
||||
{
|
||||
var sample = new OptoTelegramRaw();
|
||||
|
||||
double volLast = double.NaN;
|
||||
double tsLast = double.NaN;
|
||||
|
||||
uint volCounter = (uint)((1 << 24) - 100);
|
||||
uint tsCounter = (uint)((1UL << 32) - 1000);
|
||||
|
||||
double prevVol = double.NegativeInfinity;
|
||||
double prevTs = double.NegativeInfinity;
|
||||
|
||||
for (int i = 0; i < 500; i++)
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
volCounter += 200_000u; // < 2^23
|
||||
tsCounter += 50_000_000u; // < 2^31
|
||||
}
|
||||
|
||||
var data = CreateTelegram(volCounter, tsCounter);
|
||||
sample.UpdateFromSmart(data, 0, 0, ref volLast, ref tsLast);
|
||||
|
||||
Assert.IsTrue(sample.VolumeRawExt >= prevVol, $"Volume went backwards at i={i}");
|
||||
Assert.IsTrue(sample.TimestampExt >= prevTs, $"Timestamp went backwards at i={i}");
|
||||
|
||||
prevVol = sample.VolumeRawExt;
|
||||
prevTs = sample.TimestampExt;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
|
||||
|
||||
namespace TBFTests.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
{
|
||||
using System;
|
||||
using System.Threading;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
|
||||
using Common;
|
||||
|
||||
namespace TBFTests.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(FlowDirectionDetection))]
|
||||
public class FlowDirectionDetectionTests
|
||||
{
|
||||
private FlowDirectionDetection Create() => new FlowDirectionDetection();
|
||||
|
||||
// helper: feed linear data
|
||||
private void FeedLinearData(FlowDirectionDetection d, double slope, int samples = 64)
|
||||
{
|
||||
double volume = 0;
|
||||
double time = 0;
|
||||
|
||||
for (int i = 0; i < samples; i++)
|
||||
{
|
||||
volume += slope; // linear growth
|
||||
time += 0.125; // 8 Hz sampling
|
||||
|
||||
d.WriteToFifo(volume, time);
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void Fifo_NotFull_DataInvalid()
|
||||
{
|
||||
var d = Create();
|
||||
|
||||
d.WriteToFifo(1, 1);
|
||||
|
||||
Assert.IsFalse(d.AreFifoDataValid());
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void Fifo_Full_DataValid()
|
||||
{
|
||||
var d = Create();
|
||||
FeedLinearData(d, 1.0);
|
||||
|
||||
Assert.IsTrue(d.AreFifoDataValid());
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void PositiveFlow_Detected()
|
||||
{
|
||||
var d = Create();
|
||||
FeedLinearData(d, slope: 10); // increasing volume
|
||||
|
||||
var result = d.CheckFlowDirection(Counting.Positive, "HEAD");
|
||||
|
||||
Assert.AreEqual(OptoHeadState.OptoAndDirOK, result);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void NegativeFlow_Detected()
|
||||
{
|
||||
var d = Create();
|
||||
FeedLinearData(d, slope: -10); // decreasing volume
|
||||
|
||||
var result = d.CheckFlowDirection(Counting.Negative, "HEAD");
|
||||
|
||||
Assert.AreEqual(OptoHeadState.OptoAndDirOK, result);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void WrongDirection_Fails()
|
||||
{
|
||||
var d = Create();
|
||||
FeedLinearData(d, slope: -10); // negative flow
|
||||
|
||||
var result = d.CheckFlowDirection(Counting.Positive, "HEAD");
|
||||
|
||||
Assert.AreEqual(OptoHeadState.DirNok, result);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void ArbitraryCounting_AlwaysPassesWhenSignalGood()
|
||||
{
|
||||
var d = Create();
|
||||
FeedLinearData(d, slope: -5);
|
||||
|
||||
var result = d.CheckFlowDirection(Counting.Arbitrary, "HEAD");
|
||||
|
||||
Assert.AreEqual(OptoHeadState.OptoAndDirOK, result);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void NoFlow_ReturnsDirNok()
|
||||
{
|
||||
var d = Create();
|
||||
|
||||
// flat signal → slope ≈ 0
|
||||
for (int i = 0; i < 64; i++)
|
||||
d.WriteToFifo(100, i * 0.125);
|
||||
|
||||
var result = d.CheckFlowDirection(Counting.Positive, "HEAD");
|
||||
|
||||
Assert.AreEqual(OptoHeadState.DirNok, result);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void FifoOverwrite_StillDetectsCorrectly()
|
||||
{
|
||||
var d = Create();
|
||||
|
||||
// write more than FIFO size → overwrite happens
|
||||
FeedLinearData(d, slope: 5, samples: 200);
|
||||
|
||||
var result = d.CheckFlowDirection(Counting.Positive, "HEAD");
|
||||
|
||||
Assert.AreEqual(OptoHeadState.OptoAndDirOK, result);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------
|
||||
|
||||
[TestMethod]
|
||||
public void Timeout_InvalidatesFifo()
|
||||
{
|
||||
var d = Create();
|
||||
FeedLinearData(d, slope: 5);
|
||||
|
||||
// simulate dropout > 4.5 sec
|
||||
Thread.Sleep(5000);
|
||||
|
||||
Assert.IsFalse(d.AreFifoDataValid());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
|
||||
|
||||
namespace TBFTests.Rig.TestMethods.iPerlCommunication.iPerlHead
|
||||
{
|
||||
[TestClass]
|
||||
[TestSubject(typeof(IperlHead))]
|
||||
public class IperlHeadTest
|
||||
{
|
||||
|
||||
[TestMethod]
|
||||
public void VolumeLtrStart()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void VolumeLtrEnd()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NoSamples()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,8 +44,8 @@
|
||||
<Reference Include="JetBrains.Annotations, Version=4242.42.42.42, Culture=neutral, PublicKeyToken=1010a0d8d6380325, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\JetBrains.Annotations.2023.3.0\lib\net20\JetBrains.Annotations.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
|
||||
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Microsoft.Extensions.Configuration.Abstractions.5.0.0\lib\net461\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
|
||||
@@ -102,8 +102,21 @@
|
||||
<Compile Include="Rig\Network\Camera\KeyenceIV3G120\CameraTest.cs" />
|
||||
<Compile Include="Rig\Network\Camera\RoiForFixedStartKeyence\RoiTest.cs" />
|
||||
<Compile Include="Rig\Output\FileWriters\Enhanced\WriterTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\diagnosticLed\DiagnosticLedParserTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\hexLogger\HexFormatterTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\IperlHatProtocol\IperlHatFrameBuilderTests.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\IperlHatProtocol\IperlHatFrameParserTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\IperlHatProtocol\IperlHatIntegrationTests.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\led\ShortVariableLedParserTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\led\TouchReadLedMessageTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\wiredProtocol\TouchReadBaudRateDetectionTests.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\C4\wiredProtocol\TouchReadFrameBuilderTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\iPerlASICReader\communication\OptoHeadTestTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\PoseidonCmdStartStop\CliRunnerTest.cs" />
|
||||
<Compile Include="Rig\RegisterReaders\PoseidonCmdStartStop\PoseidonReaderTest.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\common\OptoTelegramRawTest.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\iPerlHead\FlowDirectionDetectionTest.cs" />
|
||||
<Compile Include="Rig\TestMethods\iPerlCommunication\iPerlHead\IperlHeadTest.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="app.config" />
|
||||
|
||||
Reference in New Issue
Block a user