Files
tbf/TBF/Rig/RegisterReaders/PoseidonReader/SmartReader.cs
T
michal 6eeaa113f5 feat(poseidon communication): add V1 diagnostic frame support for C3/C4 data handling
- Introduced support for V1 optical diagnostic frames (C3/C4) with separate processing to prevent interference with metrology data.
- Added `DiagnosticTelegramReceived` callback in `OptoHeadService` for detailed logging of V1 frames.
- Enhanced `PoseidonOpticalLineParser` to parse and handle C3 calibration factors and C4 auxiliary ADC values.
- Implemented a new diagnostic logging method in `SmartReader` for V1 telegrams.
- Extended test coverage with new cases to validate C3/C4 frame parsing and diagnostic handling.
- Bumped assembly version to 3.9.3176.0.
2026-10-19 15:12:23 +02:00

1710 lines
64 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Windows.Forms.VisualStyles;
using System.Xml.Linq;
using Common;
using Common.Iperl;
using Config.Entities;
using log4net;
using NHibernate;
using Sensus.iPerl.NfcHandler;
using TBF.Rig.Generic;
using TBF.Rig.GenericDevices;
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7;
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.common;
using CalibrationStruct = TBF.Rig.RegisterReaders.CommonRR.IPerl.communication.CalibrationStruct;
using CalibrationStructV4 = TBF.Rig.RegisterReaders.CommonRR.IPerl.communication.CalibrationStructV4;
using CommunicationInterface = TBF.Rig.RegisterReaders.CommonRR.CommunicationInterface;
using ConfigStruct = TBF.Rig.RegisterReaders.CommonRR.IPerl.communication.ConfigStruct;
using MeterType = TBF.Rig.RegisterReaders.CommonRR.MeterType;
using PoseidonOpticalHead = TBF.Rig.RegisterReaders.PoseidonReader.communication.PoseidonOpticalHead;
using PoseidonOpticalHeadBuilder = TBF.Rig.RegisterReaders.PoseidonReader.communication.PoseidonOpticalHeadBuilder;
using PoseidonOpticalTelegram = TBF.Rig.RegisterReaders.PoseidonReader.communication.PoseidonOpticalTelegram;
using PoseidonProtocolProfile = TBF.Rig.RegisterReaders.PoseidonReader.communication.PoseidonProtocolProfile;
namespace TBF.Rig.RegisterReaders.PoseidonReader
{
/// <summary>
/// based on IPerlReader class
/// </summary>
public class SmartReader : ComponentBase, IDevice,IRegReaderDatastream, ISessionDataMngmnt, IOperation, ISmartReader
{
private static readonly ILog log = LogManager.GetLogger(typeof(SmartReader));
public override string ToString() { return string.Format("{0}({1})", ClassName, Cfg.ToString(-1)); }
#if TURA_SPECIAL
public const int OptoDataBufferSize = 250000;
#else
public const int OptoDataBufferSize = 40000; /// Opto data count is not limitted by the buffer size
#endif
public const string OptoDataDirectory = "C:\\TBF\\ProcessData";
public const int StartOptoDataCount = OptoDataBufferSize / 2;
public const int EndOptoDataCount = OptoDataBufferSize - StartOptoDataCount;
public const int StartEndFilterSamplesCount2 = 20; /// StartEndFilterSamplesCount = 2 * StartEndFilterSamplesCount2 + 1
public const int FeatureVectorSize = 9;
private readonly PoseidonOpticalDiagnosticWriter opticalDiagnosticWriter = new PoseidonOpticalDiagnosticWriter();
private DateTime? diagnosticFirstUtc;
private uint? diagnosticLastAccumulator;
private long diagnosticExtendedAccumulator;
readonly PoseidonCfg _poseidonCfg;
public PoseidonCfg RegPoseidonCfg { get { return _poseidonCfg; } }
public int RfidComPortNr { get { return _poseidonCfg.RfidComPortNr; } }
public int OptoComPortNr { get { return _poseidonCfg.OptoComPortNr; } }
public MeterType MeterType { get { return _poseidonCfg.MeterType; } }
public string CommInterface { get { return _poseidonCfg.CommunicationInterface.ToString(); } }
public double CalibTarget { get { return _poseidonCfg.ProcParams.CalibTarget; } }
public ushort FactorLimitLo { get { return (ushort)_poseidonCfg.ProcParams.FactorLimitLo; } }
public ushort FactorLimitHi { get { return (ushort)_poseidonCfg.ProcParams.FactorLimitHi; } }
public Counting InitFlowDir { get { return (_poseidonCfg != null && _poseidonCfg.ProcParams != null) ? _poseidonCfg.ProcParams.Counting : Counting.Arbitrary; } }
string simulatedPcbNr = null;
/// Properties set by the Begin and the End form
public string SerialNr
{
get
{
if (ConfigStruct != null)
return ConfigStruct.GetPcbNrString();
else if (simulatedPcbNr != null)
return simulatedPcbNr;
else
return string.Empty;
}
set
{
simulatedPcbNr = value;
}
}
public bool _commFailed;
public bool CommFailed { get => _commFailed; set => _commFailed = value; }
public bool Disabled { get; set; }
public int ResultCode;
string extraDataPath;
public string ExtraDataPath { get { return extraDataPath; } }
float[] x;
public float[] X { get { return x; } }
// Volume of water from the opto telegram
private DateTime _firstSampleTime;
private DateTime _lastSampleTime;
// Meter ProductTime is optional (it needs an F0 System Info anchor).
// Keep the host clock as a safe fallback for old C7-only profiles.
private double? _firstMeterProductTimeSeconds;
private double? _lastMeterProductTimeSeconds;
private ushort? _meterTimeRebootCount;
private double _averageFlow;
private long _averageFlowCount;
private readonly object _avgLock = new object();
private readonly object opticalBatchLock = new object();
private readonly List<WaterMetrologyData> opticalBatch = new List<WaterMetrologyData>();
private DateTime opticalBatchStartedUtc;
private double? lastBufferedMeterSecond;
private bool _optoheadStarted = false;
private OptoHeadService _optoHeadService;
private DateTime? opticalCaptureNotBeforeUtc;
/// <summary>
/// Passed to OptoTelegramRaw.UpdateFromString(...)
/// </summary>
Int64 volumeRawExtLast;
Int64 timestampExtLast;
FlowDirectionDetection flowDirectionDetection;
public bool PositiveCounting;
public ConfigStruct ConfigStruct; /// ConfigStruct of WM obtained or updated by iPerlCommunication
public CalibrationStruct CalibrationStruct; /// CalibrationStruct of WM obtained or updated by iPerlCommunication
public CalibrationStructV4 CalibrationStructV4; /// CalibrationStruct of WM obtained or updated by iPerlCommunication
public Byte OrigTestModeConfig; /// Written to by StartTestingSealedMeter(), read from by EndTestingSealedMeter()
public ushort OrigCalibFactor;
public ushort CalibFactor
{
get
{
return (CalibrationStruct != null) ? CalibrationStruct.Calibration
: ((CalibrationStructV4 != null) ? CalibrationStructV4.Calibration
: (ushort)0);
}
}
public ushort OrigCalibFactorLNA;
public ushort CalibFactorLNA { get { return (CalibrationStructV4 != null) ? CalibrationStructV4.CalibrationLNA : (ushort)0; } }
public double Q2ErrWOCorrection;
public int Q2CorrRL;
public int Q2CorrLR;
public double Diff2Hz8Hz;
public bool Hz2CorrectionDone;
public int Hz2Correction;
public string FWVersion
{
get
{
return (CalibrationStruct != null) ? CalibrationStruct.FWVersionStr()
: ((CalibrationStructV4 != null) ? CalibrationStructV4.FWVersionStr()
: string.Empty);
}
}
/// <summary> Result of the last test used to calculate Q2 correction factors, etc </summary>
public Results.Entities.MeterTestRslt LastTestResult;
public Results.Entities.MeterTestRslt LastTestResult2;
///
Test test;
int repetitionNr;
///
/// Indices to determine centers of start / end samples
///
public int TestStartTelegramIx;
public int TestEndTelegramIx;
int endTelegramIdx1;
int endTelegramIdx2;
int endTelegramIdx3;
int currentTelegramIx;
bool startSampleAcquired;
///
/// Timestamp from the opto telegram
///
int timeFromStart; /// [s] Time from test start to determine when the test start sample should be taken
/// Test start volume for metrology in seconds
public double TimestampSecStart
{
get
{
return _lastSampleTime != DateTime.MinValue ? 1 : 0; // return one second if is initialized, 0 - is false
//return TimeFromSamples(optoData, optoDataCount, TestStartTelegramIx, StartEndFilterSamplesCount2);
}
}
/// Test end time for metrology in seconds
public double TimestampSecEnd
{
get
{
if (_lastSampleTime == DateTime.MinValue) return 0;
return GetSampleDurationSeconds() + 1;
//return TimeFromSamples(optoData, optoDataCount, TestEndTelegramIx, StartEndFilterSamplesCount2);
}
}
///
public bool NoSamples
{
get { return TimestampSecStart == 0 || TimestampSecEnd == 0 || (TimestampSecEnd - TimestampSecStart) < float.Epsilon; }
}
///
/// Volume of water from the opto telegram
///
private Int64 lastVolumeRaw; /// Last read raw volume
private double volumeLtr;
private double volumeLtr0;
/// Test start volume for metrology in liters
public double VolumeLtrStart
{
get
{
return 0;
//return NoSamples ? 0 : VolumeFromSamples(optoData, optoDataCount, TestStartTelegramIx, ScalingFactor(), StartEndFilterSamplesCount2);
}
}
/// Test end volume for metrology in liters
public double VolumeLtrEnd
{
get
{
return wmVolume; // complet calculated volume (time * flowrate)
//return NoSamples ? 0 : VolumeFromSamples(optoData, optoDataCount, TestEndTelegramIx, ScalingFactor(), StartEndFilterSamplesCount2);
}
}
OptoTelegramRaw[] optoData;
int optoDataCount; /// Real opto deta count, can be larger then optoData.Length
///
OptoTelegramRaw toBeFlushed;
///
/// Opto serial port and worker thread related private variables
///
private SerialPort optoSerialPort;
DataStreamState dataStreamState;
///
/// Variables storing the context of serial port data parsing (ReadOptoSerialPort(...))
///
bool synchronized;
bool synchronized2;
string partOfTelegram;
Counting currentFlowDir;
/// <summary>
/// ///////////////////////////////////////////
/// </summary>
public SmartReader() { }
public SmartReader(Generic.IComponentCfg cfg)
: base(cfg)
{
_poseidonCfg = cfg as PoseidonCfg;
}
/// <summary>
///
/// </summary>
/// <exception cref="NotImplementedException"></exception>
public override void Initialize()
{
x = new float[FeatureVectorSize];
flowDirectionDetection = new FlowDirectionDetection();
/// Allocate memory for opto-data from iPerl
optoData = new OptoTelegramRaw[OptoDataBufferSize];
for (int i = 0; i < OptoDataBufferSize; i++)
{
optoData[i] = new OptoTelegramRaw();
}
toBeFlushed = new OptoTelegramRaw();
dataStreamState = DataStreamState.Flush;
synchronized = false;
synchronized2 = false;
partOfTelegram = string.Empty;
optoSerialPort = null;
if (DebugLevel == DebugMode.Normal)
{
/// Open serial port: 9600 Bd, 8 data bits, 1 stop bit, no parity
/// Check whether head is connected, working
try
{
if (_poseidonCfg != null)
{
// OpenOptoSerialPort($"COM{_poseidonCfg.OptoComPortNr}", 9600, Parity.None, 8, StopBits.One,
// Handshake.None);
// CloseOptoSerialPort();
log.FatalFormat($"{Name} initialized: {this}");
}
else
{
log.Error($"{Name} NOT initialized: {this}");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
else
{
log.FatalFormat($"{Name} simulated: {this}");
}
}
public void RunDeviceBefore()
{
if (DebugLevel == DebugMode.Normal)
{
try
{
ReadOptoData(dataStreamState);
}
catch (Exception e)
{
DebugLevel = DebugMode.FailureDuringOperation;
log.FatalFormat("Opto-data serial port failure : {0}", e.Message);
if (e.InnerException != null)
{
log.FatalFormat("InnerMessage : {0}", e.InnerException.Message);
}
}
}
else if (DebugLevel == DebugMode.FailureDuringOperation)
{
}
}
public void RunDeviceAfter() { }
public void StopDevice()
{
try
{
if (optoSerialPort != null)
{
CloseOptoSerialPort();
}
}
catch
{
}
}
public void StopDevice2() { }
/// <summary>
/// Events: Event.ReadRegisterDone, Event.Error
/// </summary>
/// <returns>ReadWaterMeter instance reference casted to IOperaton</returns>
public IOperation ReadRegisterOp()
{
return this;
}
public RegisterReaderType RegisterReaderType { get { return RegisterReaderType.DataStream; } }
public int Position
{
get
{
int firstDigitPos = Name.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' });
int position;
return (firstDigitPos < 0) ? 0 : (int.TryParse(Name.Substring(firstDigitPos), out position) ? position : 0);
}
}
int wmPulses;
int wmRefPulses;
double beginWMState;
double endWMState;
double wmVolume;
double wmTestTime;
public double PulsesPerLtr {
get { return 1000.0; }
set { PulsesPerLtr = value; }
}
public double LtrsPerPulse { get { return 1 / PulsesPerLtr; } }
public string QuantityUnits { get; set; }
public int WMPulses { get { return wmPulses; } }
public int WMRefPulses { get { return wmRefPulses; }}
public double WMVolume { get { return wmVolume; } }
public double BeginWMState { get { return beginWMState;} set => beginWMState = value; }
public double EndWMState { get { return endWMState; } set => endWMState = value; }
public IOperation ReadDatastreamOp()
{
return this;
}
/// <summary>
/// Clear data related to a specific water meter
/// </summary>
public void StartSession()
{
ResultCode = 0;
Disabled = false;
CommFailed = false;
ConfigStruct = null;
CalibrationStruct = null;
CalibrationStructV4 = null;
OrigTestModeConfig = 0;
LastTestResult = null;
LastTestResult2 = null;
OrigCalibFactor = 0;
OrigCalibFactorLNA = 0;
Q2ErrWOCorrection = 0;
Q2CorrRL = 0;
Q2CorrLR = 0;
lock (_avgLock)
{
_firstSampleTime = DateTime.MinValue;
_lastSampleTime = DateTime.MinValue;
_firstMeterProductTimeSeconds = null;
_lastMeterProductTimeSeconds = null;
_meterTimeRebootCount = null;
_averageFlow = 0;
_averageFlowCount = 0;
log.Debug("Initializing datastream state");
}
simulatedPcbNr = null;
dataStreamState = DataStreamState.Flush;
currentFlowDir = InitFlowDir;
}
public void SaveMark(object mark)
{
/// TODO
}
public void EndSession()
{
StopDataStreamProcessing();
}
/// <summary>
/// Start this operation
/// </summary>
public void Start()
{
lock (this)
{
Clear();
ReadPulses();
StartDataStreamProcessing();
}
}
/// <summary>
/// Run this operation
/// </summary>
/// <returns>eventDone</returns>
public Event Run()
{
lock (this)
{
PublishBufferedOptical(false);
timeFromStart += StateMachine.Period;
ReadPulses();
//TODO read flow
if (_optoHeadService == null && opticalCaptureNotBeforeUtc.HasValue &&
DateTime.UtcNow >= opticalCaptureNotBeforeUtc.Value)
{
opticalCaptureNotBeforeUtc = null;
OpenOpticalCapture();
}
if (_optoHeadService!= null && !_optoHeadService.IsRunning)
StartOptohead();
if (!startSampleAcquired && (timeFromStart >= 8) && (currentTelegramIx >= 0))
{
/// Take the test start sample
startSampleAcquired = true;
TestStartTelegramIx = currentTelegramIx;
}
else if (startSampleAcquired)
{
/// Shift data in pipelines
TestEndTelegramIx = endTelegramIdx3;
endTelegramIdx3 = endTelegramIdx2;
endTelegramIdx2 = endTelegramIdx1;
endTelegramIdx1 = currentTelegramIx;
}
}
return Event.ReadRegisterDone;
}
private void StartOptohead()
{
ResetOpticalBatch();
lock (_avgLock)
{
_firstSampleTime = DateTime.MinValue;
_lastSampleTime = DateTime.MinValue;
_firstMeterProductTimeSeconds = null;
_lastMeterProductTimeSeconds = null;
_meterTimeRebootCount = null;
_averageFlow = 0;
_averageFlowCount = 0;
}
StartOptoTestInputLoop(new EventHandler<CommonRR.IPerl.communication.OptoReceivedEventArgs>(OnOptoHandler));
}
private bool OpenOptoConnection(PoseidonCfg iHeadCfg)
{
try
{
if (iHeadCfg != null)
{
if (_optoHeadService != null) return false;
// Optical data are an output-only stream. Resolve its
// framing from the versioned Poseidon profile rather than
// from the legacy CLI defaults.
PoseidonProtocolProfile profile = iHeadCfg.CreateProtocolProfile();
PoseidonOpticalHead opticalHead = new PoseidonOpticalHeadBuilder()
.WithComPort(iHeadCfg.OptoComPortNr)
.WithProfile(profile)
.Build();
OptoHeadService.Con connection = new OptoHeadService.Con(iHeadCfg.DebugLevel,
$"COM{opticalHead.ComPortNr}", profile.OpticalBaudRate,
profile.OpticalDataBits, profile.OpticalParity, profile.OpticalStopBits,
5000, 1000);
log.InfoFormat("POSEIDON_OPTO_OPEN: reader='{0}', port=COM{1}, profile={2}",
Name, opticalHead.ComPortNr, profile);
_optoHeadService = new OptoHeadService(connection, profile);
diagnosticFirstUtc = null;
diagnosticLastAccumulator = null;
diagnosticExtendedAccumulator = 0;
_optoHeadService.DiagnosticReceived = CaptureOpticalDiagnostic;
_optoHeadService.DiagnosticTelegramReceived = CaptureV1DiagnosticTelegram;
bool opened = _optoHeadService.CreateSerialConnection();
if (opened && iHeadCfg.ClearOpticalInputOnOpen)
_optoHeadService.DiscardPendingInput();
return opened;
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
private bool StartOptoTestInputLoop(EventHandler<CommonRR.IPerl.communication.OptoReceivedEventArgs> onOptoReceivedHandler)
{
try
{
if (_optoHeadService != null)
{
if (_optoHeadService.IsRunning) return false;
_optoHeadService.RunLoop(onOptoReceivedHandler);
//run loop runstate = true;
return true;
}
}
catch (Exception ex)
{
log.Error(ex.Message);
throw ex;
}
return false;
}
private void CaptureOpticalDiagnostic(byte[] raw, DateTime receivedUtc,
WaterMetrologyData data, bool simulatedPayload)
{
if (_poseidonCfg == null) return;
WaterMetrologyDataC2 parsed = data == null ? null : (data.C7Data ?? data.C2Data);
bool wrapped = false;
long? extended = null;
if (parsed != null && !simulatedPayload)
{
diagnosticExtendedAccumulator = PoseidonOpticalDiagnosticWriter.ExtendAccumulator(
parsed.Accumulator, diagnosticLastAccumulator, diagnosticExtendedAccumulator, out wrapped);
diagnosticLastAccumulator = parsed.Accumulator;
extended = diagnosticExtendedAccumulator;
}
if (!diagnosticFirstUtc.HasValue) diagnosticFirstUtc = receivedUtc;
opticalDiagnosticWriter.Write(_poseidonCfg.EnableDetailedLogPerWM,
_poseidonCfg.OpticalDiagnosticFormat, _poseidonCfg.RawOpticalDataFormat,
_poseidonCfg.IncludeParsedValues, Sequences.ProcessData.BatchNr,
Position > 0 ? Position.ToString() : Name, Name, SerialNr, receivedUtc,
simulatedPayload ? "OpticalService/SimulatedPayload" : "OpticalService/DriverBytes",
parsed == null ? "ParseRejected" : "Parsed",
raw, null,
parsed == null ? (object)null : parsed.Accumulator,
extended, wrapped,
parsed == null ? (object)null : parsed.FlowRateLPerS,
parsed == null ? (object)null : wmVolume,
(receivedUtc - diagnosticFirstUtc.Value).TotalSeconds,
null, null, "Stream", data == null ? null : data.ToString());
}
private void CaptureV1DiagnosticTelegram(PoseidonOpticalTelegram telegram)
{
if (_poseidonCfg == null || telegram == null || (telegram.C3 == null && telegram.C4 == null)) return;
string details = telegram.C3 != null ? telegram.C3.ToString() : telegram.C4.ToString();
byte[] raw = System.Text.Encoding.ASCII.GetBytes(telegram.RawLine ?? string.Empty);
opticalDiagnosticWriter.Write(_poseidonCfg.EnableDetailedLogPerWM,
_poseidonCfg.OpticalDiagnosticFormat, _poseidonCfg.RawOpticalDataFormat,
_poseidonCfg.IncludeParsedValues, Sequences.ProcessData.BatchNr,
Position > 0 ? Position.ToString() : Name, Name, SerialNr, telegram.ReceivedUtc,
"OpticalService/V1Diagnostic", "ParsedDiagnostic", raw, telegram.RawLine,
null, null, false, null, null, null, null, "Diagnostic", details);
}
private void OnOptoHandler(object sender, CommonRR.IPerl.communication.OptoReceivedEventArgs e)
{
//received data from optohead
WaterMetrologyData eWaterMetrologyData = e?.WaterMetrologyData;
if (GetMetrologyData(eWaterMetrologyData) != null)
{
// Measurement acquisition is never down-sampled. The optional
// buffer remains diagnostic/selection-only and cannot change the
// current Process view, start/end volume, or start/end time.
ApplyOpticalTelegram(eWaterMetrologyData);
if (ExperimentalOpticalSelectionEnabled)
BufferOpticalTelegram(eWaterMetrologyData);
}
}
private static WaterMetrologyDataC2 GetMetrologyData(WaterMetrologyData telegram)
{
return telegram == null ? null : (WaterMetrologyDataC2)telegram.C7Data ?? telegram.C2Data;
}
private bool ExperimentalOpticalSelectionEnabled
{
get
{
return _poseidonCfg != null && _poseidonCfg.EnableOpticalExperiments &&
(_poseidonCfg.EnableOpticalBatchSelection || _poseidonCfg.OnlyNewOpticalMeterSecond);
}
}
private void ResetOpticalBatch()
{
lock (opticalBatchLock)
{
opticalBatch.Clear();
opticalBatchStartedUtc = DateTime.MinValue;
lastBufferedMeterSecond = null;
}
}
private void BufferOpticalTelegram(WaterMetrologyData telegram)
{
lock (opticalBatchLock)
{
WaterMetrologyDataC2 metrology = GetMetrologyData(telegram);
double? meterSeconds = metrology.MeterProductTimeSeconds;
if (_poseidonCfg.OnlyNewOpticalMeterSecond && meterSeconds.HasValue)
{
double second = Math.Floor(meterSeconds.Value);
if (lastBufferedMeterSecond.HasValue && second <= lastBufferedMeterSecond.Value)
return;
lastBufferedMeterSecond = second;
}
if (opticalBatch.Count == 0) opticalBatchStartedUtc = DateTime.UtcNow;
opticalBatch.Add(telegram);
if (opticalBatch.Count >= EffectiveOpticalBatchSize)
TakeBufferedOpticalLocked();
}
}
private int EffectiveOpticalBatchSize
{
get { return _poseidonCfg != null && _poseidonCfg.EnableOpticalBatchSelection ? Math.Max(2, Math.Min(1000, _poseidonCfg.OpticalBatchSize)) : 1; }
}
private void PublishBufferedOptical(bool force)
{
lock (opticalBatchLock)
{
if (opticalBatch.Count == 0) return;
int timeoutSeconds = _poseidonCfg == null ? 30 : Math.Max(1, Math.Min(60, _poseidonCfg.OpticalBatchTimeoutSeconds));
if (force || DateTime.UtcNow.Subtract(opticalBatchStartedUtc).TotalSeconds >= timeoutSeconds)
TakeBufferedOpticalLocked();
}
}
private List<WaterMetrologyData> TakeBufferedOpticalLocked()
{
var selected = new List<WaterMetrologyData>();
if (opticalBatch.Count > 0)
{
selected.Add(opticalBatch[0]);
if (opticalBatch.Count > 1) selected.Add(opticalBatch[opticalBatch.Count - 1]);
}
opticalBatch.Clear();
opticalBatchStartedUtc = DateTime.MinValue;
return selected;
}
private void ApplyOpticalTelegram(WaterMetrologyData telegram)
{
WaterMetrologyDataC2 metrology = GetMetrologyData(telegram);
if (metrology == null) return;
double flowRateLPerS = metrology.FlowRateLPerS;
lock (_avgLock)
{
if (_averageFlowCount == 0)
{
_firstSampleTime = metrology.Dt;
_firstMeterProductTimeSeconds = metrology.MeterProductTimeSeconds;
_meterTimeRebootCount = metrology.MeterRebootCount;
}
_lastSampleTime = metrology.Dt;
UpdateMeterTime(metrology);
_averageFlowCount++;
_averageFlow += (flowRateLPerS - _averageFlow) / _averageFlowCount;
double elapsedSeconds = GetSampleDurationSeconds();
wmVolume = elapsedSeconds <= 0 ? 0 : _averageFlow * elapsedSeconds;
log.Info("Calculated Value:" + wmVolume);
}
}
/// <summary>
/// Stop this operation
/// </summary>
public void Stop()
{
log.DebugFormat("Flow filtering end, feature vector calculation start: {0:HH:mm:ss.fff}", DateTime.Now);
int startIx;
int endIx;
lock (this)
{
StopDataStreamProcessing();
AddTestStartEndMarksToData(out startIx, out endIx);
}
DataStreamPostProcessing();
// TODO: Enable when calculations completed
//
// float[] offsetV, kOhmsR, kOhmsC, dutFlow, refFlow, flowRatio, magField, emfV;
// x = Common.StatisticalMetrics.Calculate(optoData, optoDataCount, startIx, endIx, true,
// out offsetV, out kOhmsR, out kOhmsC, out dutFlow,
// out refFlow, out flowRatio, out magField, out emfV);
//
// log.DebugFormat("Feature vector calculation end, save opto-file start: {0:HH:mm:ss.fff}", DateTime.Now);
#if ORACLE_DB
if (test.RawDataId + (test.Repeats - repetitionNr) * test.RawDataIdRepetMulti != 0)
{
string relativeDirectory = Path.Combine(StateMachine.CycleStartTimeStamp.ToString("yy"),
StateMachine.CycleStartTimeStamp.ToString("MM"),
StateMachine.CycleStartTimeStamp.ToString("dd"));
string fileName = DetermineExtraDataFileName();
if (SaveOptoDataToFile(Path.Combine(OptoDataDirectory, relativeDirectory), fileName))
{
extraDataPath = Path.Combine(relativeDirectory, fileName);
}
log.WarnFormat("IPerlReader.Stop() startIx={0} endIx={1} len={2} raw data file = {3}",
startIx, endIx, optoData.Length, fileName);
}
else
#endif
{
log.WarnFormat("IPerlReader.Stop() startIx={0} endIx={1} len={2} no raw data file", startIx, endIx, optoData.Length);
}
long processedOpticalSamples;
lock (_avgLock)
{
processedOpticalSamples = _averageFlowCount;
}
// Poseidon V1 is decoded before the historical iPerl raw telegram
// buffer. That buffer deliberately stays empty because its fixed
// 42-character layout is not a Poseidon C1/C7 frame. The processed
// metrology count is therefore the authoritative missing-data check.
if (processedOpticalSamples < 2)
{
ResultCode |= (int)Results.Entities.ResultCode.MissingOptoData;
}
else if (VolumeLtrEnd == VolumeLtrStart)
{
ResultCode |= (int)Results.Entities.ResultCode.OptoDataWithZeroFlow;
}
}
////////////////////////////////////////////////////////
///
/// <summary>
/// New calibration factor calculated from the original factor (argument)
/// and results of any test(s).
/// Uses also: this.CalibTarget, this.VolumeLtrStart, this.VolumeLtrEnd
/// Side effects: this.OrigCalibFactor, this.PositiveCounting
/// </summary>
/// <param name="adjustTestResult">Test result for calculations</param>
/// <param name="originalCalibrationFactor">Original calibration factor</param>
/// <param name="factorLimitLo">Lower limit for the calibration factor</param>
/// <param name="factorLimitHi">Upper limit for the calibration factor</param>
/// <returns>New calibration factor or 0 (= Out of range)</returns>
public UInt16 CalculateNewCalibFactor(Results.Entities.MeterTestRslt adjustTestResult, UInt16 originalCalibrationFactor, UInt16 factorLimitLo, UInt16 factorLimitHi)
{
double meterVolume = adjustTestResult.VolumeMeter;
double targetVolume = adjustTestResult.VolumeRef * (1.0f + CalibTarget / 100.0f);
OrigCalibFactor = originalCalibrationFactor;
if (meterVolume > 1E-2)
{
PositiveCounting = VolumeLtrEnd > VolumeLtrStart;
UInt16 newFactor = (UInt16)((double)originalCalibrationFactor * targetVolume / meterVolume + 0.5);
log.InfoFormat("Calibration factor: orig={0} new={1} V_iperl={2} V_ref={3} V_target={4}",
originalCalibrationFactor,
newFactor,
meterVolume.ToString("F3"),
adjustTestResult.VolumeRef.ToString("F3"),
targetVolume.ToString("F3"));
if (newFactor < factorLimitLo || newFactor > factorLimitHi) return 0;
return newFactor;
}
else
{
log.ErrorFormat("Calibration factor: orig={0} new={0} (unchanged!) V_iperl={1}",
originalCalibrationFactor,
meterVolume.ToString("F3"));
return originalCalibrationFactor; /// Too small volume in the denominator -> no correction at all
}
}
/// <summary>
/// Store/update values to be used as a part of the opto-data log file name.
/// Stop data stream processing and saving, if it is enabled.
/// </summary>
/// <param name="test">Currently executed test</param>
/// <param name="repetitionNr">Currently executed repetition number</param>
public void TestIsGoingToStartSoon(Test _test, int _repetitionNr)
{
/// Store/update values to be used as a part of the opto-data log file name
this.test = _test;
this.repetitionNr = _repetitionNr;
if (IsDataStreamProcessing())
{
StopDataStreamProcessing();
/// Dummy '#### start test ####' and '#### end of test ####' marks are added
/// to the raw data file on request of Joern Goege
if (optoDataCount >= 100 && optoDataCount <= optoData.Length &&
optoData[40].Flags == OptoTelegramFlags.OK &&
optoData[optoDataCount - 40].Flags == OptoTelegramFlags.OK)
{
optoData[40].Flags = OptoTelegramFlags.OK_TestStart;
optoData[optoDataCount - 40].Flags = OptoTelegramFlags.OK_TestEnd;
}
DataStreamPostProcessing();
string pcbNr = (ConfigStruct != null) ? ConfigStruct.GetPcbNrString() : "UnknownPcbNr";
string wmPosition = Name.Substring(5); /// WMPosition is extracted from a component name in form 'iPerl#'
if (wmPosition.Length == 1) wmPosition = "0" + wmPosition;
string cycleStartTime = StateMachine.CycleStartTimeStamp.ToString("HH_mm_ss");
///
string relativeDirectory = Path.Combine(StateMachine.CycleStartTimeStamp.ToString("yy"),
StateMachine.CycleStartTimeStamp.ToString("MM"),
StateMachine.CycleStartTimeStamp.ToString("dd"));
string directory = Path.Combine(OptoDataDirectory, relativeDirectory);
string fileName = string.Format("{0}_{1}_{2}_{3}.txt", pcbNr, wmPosition, "WM", cycleStartTime);
if (SaveOptoDataToFile(directory, fileName))
{
extraDataPath = Path.Combine(relativeDirectory, fileName);
}
}
}
/// <summary>
/// Reads opto-datastream via serial port. Invoked from RunDeviceBefore()
///
/// Telegram description:
/// AAAAAA[tab]BBBB[tab]CCCC[tab]DDDDDD[tab]EEEE[tab]FFFFFFFF[tab]GG[cr][lf] (42 bytes)
/// Example:
/// FFFFFE 51EA 0000 65324E 0087 F6319DFF 86
/// FFDD3A 51F9 0000 65324E 0088 F631A60B 45
/// ...
/// </summary>
/// <param name="optoState">OptoState.Read or OptoState.Flush</param>
void ReadOptoData(DataStreamState optoState)
{
// lock (this)
// {
//
// }
}
public string ReadOptoData()
{
string received = ".";
// lock (this)
// {
//
// }
return received;
}
/// <summary>
///
/// Called from the state machine when a test is selected and UI needs to be updated.
/// </summary>
public void OnOptoReceived(object sender, OptoReceivedEventArgs args)
{
if (OptoReceivedHandler == null) return;
try { OptoReceivedHandler(sender, args); }
catch (Exception) { }
}
public event EventHandler<OptoReceivedEventArgs> OptoReceivedHandler;
void AddTestStartEndMarksToData(out int startIx, out int endIx)
{
startIx = BufferIdx(TestStartTelegramIx);
if ((startIx > 0) && (startIx < StartOptoDataCount) && (optoData[startIx].Flags == OptoTelegramFlags.OK))
{
optoData[startIx].Flags = OptoTelegramFlags.OK_TestStart;
OptoTelegramRaw.TestStartTimestampDec = optoData[startIx].TimestampDec();
}
else
{
for (int ix = 0; ix < StartOptoDataCount; ix++)
{
if (optoData[ix].Flags == OptoTelegramFlags.OK)
{
/// This is the first correct opto-telegram received
OptoTelegramRaw.TestStartTimestampDec = optoData[ix].TimestampDec();
break;
}
}
}
endIx = BufferIdx(TestEndTelegramIx);
if ((endIx > 0) && (optoData[endIx].Flags == OptoTelegramFlags.OK))
{
optoData[endIx].Flags = OptoTelegramFlags.OK_TestEnd;
}
}
/// <summary>
/// Data stream post processing:
/// Flow from a reference flowmeter is FIR filtered
/// </summary>
void DataStreamPostProcessing()
{
if (optoDataCount <= OptoDataBufferSize)
{
FIRFilterFlow(optoData, 0, optoDataCount - 1);
}
else
{
FIRFilterFlow(optoData, 0, StartOptoDataCount - 1);
FIRFilterFlow(optoData, (optoDataCount - EndOptoDataCount), optoDataCount - 1);
}
}
/// <summary>
/// Determine opto data file name: PCB_AA_BB_HH_MI_SS..txt
/// </summary>
/// <param name="testName">Test name</param>
/// <param name="testRepeats">Test repeats count (>= 1)</param>
/// <param name="repetitionNr">Repetition number (1 .. testRepeats)</param>
/// <returns></returns>
string DetermineExtraDataFileName()
{
///
/// Get required pieces of information
///
string pcbNr = (ConfigStruct != null) ? ConfigStruct.GetPcbNrString() : "UnknownPcbNr";
string wmPosition = Name.Substring(5); /// WMPosition is extracted from a component name in form 'iPerl#'
if (wmPosition.Length == 1) wmPosition = "0" + wmPosition;
string cycleStartTime = StateMachine.CycleStartTimeStamp.ToString("HH_mm_ss");
#if ORACLE_DB
string[] designations = string.IsNullOrEmpty(test.RawDataDesignation) ? new string[0] : test.RawDataDesignation.Split(new char[] { '~' });
int testId = test.RawDataId + (test.Repeats - repetitionNr) * test.RawDataIdRepetMulti;
string designation = string.IsNullOrEmpty(test.RawDataDesignation)
? testId.ToString(testId > 0 ? "D2" : "D1") /// Name is generated from Id
: (designations.Length > repetitionNr - 1) ? designations[repetitionNr - 1] /// Name is from 'RawDataDesignation' parameter
: string.Format("{0}-{1}", designations[0], repetitionNr); /// Name is form test name and repetition nr.
#else
int testId = 0;
string designation = (test.Repeats == 1) ? test.Name : string.Format("{0}-{1}", test.Name, repetitionNr);
#endif
///
/// Return the file name
///
return string.Format("{0}_{1}_{2}_{3}.txt", pcbNr, wmPosition, designation, cycleStartTime);
}
/// <summary>
/// Save opto data to a file.
/// </summary>
bool SaveOptoDataToFile(string directory, string fileName)
{
string fullFileName = Path.Combine(directory, fileName);
log.WarnFormat("Saving {0} raw data to {1}", Name, fullFileName);
try
{
Directory.CreateDirectory(directory);
double scalFact = ScalingFactor();
using (TextWriter optoLogFile = new StreamWriter(fullFileName))
{
if (optoDataCount <= OptoDataBufferSize)
{
/// Telegrams are stored continuously, save them.
optoLogFile.WriteLine(optoData[0].ToString(scalFact, null));
for (int i = 1; i < optoDataCount; i++)
{
optoLogFile.WriteLine(optoData[i].ToString(scalFact, optoData[i - 1]));
}
}
else /// if (optoDataCount > MaxOptoDataCount)
{
/// Buffer overflow
/// First part of the buffer is saved as is
optoLogFile.WriteLine(optoData[0].ToString(scalFact, null));
for (int i = 1; i < StartOptoDataCount; i++)
{
optoLogFile.WriteLine(optoData[i].ToString(scalFact, optoData[i - 1]));
}
optoLogFile.WriteLine(" ...");
/// Second part of the buffer is an overflowed circular buffer
optoLogFile.WriteLine(optoData[BufferIdx(optoDataCount)].ToString(scalFact, null));
for (int i = optoDataCount - EndOptoDataCount + 1; i < optoDataCount; i++)
{
optoLogFile.WriteLine(optoData[BufferIdx(i)].ToString(scalFact, optoData[BufferIdx(i - 1)]));
}
}
log.WarnFormat("{0} opto data successfully saved: {1} lines", Name, optoDataCount);
optoLogFile.Close();
}
return true;
}
catch (Exception exc)
{
File.Delete(fullFileName);
log.ErrorFormat(string.Format("Error writing into file {0}", fullFileName));
log.ErrorFormat(string.Format("Exception message: {0}", exc.Message));
return false;
}
}
void ReadPulses()
{
double elapsedSeconds = GetSampleDurationSeconds();
double volume = _averageFlow * elapsedSeconds;
//log.Debug("ReadPulses - Calculated Value:" + volume);
beginWMState = 1;
endWMState = beginWMState + volume ;
wmVolume = Math.Abs(endWMState - beginWMState);
wmPulses = (int)(wmVolume * (double)PulsesPerLtr + 0.5);
wmRefPulses = StateMachine.ControlBoardMain.RefPulses;
wmTestTime = elapsedSeconds;
}
private void UpdateMeterTime(WaterMetrologyDataC2 data)
{
if (data == null || !data.MeterProductTimeSeconds.HasValue || !data.MeterRebootCount.HasValue)
return;
if (!_meterTimeRebootCount.HasValue)
{
// The first C7 did not have a clock anchor, so keep host time
// for this measurement rather than mixing two time bases.
return;
}
if (_meterTimeRebootCount.Value != data.MeterRebootCount.Value)
{
log.WarnFormat("{0}: Poseidon ProductTime reboot counter changed from {1} to {2}; using PC receive time for this measurement.",
Name, _meterTimeRebootCount.Value, data.MeterRebootCount.Value);
_firstMeterProductTimeSeconds = null;
_lastMeterProductTimeSeconds = null;
return;
}
if (_firstMeterProductTimeSeconds.HasValue && data.MeterProductTimeSeconds.Value >= _firstMeterProductTimeSeconds.Value)
_lastMeterProductTimeSeconds = data.MeterProductTimeSeconds.Value;
}
private double GetSampleDurationSeconds()
{
if (_firstMeterProductTimeSeconds.HasValue && _lastMeterProductTimeSeconds.HasValue &&
_lastMeterProductTimeSeconds.Value >= _firstMeterProductTimeSeconds.Value)
return _lastMeterProductTimeSeconds.Value - _firstMeterProductTimeSeconds.Value;
if (_firstSampleTime == DateTime.MinValue || _lastSampleTime == DateTime.MinValue)
return 0;
return Math.Max(0, (_lastSampleTime - _firstSampleTime).TotalSeconds);
}
private void OpenOptoSerialPort(string comPort, int baudRate, Parity parity, int dataBits, StopBits stopBit, Handshake handshake)
{
if (DebugLevel == DebugMode.FailureDuringOperation) DebugLevel = DebugMode.Normal;
if (DebugLevel == DebugMode.Normal)
{
/// Open serial port: 9600 Bd, 8 data bits, 1 stop bit, no parity
try
{
CloseOptoSerialPort();
optoSerialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBit);
optoSerialPort.Handshake = handshake;
optoSerialPort.Open();
log.FatalFormat($"{Name} OptoPort opened: {this}");
}
catch (Exception ex)
{
log.FatalFormat($"{Name} OptoPort - error opening port: {this}" + Environment.NewLine + ex.Message);
throw ex;
}
}
else
{
optoSerialPort = null;
log.FatalFormat($"{Name} OproPort simulated: {this}");
}
}
private void CloseOptoSerialPort()
{
if (_optoHeadService != null)
{
_optoHeadService.CloseSerialConnection();
_optoHeadService = null;
log.FatalFormat($"{Name} OptoPort closed: {this}");
}
// Do not invoke HatCliDemo here. The caller that owns the direct
// NA2W command transport is responsible for restoring the meter
// optical mode after all consumers have stopped.
}
/// <summary>
/// Reset counters / indices / time and start processing and saving datastream data
/// </summary>
public void StartDataStreamProcessing()
{
try
{
// The optical connector is receive-only. Switching the meter
// mode belongs to PoseidonCommunication's radio transport;
// starting capture itself must never spawn the obsolete CLI.
int delaySeconds = EffectiveOpticalStartDelaySeconds;
if (delaySeconds > 0)
{
opticalCaptureNotBeforeUtc = DateTime.UtcNow.AddSeconds(delaySeconds);
log.InfoFormat("POSEIDON_OPTO_CAPTURE_DELAY: reader='{0}', seconds={1}", Name, delaySeconds);
}
else
{
OpenOpticalCapture();
}
}
catch (Exception e)
{
log.Error($"{Name} OptoPort - error opening port: {_poseidonCfg.OptoComPortNr}, Details: {e.Message}");
}
/// Reset opto-data, etc.
optoDataCount = 0;
timeFromStart = 0;
currentTelegramIx = -1;
startSampleAcquired = false;
TestStartTelegramIx = 0;
endTelegramIdx1 = 0;
endTelegramIdx2 = 0;
endTelegramIdx3 = 0;
TestEndTelegramIx = 0;
if (optoSerialPort != null && optoSerialPort.IsOpen) optoSerialPort.DiscardInBuffer();
if (flowDirectionDetection != null) flowDirectionDetection.ClearFifo(); /// Clear FIFO for flow direction detection
/// Enable opto-data parsing and saving
dataStreamState = DataStreamState.ProcessAndSave;
}
/// <summary>
/// Returns true when processing and saving datastream data is in progress
/// </summary>
bool IsDataStreamProcessing()
{
return dataStreamState == DataStreamState.ProcessAndSave;
}
/// <summary>
/// Stop processing and saving datastream data
/// </summary>
public void StopDataStreamProcessing()
{
PublishBufferedOptical(true);
opticalCaptureNotBeforeUtc = null;
dataStreamState = DataStreamState.Flush;
CloseOptoSerialPort();
}
private int EffectiveOpticalStartDelaySeconds
{
get
{
return _poseidonCfg != null && _poseidonCfg.EnableOpticalExperiments &&
_poseidonCfg.ClearOpticalInputOnOpen
? Math.Max(0, Math.Min(3600, _poseidonCfg.OpticalStartDelaySeconds)) : 0;
}
}
private void OpenOpticalCapture()
{
OpenOptoConnection(_poseidonCfg);
log.InfoFormat("POSEIDON_OPTO_CAPTURE_START: reader='{0}', port=COM{1}, cli=false",
Name, _poseidonCfg == null ? 0 : _poseidonCfg.OptoComPortNr);
}
/// <summary>
/// Compares CalibrationStruct.MeterType with iPerlCfg.MeterType.
/// iPerlCfg.MeterType == MeterType.AutoDetect disables type checking
/// CalibrationStruct == null disables type checking ...
/// ... so that failed RFID communication does not cause type verification failure)
/// </summary>
/// <returns>true when type is OK</returns>
public bool VerifyIPerlType()
{
if (_poseidonCfg.MeterType == MeterType.AutoDetect || CalibrationStruct == null)
{
return true;
}
return _poseidonCfg.MeterType == CalibrationStruct.MeterType;
}
public static double UnitVolume(VolumeUnits units)
{
switch (units)
{
default:
case VolumeUnits.m3: return Common.Units.ConvertFrom(Common.Unit.m3, 1.0); /// 1 liter
case VolumeUnits.UK_gallon: return Common.Units.ConvertFrom(Common.Unit.UKgal, 1.0); /// 1 imperial gallon
case VolumeUnits.US_gallon: return Common.Units.ConvertFrom(Common.Unit.USgal, 1.0); /// 1 US gallon
}
}
public double ScalingFactor()
{
if ((_poseidonCfg.MeterType == MeterType.AutoDetect) && (CalibrationStruct != null))
{
return ScalingFactor(CalibrationStruct.MeterType);
}
else if (_poseidonCfg.MeterType != MeterType.AutoDetect)
{
return ScalingFactor(_poseidonCfg.MeterType);
}
else
{
return ScalingFactor(MeterType.DN20);
}
}
/// <summary>
/// Scaling factor:
/// 0, 1 (DN15, Coax) . . . . 1
/// 2 (DN20) . . . . . . . . 2
/// 3 (DN25) . . . . . . . . 4
/// 4, 5 (DN26, DN32) . . . . 8
/// 6 (DN40) . . . . . . . . 16
/// </summary>
/// <param name="meterType">MeterType (0..6)</param>
/// <returns>Scaling factor</returns>
public static double ScalingFactor(MeterType meterType)
{
switch (meterType)
{
default:
case MeterType.DN15:
case MeterType.CoaxManifold:
return 1.0;
case MeterType.DN20:
return 2.0;
case MeterType.DN25:
return 4.0;
case MeterType.DN25_Q3_10:
case MeterType.DN32:
return 8.0;
case MeterType.DN40:
return 16.0;
}
}
/// <summary>
/// Calculate a filtered volume from data stream samples
/// </summary>
/// <param name="unwrappedIx">Samples used in calculation are centered around unwrappedIx</param>
/// <param name="samplesCount2">Count of samples used in calculation is 2 * smaplesCount2 + 1</param>
/// <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++)
{
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>
/// Calculate a filtered time from data stream samples
/// </summary>
/// <param name="unwrappedIx">Samples used in calculation are centered around unwrappedIx</param>
/// <param name="samplesCount2">Count of samples used in calculation is 2 * smaplesCount2 + 1</param>
/// <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++)
{
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>
/// Filter RefFlow data in an array of OptoTelegramRaw objects by a FIR filter:
///
/// kSize = 5, kSize2 = 2
///
/// i k
/// ---------------------------------------------------------------------------
/// 0 -5 filtered[0] = data[0]
/// 1 -4 filtered[1] = data[1]
/// 2 -3 filtered[2] = data[0]*k[0] + ... + data[4]*k[4]
/// 3 -2 filtered[3] = data[1]*k[0] + ... + data[5]*k[4]
/// 4 -1 filtered[4] = data[2]*k[0] + ... + data[6]*k[4]
/// 5 0 data[0] = filtered[0], filtered[0] = data[3]*k[0] + ... + data[7]*k[4]
/// 6 1 data[1] = filtered[1], filtered[1] = data[4]*k[0] + ... + data[8]*k[4]
/// 7 ...
/// </summary>
/// <param name="optoData">array of OptoTelegramRaw objects</param>
/// <param name="from">Index of the first optoData item to process</param>
/// <param name="to">Index of the last optoData item to process</param>
public static void FIRFilterFlow(OptoTelegramRaw[] optoData, int from, int to)
{
float[] kernel = new float[] { 0.1f, 0.2f, 0.4f, 0.2f, 0.1f };
int kSize = kernel.Length;
int kSize2 = kernel.Length / 2;
float[] filtered = new float[kSize];
for (int i = from; i <= to; i++)
{
if ((i < from + kSize2) || (i > to - kSize2))
{
/// Beginning or end of optoData buffer => Just copy data (=do not filter)
filtered[i % kSize] = optoData[BufferIdx(i)].RefFlow;
}
else
{
/// Make a convolution of optoData and the kernel
float weightedSum = 0;
for (int j = -kSize2; j <= kSize2; j++)
weightedSum += optoData[BufferIdx(i + j)].RefFlow * kernel[j + kSize2];
filtered[i % kSize] = weightedSum;
}
if (i >= from + kSize)
{
/// filtered[] buffer full => copy filtered data to optoData
optoData[BufferIdx(i - kSize)].RefFlow = filtered[i % kSize];
}
}
for (int i = to - kSize + 1; i <= to; i++)
{
if (i >= 0) optoData[BufferIdx(i)].RefFlow = filtered[i % kSize];
}
}
/// <summary>
/// Get index to optoData buffer
/// </summary>
/// <param name="index">Original unwrapped index</param>
/// <returns>Index to the buffer</returns>
public static int BufferIdx(int index)
{
if (index < SmartReader.OptoDataBufferSize)
{
return index;
}
else
{
return SmartReader.StartOptoDataCount + (index - SmartReader.OptoDataBufferSize) % SmartReader.EndOptoDataCount;
}
}
public void WriteBinary(BinaryWriter writer)
{
writer.Write(Disabled);
writer.Write(CommFailed);
writer.Write(ResultCode);
writer.Write(PositiveCounting);
if (ConfigStruct != null)
{
writer.Write(true);
ConfigStruct.WriteBinary(writer);
}
else writer.Write(false);
if (CalibrationStruct != null)
{
writer.Write(true);
CalibrationStruct.WriteBinary(writer);
}
else writer.Write(false);
if (CalibrationStructV4 != null)
{
writer.Write(true);
CalibrationStructV4.WriteBinary(writer);
}
else writer.Write(false);
writer.Write(OrigCalibFactor);
writer.Write(OrigCalibFactorLNA);
writer.Write(Q2ErrWOCorrection);
writer.Write(Q2CorrRL);
writer.Write(Q2CorrLR);
writer.Write(Diff2Hz8Hz);
writer.Write(Hz2CorrectionDone);
writer.Write(Hz2Correction);
if (LastTestResult != null)
{
writer.Write(true);
LastTestResult.WriteBinary(writer);
}
else writer.Write(false);
if (LastTestResult2 != null)
{
writer.Write(true);
LastTestResult2.WriteBinary(writer);
}
else writer.Write(false);
}
public void ReadBinary(BinaryReader reader)
{
Disabled = reader.ReadBoolean();
CommFailed = reader.ReadBoolean();
ResultCode = reader.ReadInt32();
PositiveCounting = reader.ReadBoolean();
if (reader.ReadBoolean()) (ConfigStruct = new ConfigStruct()).ReadBinary(reader);
if (reader.ReadBoolean()) (CalibrationStruct = new CalibrationStruct()).ReadBinary(reader);
if (reader.ReadBoolean()) (CalibrationStructV4 = new CalibrationStructV4()).ReadBinary(reader);
OrigCalibFactor = reader.ReadUInt16();
OrigCalibFactorLNA = reader.ReadUInt16();
Q2ErrWOCorrection = reader.ReadDouble();
Q2CorrRL = reader.ReadInt32();
Q2CorrLR = reader.ReadInt32();
Diff2Hz8Hz = reader.ReadDouble();
Hz2CorrectionDone = reader.ReadBoolean();
Hz2Correction = reader.ReadInt32();
if (reader.ReadBoolean()) (LastTestResult = new Results.Entities.MeterTestRslt()).ReadBinary(reader, null);
if (reader.ReadBoolean()) (LastTestResult2 = new Results.Entities.MeterTestRslt()).ReadBinary(reader, null);
}
public void ResetNfcInterface(bool? nfc_on = null)
{
if (_poseidonCfg.HeadCommunicationComPortNr == 0) return;
SERIAL_Driver _SERIAL_Driver_Head_Config = new SERIAL_Driver();
_SERIAL_Driver_Head_Config.OpenConnection($"COM{_poseidonCfg.HeadCommunicationComPortNr}", 9600, 8, Parity.None, StopBits.One);
NFCHeadConfig _NFCHead_Config = new NFCHeadConfig(_SERIAL_Driver_Head_Config);
if (nfc_on == null || nfc_on == false) _NFCHead_Config.NFCHeadConfig_SetInterface(false); // set RFID interface
if (nfc_on == null || nfc_on == true ) _NFCHead_Config.NFCHeadConfig_SetInterface(true); // set NFC interface
_SERIAL_Driver_Head_Config.Close();
_SERIAL_Driver_Head_Config.Dispose();
}
public void SetNfcInterface()
{
ResetNfcInterface(true);
}
public void SetRfidInterface()
{
ResetNfcInterface(false);
}
public void SetCommunicationInterface(string commInterface)
{
//using (ISession session = TBF.DB.ConfigDBSessionFactory.OpenSession())
// Replace the problematic line with the following code to fix the error:
using (ISession session = TBF.DB.SessionFactories[(int)DBKind.Config].OpenSession())
using (ITransaction tx = session.BeginTransaction())
{
try
{
var cmpntEntities = session.QueryOver<Component>()
.OrderBy(x => x.ItemNr).Asc
.List<Component>();
var cmpnt = cmpntEntities.Where(x => x.Name == Name).First();
if (cmpnt != null)
{
XDocument doc = XDocument.Parse(cmpnt.Parameters);
if (doc != null)
{
XElement element = doc.Root.Element("CommunicationInterface");
if (element != null)
{
element.Value = commInterface.ToString();
cmpnt.Parameters = doc.ToString();
session.SaveOrUpdate(cmpnt);
tx.Commit();
log.FatalFormat($"Set CommunicationInterface {Name} to {commInterface}");
}
}
}
}
catch (Exception ex)
{
if (tx != null) tx.Rollback();
log.FatalFormat($"Set CommunicationInterface {Name} error: {ex.Message}");
}
}
}
///
public OptoHeadState CheckFlowDirection()
{
return (flowDirectionDetection != null) ? flowDirectionDetection.CheckFlowDirection(currentFlowDir, Name) : OptoHeadState.DirNok;
}
///
public void ChangeFlowDirection()
{
switch (InitFlowDir)
{
case Counting.Positive:
currentFlowDir = Counting.Negative;
break;
case Counting.Negative:
currentFlowDir = Counting.Positive;
break;
case Counting.Arbitrary:
default:
currentFlowDir = Counting.Arbitrary;
break;
}
if (flowDirectionDetection != null) flowDirectionDetection.ClearFifo(); /// Clear FIFO for flow direction detection
}
/// <summary>
/// Clear data/counters related to a specific tests
/// </summary>
public void Clear()
{
ResultCode = 0;
volumeLtr = 0;
volumeLtr0 = 0;
extraDataPath = null;
/// Clear the feature vector
for (int i = 0; i < FeatureVectorSize; i++)
{
x[i] = 0;
}
}
public void TestCompleted()
{
/// TODO: Implement
}
}
}