- Introduced support for V1 optical diagnostic frames (C3/C4) with separate processing to prevent interference with metrology data. - Added `DiagnosticTelegramReceived` callback in `OptoHeadService` for detailed logging of V1 frames. - Enhanced `PoseidonOpticalLineParser` to parse and handle C3 calibration factors and C4 auxiliary ADC values. - Implemented a new diagnostic logging method in `SmartReader` for V1 telegrams. - Extended test coverage with new cases to validate C3/C4 frame parsing and diagnostic handling. - Bumped assembly version to 3.9.3176.0.
323 lines
13 KiB
C#
323 lines
13 KiB
C#
using System;
|
|
using System.IO.Ports;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Common;
|
|
using log4net;
|
|
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols;
|
|
using TBF.Rig.Sequences;
|
|
using TBF.Rig.RegisterReaders.PoseidonReader.communication;
|
|
using SERIAL_Driver = TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Utils.SERIAL_Driver;
|
|
using WaterMetrologyData = TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols.WaterMetrologyData;
|
|
|
|
namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
|
{
|
|
public class OptoHeadService
|
|
{
|
|
static readonly ILog log = LogManager.GetLogger("PoseidonConnection");
|
|
// This logger is intentionally separate from the general connection log.
|
|
// It is used by the manual optical test as well as the test-run reader.
|
|
static readonly ILog opticalTraceLog = LogManager.GetLogger("PoseidonOptical");
|
|
|
|
public class Con
|
|
{
|
|
|
|
public string com = "COM5";
|
|
public int baudrate = 38400;
|
|
public int dataBits = 8;
|
|
public Parity parity = Parity.None;
|
|
// Poseidon optical output is specified as 38400 8-N-1.
|
|
public StopBits stopbits = StopBits.One;
|
|
public int readTimeout = 5000;
|
|
public int writeTimeout = 1000;
|
|
private DebugMode _debugLevel;
|
|
public DebugMode DebugModeSetting { get => _debugLevel; }
|
|
|
|
public Con(string com, int baudrate, int dataBits, Parity parity, StopBits stopbits, int readTimeout,
|
|
int writeTimeout) : this(com)
|
|
{
|
|
this.baudrate = baudrate;
|
|
this.dataBits = dataBits;
|
|
this.parity = parity;
|
|
this.stopbits = stopbits;
|
|
this.readTimeout = readTimeout;
|
|
this.writeTimeout = writeTimeout;
|
|
}
|
|
|
|
public Con(DebugMode debugLevel,string com, int baudrate, int dataBits, Parity parity, StopBits stopbits, int readTimeout,
|
|
int writeTimeout) : this(com)
|
|
{
|
|
this._debugLevel = debugLevel;
|
|
this.baudrate = baudrate;
|
|
this.dataBits = dataBits;
|
|
this.parity = parity;
|
|
this.stopbits = stopbits;
|
|
this.readTimeout = readTimeout;
|
|
this.writeTimeout = writeTimeout;
|
|
}
|
|
|
|
public Con(string com, DebugMode debugLevel = DebugMode.Normal)
|
|
{
|
|
this.com = com;
|
|
this._debugLevel = debugLevel;
|
|
}
|
|
}
|
|
|
|
private Con Connection { get; set; }
|
|
private SERIAL_Driver driver;
|
|
private readonly PoseidonProtocolProfile protocolProfile;
|
|
private readonly StringBuilder opticalTextBuffer = new StringBuilder();
|
|
private PoseidonOpticalLineParser opticalLineParser;
|
|
private DateTime bufferedLineReceivedUtc = DateTime.MinValue;
|
|
/// <summary>
|
|
/// Filed After Run() is called.
|
|
/// </summary>
|
|
public WaterMetrologyData WaterMetrologyData { get; private set; }
|
|
|
|
// Driver bytes and parse outcome, including rejected packets.
|
|
public Action<byte[], DateTime, WaterMetrologyData, bool> DiagnosticReceived { get; set; }
|
|
// Valid non-metrology V1 frames (for example C3/C4) are exposed
|
|
// separately so they can be logged without entering the test result.
|
|
public Action<PoseidonOpticalTelegram> DiagnosticTelegramReceived { get; set; }
|
|
|
|
public OptoHeadService(Con con)
|
|
: this(con, null)
|
|
{
|
|
}
|
|
|
|
public OptoHeadService(Con con, PoseidonProtocolProfile profile)
|
|
{
|
|
Connection = con;
|
|
protocolProfile = profile;
|
|
opticalLineParser = profile == null ? null : new PoseidonOpticalLineParser(profile);
|
|
driver = new SERIAL_Driver();
|
|
OnOptoReceivedHandler = null;
|
|
}
|
|
|
|
public bool CreateSerialConnection()
|
|
{
|
|
OnOptoReceivedHandler = null;
|
|
dissableRunLoop = false;
|
|
opticalTextBuffer.Length = 0;
|
|
bufferedLineReceivedUtc = DateTime.MinValue;
|
|
if (opticalLineParser != null) opticalLineParser.ResetMeterTimeAnchor();
|
|
bool isopen = false;
|
|
Con con = Connection;
|
|
if (con == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
byte[] message = {0x00};
|
|
byte[] bytesReceived;
|
|
|
|
if (con?.DebugModeSetting == DebugMode.Simulate)
|
|
{
|
|
isopen = true;
|
|
}
|
|
else if (!driver.isOpen())
|
|
{
|
|
|
|
isopen = driver.OpenConnection(
|
|
con.com,
|
|
con.baudrate,
|
|
con.dataBits,
|
|
con.parity,
|
|
con.stopbits,
|
|
con.readTimeout,
|
|
con.writeTimeout);
|
|
}
|
|
|
|
_bRunStarted = false;
|
|
|
|
return isopen;
|
|
}
|
|
|
|
/// <summary>Discard bytes received before a measurement capture starts.</summary>
|
|
public void DiscardPendingInput()
|
|
{
|
|
opticalTextBuffer.Length = 0;
|
|
bufferedLineReceivedUtc = DateTime.MinValue;
|
|
driver.DiscardInputBuffer();
|
|
}
|
|
|
|
public void CloseSerialConnection()
|
|
{
|
|
dissableRunLoop = true;
|
|
OnOptoReceivedHandler = null;
|
|
if (Connection?.DebugModeSetting != DebugMode.Simulate)
|
|
{
|
|
driver.Close();
|
|
}
|
|
_bRunStarted = false;
|
|
}
|
|
|
|
private EventHandler<CommonRR.IPerl.communication.OptoReceivedEventArgs> OnOptoReceivedHandler;
|
|
|
|
|
|
|
|
public bool IsRunning
|
|
{
|
|
get { return !dissableRunLoop
|
|
&& ((Connection?.DebugModeSetting != DebugMode.Simulate) ? driver.isOpen() : true)
|
|
&& _bRunStarted;}
|
|
}
|
|
|
|
public void RunLoop(EventHandler<CommonRR.IPerl.communication.OptoReceivedEventArgs> onOptoReceivedHandler)
|
|
{
|
|
log.Debug("RunLoop started on event!");
|
|
OnOptoReceivedHandler = onOptoReceivedHandler;
|
|
Task.Run(() => Run());
|
|
}
|
|
|
|
public void RunLoop()
|
|
{
|
|
log.Debug("RunLoop started!");
|
|
Task.Run(() => Run());
|
|
}
|
|
|
|
private bool dissableRunLoop = false;
|
|
private bool _bRunStarted = false;
|
|
/// <summary>
|
|
/// Run the service. Catch one communication to WaterMetrologyData field.
|
|
/// </summary>
|
|
public void Run()
|
|
{
|
|
while (!dissableRunLoop)
|
|
{
|
|
_bRunStarted = true;
|
|
DateTime receivedUtc;
|
|
byte[] rawDiagnosticData = RunReading(out receivedUtc);
|
|
WaterMetrologyData = ParseData(rawDiagnosticData, receivedUtc);
|
|
if (OnOptoReceivedHandler != null && WaterMetrologyData != null)
|
|
{
|
|
log.Debug($"Received OptoData: {WaterMetrologyData}");
|
|
OnOptoReceivedHandler?.Invoke(this, new CommonRR.IPerl.communication.OptoReceivedEventArgs(WaterMetrologyData?.ToString(), WaterMetrologyData));
|
|
}
|
|
try
|
|
{
|
|
// Empty polling is not a rejected frame. Only record actual
|
|
// COM data (or a produced metrology result) here; parsed C3/C4
|
|
// frames are recorded through DiagnosticTelegramReceived.
|
|
if ((rawDiagnosticData != null && rawDiagnosticData.Length > 0) || WaterMetrologyData != null)
|
|
DiagnosticReceived?.Invoke(rawDiagnosticData, receivedUtc, WaterMetrologyData,
|
|
Connection?.DebugModeSetting != DebugMode.Simulate);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
log.Warn("Poseidon optical diagnostic callback failed.", ex);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
byte[] RunReading(out DateTime receivedUtc)
|
|
{
|
|
receivedUtc = DateTime.UtcNow;
|
|
if (Connection?.DebugModeSetting == DebugMode.Simulate)
|
|
{
|
|
return new byte[] {0x00};
|
|
}
|
|
if (driver.isOpen())
|
|
{
|
|
byte[] rawData = driver.GetRawData();
|
|
// Capture immediately after the COM read, before diagnostics or
|
|
// parsing. This is the PC/UTC timestamp defined for V1 logs.
|
|
receivedUtc = DateTime.UtcNow;
|
|
if (rawData == null)
|
|
System.Threading.Thread.Sleep(10);
|
|
log.Debug($"Received data size: {rawData?.Length ?? 0} bytes, raw data: {(rawData==null? "" :BitConverter.ToString(rawData))}");
|
|
if (rawData != null && rawData.Length > 0)
|
|
{
|
|
// Preserve the exact data received from COM, including fragments of a
|
|
// V1 line. The parser may need several callbacks before a CR/LF-terminated
|
|
// telegram is available, so logging must happen before parsing.
|
|
opticalTraceLog.Info("Incoming optical stream; source=COM; port=" +
|
|
(Connection?.com ?? "unknown") + "; bytes=" + rawData.Length +
|
|
"; raw=" + EscapeOpticalBytes(rawData));
|
|
}
|
|
return rawData;
|
|
}
|
|
else
|
|
{
|
|
log.Debug("Serial port is not open.");
|
|
dissableRunLoop = true;
|
|
}
|
|
|
|
return new byte[] {0xFF};
|
|
}
|
|
|
|
public WaterMetrologyData ParseData(byte[] data)
|
|
{
|
|
return ParseData(data, DateTime.UtcNow);
|
|
}
|
|
|
|
internal WaterMetrologyData ParseData(byte[] data, DateTime receivedUtc)
|
|
{
|
|
if (Connection?.DebugModeSetting == DebugMode.Simulate)
|
|
{
|
|
return WaterMetrologyData.SimulateC7();
|
|
}
|
|
try
|
|
{
|
|
if (protocolProfile != null && protocolProfile.OpticalProtocol != PoseidonOpticalProtocol.LegacyV0)
|
|
{
|
|
if (data != null && data.Length > 0)
|
|
{
|
|
if (opticalTextBuffer.Length == 0)
|
|
bufferedLineReceivedUtc = receivedUtc;
|
|
opticalTextBuffer.Append(Encoding.ASCII.GetString(data));
|
|
}
|
|
int lineEnd = opticalTextBuffer.ToString().IndexOf('\n');
|
|
if (lineEnd < 0)
|
|
return null;
|
|
|
|
string line = opticalTextBuffer.ToString(0, lineEnd + 1);
|
|
opticalTextBuffer.Remove(0, lineEnd + 1);
|
|
PoseidonOpticalTelegram telegram;
|
|
string error;
|
|
DateTime lineReceivedUtc = bufferedLineReceivedUtc == DateTime.MinValue ? receivedUtc : bufferedLineReceivedUtc;
|
|
bufferedLineReceivedUtc = opticalTextBuffer.Length == 0 ? DateTime.MinValue : receivedUtc;
|
|
if (!opticalLineParser.TryParse(line, lineReceivedUtc, out telegram, out error))
|
|
{
|
|
log.Warn("Poseidon optical V1 frame rejected: " + error);
|
|
return null;
|
|
}
|
|
try
|
|
{
|
|
DiagnosticTelegramReceived?.Invoke(telegram);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
log.Warn("Poseidon V1 diagnostic telegram callback failed.", ex);
|
|
}
|
|
if (telegram.C7 != null) return WaterMetrologyData.FromC7(telegram.C7);
|
|
if (telegram.C2 != null) return WaterMetrologyData.FromC2(telegram.C2);
|
|
return null;
|
|
}
|
|
if (data == null || data.Length == 0)
|
|
return null;
|
|
return WaterMetrologyData.Parse(data, DateTime.Now, "");
|
|
}catch(Exception e)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static string EscapeOpticalBytes(byte[] data)
|
|
{
|
|
var result = new StringBuilder();
|
|
foreach (byte value in data)
|
|
{
|
|
if (value == 92) result.Append(@"\\");
|
|
else if (value == 13) result.Append(@"\r");
|
|
else if (value == 10) result.Append(@"\n");
|
|
else if (value == 9) result.Append(@"\t");
|
|
else if (value >= 32 && value <= 126) result.Append((char)value);
|
|
else result.Append(@"\x").Append(value.ToString("X2"));
|
|
}
|
|
return result.ToString();
|
|
}
|
|
}
|
|
}
|