Files
laatzen/Common/Hardware/WaterMeter/eRegister/eRegisterCore/eRegisterMeter.cs
T
2024-02-12 15:18:19 +01:00

696 lines
25 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xylem.Common.CommonCore.Consts;
using Xylem.Common.Hardware.Interfaces.Ports.PortCore;
using Xylem.Common.Hardware.Interfaces.Ports.PortCore.EventArguments;
using Xylem.Common.Hardware.Interfaces.Ports.SerialPorts;
using Xylem.Common.Hardware.Interfaces.Protocols.ProtocolCore;
using Xylem.Common.Hardware.Interfaces.Protocols.ProtocolCore.EventArguments;
using Xylem.Common.Hardware.Interfaces.Protocols.TransmitProtocol;
using Xylem.Common.Hardware.WaterMeter.eRegister.Protocols.StreamingProtocol;
using Xylem.Common.Hardware.WaterMeter.ERegister.DataPackages.MeasurementRecords;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore.Consts;
using Xylem.Common.Metrology.Measurements;
using Xylem.Common.Metrology.Measurements.Consts;
using Xylem.Common.Utils.Logging;
namespace Xylem.Common.Hardware.WaterMeter.eRegister.eRegisterCore
{
public class eRegisterMeter : WaterMeterCore.IMeter, WaterMeterCore.IMeterEvents
{
public String SerialNumber
{
get; set;
}
/// <inheritdoc />
public Int32 Slot
{
get; set;
}
/// <inheritdoc />
public Int32 IntermediateUpdateTimeS
{
get;
set;
} = 10;
/// <summary>
/// to reduce the IrdA communication in test bench, preparation will be done once (when SkipPreparationForTestBench is true)
/// </summary>
public Boolean SkipPreparationForTestBench
{
get; set;
}
private String _currentActionText = "";
/// <summary>
/// Hold the current process name e.g. FlowTest, Preadjustment for logging
/// </summary>
public String CurrentActionText
{
get => _currentActionText;
set
{
_currentActionText = value;
SetLogger();
}
}
private ILogger _logger;
/// <summary>
/// streaming port assignment/info
/// </summary>
private IPort StreamingPort
{
get;
set;
}
/// <summary>
/// streaming protocol assignment/info
/// </summary>
private StreamingProtocol StreamingProtocol;
/// <summary>
/// List of ongoing measurements, base- and calibration-measurements
/// </summary>
private List<IMeasurement> _listOfIMeasurement = new List<IMeasurement>();
/// <summary>
/// Enable raw record logging, if set every incoming package will be logged
/// </summary>
private Boolean _enableRawDataLogging;
public event EventHandler OnProcessStatusChanged;
public event EventHandler OnErrorStatusChanged;
public event EventHandler OnInitCompleted;
public event EventHandler OnMeasurementInitCompleted;
public event EventHandler OnMeasurementCompleted;
public event EventHandler OnCalibInitCompleted;
public event EventHandler OnCalibCompleted;
public event EventHandler OnDisposeCompleted;
/// <summary>
/// do not use it to set ProcessStatus
/// if you want to change ProcessStatus of this genesis use <see cref="ProcessStatus" />
/// <see cref="_myProcessStatus" /> is just store for some routines
/// </summary>
private ProcessState _myProcessStatus;
/// <inheritdoc />
/// if state is change
/// <see cref="OnProcessStatusChanged" />
/// will be invoked.
/// on some states other events will be invoke as well
public ProcessState ProcessStatus
{
get => _myProcessStatus;
private set
{
if (_myProcessStatus == value)
{
return;
}
_myProcessStatus = value;
Invoker(OnProcessStatusChanged);
switch (value)
{
case ProcessState.InitIsActive:
Invoker(OnInitCompleted);
break;
case ProcessState.MeasurementIsActive:
Invoker(OnMeasurementInitCompleted);
break;
case ProcessState.MeasurementIsDone:
Invoker(OnMeasurementCompleted);
break;
case ProcessState.CalibrationIsActive:
Invoker(OnCalibInitCompleted);
break;
case ProcessState.CalibrationIsDone:
Invoker(OnCalibCompleted);
break;
case ProcessState.QRefDone:
case ProcessState.WaitForQRef:
case ProcessState.WaitForCalibration:
case ProcessState.WaitForMeasurement:
case ProcessState.IsNotInit:
//no extra event needed
break;
default:
throw new OverflowException("MagFlux measurement unknown process status");
}
}
}
public void BuildAndCheckCalibFactorsAllChannels(Double refVolumeCm, Double? refTimeS = null, Double reqDeviationPercent = 0, Double maxCalibFactorTolerancePercent = 0)
{
//no calibration
}
public Boolean CheckStateAfterMeasurement()
{
return true;
}
/// <summary>
/// A helper to invoke events only if someone is listening, otherwise nothing will happen
/// </summary>
/// <param name="handler">Event handler to call</param>
/// <param name="sender">Sender (can be null)</param>
/// <param name="e">Event arguments (can be null)</param>
private void Invoker(EventHandler handler, Object sender = null, EventArgs e = null)
{
if (handler != null)
{
if (sender == null)
{
sender = this;
}
if (e == null)
{
e = new EventArgs();
}
handler.Invoke(sender, e);
}
// ReSharper disable once RedundantIfElseBlock
else
{
//nobody is listening
}
}
/// <inheritdoc />
/// <summary>
/// Start Event listening, has to be called after <see cref="SetupGenesisMeter" />
/// </summary>
public void ConnectMeter()
{
if (StreamingPort != null && StreamingPort.GetPortName() != BaseSerialPort.PortNotAssigned)
{
LinkPortToProtocol(StreamingPort, StreamingProtocol);
_logger.Trace($"Slot:{Slot} - StreamingPort and StreamingProtocol linked");
StreamingProtocol.OnRecordIsDecoded += StreamingProtocol_ApplyDecodedRecord;
}
_logger.Debug($"Slot:{Slot} - Connected and communication started");
}
/// <summary>
/// Add a port to working queue
/// </summary>
/// <param name="port">On <see cref="IPort" /> should one once added in runtime</param>
/// <param name="protocol"></param>
public void LinkPortToProtocol(IPort port, IProtocol protocol)
{
//for streaming mode only
if (port == null)
{
return;
}
port.OnRawRecordReceived += delegate (Object o, BasePortDataEventArgs rawMsg)
{
protocol.FillDecodingBuffer(rawMsg);
};
try
{
if (!port.IsOpen())
{
port.Open();
}
}
catch (Exception ex)
{
throw new ApplicationException($"Cannot Open Comport. Check TaskManager for other Genesis relevant programs and close them. Also check if the comport is valid! { Environment.NewLine }{ ex.Message}");
}
protocol.OnRecordReadyToSend += delegate (Object o, BasePortDataEventArgs dataToSend)
{
var data = (List<Byte>)dataToSend.GetData();
port.PortWrite(data.ToArray());
};
}
/// <summary>
/// Track all incoming led record packages (Calibration and Flow)
/// </summary>
/// <param name="sender"></param>
/// <param name="e">
/// I should be <see cref="MagFluxRecord" />
/// otherwise this method does nothing
/// </param>
private void StreamingProtocol_ApplyDecodedRecord(Object sender, BaseDataEventArgs e)
{
var result = e.GetEventData();
if (result is IMeasurementRecord measurementRecord)
{
if (measurementRecord is ERegisterRecord record)
{
WriteLog(record.ToString());
if (!record.IsValid)
{
return;
}
}
AddData(measurementRecord);//-0,1 bis -0,6
}
}
public void Dispose()
{
_logger.Trace($"Slot:{Slot} - Start to dispose");
StreamingProtocol.OnRecordIsDecoded -= StreamingProtocol_ApplyDecodedRecord;
LogRawData(false);
LogManager.Flush();
//isPart of Logout
StreamingPort?.Dispose();
StreamingProtocol?.Dispose();
_logger.Trace($"Slot:{Slot} - Dispose is finished");
}
public void DisposeMeter()
{
Dispose();
}
public List<MeasurementResults> GetAllMeasurementResults(Double? refVolume, Double? refTimeS, Boolean intermediateMeasurement = false, Int32? channel = null, MeasurementDirection dir = MeasurementDirection.TakeBoth)
{
if (!intermediateMeasurement && GetMeasurementState(channel) != MeasurementStates.IsCompleted)
{
throw new ApplicationException("Measurement is not completed");
}
var mainMeasurement = _listOfIMeasurement.FirstOrDefault(m => m.GetType() == typeof(ERegisterRecord));
if (mainMeasurement == null)
{
throw new ApplicationException("Can not find an ongoing measurement");
}
mainMeasurement.FlowDirectionforCalculatingVol = MeasurementDirection.TakeBoth;
var results = new List<MeasurementResults>();
var mainResult = intermediateMeasurement
? mainMeasurement.GetIntermediateMeasurementResult(refVolume, refTimeS)
: mainMeasurement.GetFinalMeasurementResult(refVolume, refTimeS);
results.Add(mainResult);
_logger.Info($"Slot:{Slot}, Channel:{mainMeasurement.GetChannel()} - MeasuredTime({mainResult.DutTimeS}s), " +
$"MeasuredVolume({mainResult.DutVolumeCm}Qm)");
foreach (var otherMeasurement in _listOfIMeasurement.Where(m => m.GetType() != typeof(ERegisterRecord)))
{
try
{
var otherResults = intermediateMeasurement
? otherMeasurement.GetIntermediateMeasurementResult(refVolume, refTimeS)
: otherMeasurement.GetFinalMeasurementResult(refVolume, refTimeS);
_logger.Info($"Slot:{Slot}, Channel:{otherMeasurement.GetChannel()} - ChannelTime({otherResults.DutTimeS}s), " +
$"ChannelVolume({otherResults.DutVolumeCm}Qm)");
results.Add(otherResults);
}
catch (Exception ex)
{
_logger.Warn($"Slot:{Slot}, No Results for channel:{otherMeasurement.GetChannel()} Ex: {ex.Message}");
if (channel == null)
{
throw new ApplicationException($"Can not read result from channel:{otherMeasurement.GetChannel() } Ex: {ex.Message}");
}
}
}
return results;
}
public MeasurementStates GetCalibrationState()
{
return GetMeasurementState();
}
public DisplayCodes GetLastProcessState()
{
throw new NotImplementedException();
}
public MeasurementResults GetMainMeasurementResult(Double? refVolume, Double? refTimeS, Boolean intermediateMeasurement = false, MeasurementDirection dir = MeasurementDirection.TakeBoth)
{
if (!intermediateMeasurement && GetMeasurementState(0) != MeasurementStates.IsCompleted)
{
throw new ApplicationException("Measurement is not completed");
}
if (dir != MeasurementDirection.TakeOnlyBackward)
{
_logger.Info($"Slot:{Slot} - Wrong MeasurementDirection no backwards volume for eRegister");
}
return GetAllMeasurementResults(refVolume, refTimeS, intermediateMeasurement, 0).First();
}
public MeasurementStates GetMeasurementState(Int32? onlyChannelNr = null)
{
_logger.Trace($"Slot:{Slot} - Get measurement state");
if (!_listOfIMeasurement.Any())
{
return MeasurementStates.NotStarted;
}
if (onlyChannelNr.HasValue)
{
var measurement = _listOfIMeasurement.First(f => f.GetChannel() == onlyChannelNr.Value);
return measurement.GetMeasurementState();
}
return _listOfIMeasurement.Min(m => m.MeasurementState);
}
public String GetPcbId()
{
return "1";
}
public void InitCalibration()
{
_logger.Info($"Slot:{Slot} - Init measurement");
PreMeasurement();
}
public void InitMeasurement()
{
_logger.Info($"Slot:{Slot} - Init measurement");
PreMeasurement();
}
private void PreMeasurement()
{
if (!SkipPreparationForTestBench)
{
SkipPreparationForTestBench = true;
}
else
{
WriteLog("Wait on measurement start");
}
ProcessStatus = ProcessState.WaitForMeasurement;
}
public Boolean Login()
{
return true;
}
public Boolean Login(String password, Boolean runImmediately = true, Boolean skipReadMeterFwAndAssignRegisters = false)
{
return true;
}
public Boolean Logout()
{
return true;
}
public void LogRawData(Boolean on)
{
_enableRawDataLogging = on;
if (StreamingPort is Interfaces.Ports.SerialPorts.LedSerialPort port)
{
port.RecordStreamingRawData = _enableRawDataLogging;
}
}
public Boolean RequestIntermediateMeasurementState(Int32? onlyChannelNr = null)
{
_logger.Trace($"Slot:{Slot} - Get measurement state");
if (!_listOfIMeasurement.Any())
{
return false;
}
Boolean? ret = null;
foreach (var item in _listOfIMeasurement)
{
if (!onlyChannelNr.HasValue || item.GetChannel() == onlyChannelNr.Value)
{
var measurement = _listOfIMeasurement.First(f => onlyChannelNr != null && f.GetChannel() == onlyChannelNr.Value);
if ((measurement.MeasurementState == MeasurementStates.IsRunning
|| measurement.MeasurementState == MeasurementStates.IsWaitingForIntermediateData))
{
measurement.RequestIntermediateRecord();
if (!ret.HasValue)
{
ret = true;
}
}
else
{
ret = false;
}
}
}
return ret.HasValue ? ret.Value : false;
}
public void SetCalibFactorsAllChannels(Boolean justLog = false)
{
throw new NotImplementedException();
}
public void SetLcdText(Boolean release, Byte[] textInHex)
{
//
}
public void SetProcessState(DisplayCodes newState, Boolean webRequest = true)
{
//
}
public void SetupFromConfigFile(Int32 slot, Boolean ignoreCorruptedData = true, Boolean useRequest = true, Boolean useStreaming = true)
{
Slot = slot;
var configFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "eRegister", ProgramConfig.SerialConfigFileName);
if (!System.IO.File.Exists(configFile))
{
configFile = Path.Combine(ProgramConfig.SerialConfigFileName);
if (!File.Exists(configFile))
{
throw new ApplicationException($"Configuration file {configFile} not found ");
}
}
var tr = new StreamReader(configFile);
var slotConfigList = JsonConvert.DeserializeObject<SlotConfig[]>(tr.ReadToEnd());
if (slotConfigList != null)
{
var slotConfig = slotConfigList.FirstOrDefault(t => t.Slot == slot);
if (slotConfig == null)
{
throw new ApplicationException($"Slot:{slot} - File " +
$"{ProgramConfig.SerialConfigFileName} does not contain valid configuration");
}
SetupMagFluxMeter(slot, null, slotConfig.Streaming, ignoreCorruptedData);
}
_logger.Debug($"Slot:{slot} - Configuration loaded");
}
/// <summary>
/// just internal setup. called on ctor or from vb6 setup function
/// </summary>
/// <param name="slot">Slot Number for test-bench </param>
/// <param name="requestPort"><see cref="PortConfig" /> for RFID/UART/IrDA Port</param>
/// <param name="streamingPort"><see cref="PortConfig" /> for LED Port</param>
/// <param name="ignoreCorruptedData">don´t send CRC error or telegrams with error flag to caller</param>
/// <param name="password">
/// If you have a password for highest access level you need, if you don't want to access the meter
/// (just read led record) than you can leave it nullS
/// </param>
private void SetupMagFluxMeter(Int32 slot, PortConfig? requestPort, PortConfig? streamingPort,
Boolean ignoreCorruptedData = true, String password = "")
{
Slot = slot;
//_password = password;
if (streamingPort != null)
{
var ledTransmit = new LedTransmitProtocol(streamingPort.Value.PortName);
var streamingIdent = $"Slot:{Slot}, Port:{streamingPort.Value.PortName}, Protocol:LED";
StreamingPort = new LedSerialPort(streamingIdent, streamingPort.Value.GetSerialPort(),
ledTransmit.GetTransmitPortSettings(9600));
StreamingProtocol = new StreamingProtocol(streamingIdent, ignoreCorruptedData);
}
SetLogger();
_logger.Debug($"Slot:{Slot} - Setup done");
}
public void StartCalibration()
{
StartMeasurement();
}
private void Measurement_ActionStateHasChanged(Object sender, EventArgs e)
{
SyncStreamingBuffer(SyncMarkRecord.DecodeIntermediate);
}
public void StartMeasurement()
{
_listOfIMeasurement = new List<IMeasurement>
{
new BaseMeasurement(Slot, typeof(ERegisterRecord), IntermediateUpdateTimeS)
};
foreach (var measurement in _listOfIMeasurement)
{
measurement.OnActionStateHasChanged += Measurement_ActionStateHasChanged;
}
_logger.Info($"Slot:{Slot} - Start measurement");
ProcessStatus = ProcessState.MeasurementIsActive;
_listOfIMeasurement.ForEach(m => m.MeasurementState = MeasurementStates.IsWaitingForStartData);
SyncStreamingBuffer(SyncMarkRecord.SyncStart);
}
public void StopCalibration()
{
StopMeasurement();
}
public void StopMeasurement()
{
_logger.Info($"Slot:{Slot} - Stop measurement");
ProcessStatus = ProcessState.MeasurementIsDone;
_listOfIMeasurement.ForEach(m => m.MeasurementState = MeasurementStates.IsWaitingForEndData);
SyncStreamingBuffer(SyncMarkRecord.SyncEnd);
}
private void AddData(IMeasurementRecord newRecord)
{
foreach (var measurement in _listOfIMeasurement)
{
if (measurement.GetType() != newRecord.GetType())
{
continue;
}
if (measurement.GetChannel() == newRecord.GetChannel())
{
measurement.AddData(newRecord);
}
}
// when every measurement has state IsRunning or every measurement has state IsCompleted, the streaming buffer set to skip decoding
if (_listOfIMeasurement.All(m => m.MeasurementState == MeasurementStates.IsRunning)
|| _listOfIMeasurement.All(m => m.MeasurementState == MeasurementStates.IsCompleted))
{
SyncStreamingBuffer(SyncMarkRecord.DecodeIntermediateQuality);
}
}
/// <summary>
/// Synchronization of the record for the streaming interface
/// </summary>
/// <param name="markRecord"></param>
/// <exception cref="ApplicationException"></exception>
private void SyncStreamingBuffer(SyncMarkRecord markRecord)
{
if (StreamingPort == null)
{
throw new ApplicationException("Synchronization not possible due to undefined streaming port");
}
StreamingPort.SynchronizeReceiveBuffer(markRecord);
}
public void TestBenchDispose()
{
//nothing todo
}
public void WriteLog(String text)
{
_logger.Info($"Slot:{Slot} - {text}");
}
#region logging
private void SetLogger()
{
if (_logger != null)
{
LogManager.Flush();
}
// the id is a combination of UniqueId stored in PcbId and SensorSN (SensorId)
var id = !string.IsNullOrEmpty(SerialNumber) ? $"_SN{SerialNumber}" : "?";
var fileName = $"eRegister_Slot_{Slot}";
if (string.IsNullOrEmpty(CurrentActionText))
{
_logger = NLogHelper.CreateOrGetMultiLogger($"Slot:{Slot}", $"", "Meter", "MeterBase", "MeterBase");
}
else
{
_logger = NLogHelper.CreateOrGetMultiLogger($"Slot:{Slot}_{id}_{CurrentActionText}", "Slot", "Meter", "MeterBase", "MeterBase");
//TODO check with roland
if (StreamingPort is LedSerialPort)
{
var streamingIdent = $"LedRawData_Slot_{Slot}_{id}_{CurrentActionText}";
((LedSerialPort)StreamingPort).Ident = streamingIdent;
((LedSerialPort)StreamingPort).RefreshLogger();
if (!string.IsNullOrEmpty(SerialNumber) && CurrentActionText.Contains("PG"))
{
//var pathMain = NLogHelper.GetPath(_logger);
//var pathRaw = NLogHelper.GetPath(((LedSerialPort)StreamingPort).GetRawLogger());
//var basePath = Path.GetDirectoryName(pathMain);
//var testRunString = CurrentActionText.Replace("PG", "");
//var lastChat = pathMain.LastIndexOf('\\');
//pathMain = pathMain.Substring(lastChat + 1);
//pathRaw = Path.GetFileName(pathRaw);
//var tmpUrl = $"http://10.49.40.25/MeterProcessState/api/TestBench/SetMeterLogPathInfo?SerialNumber={SerialNumber}&TestRunId={testRunString}&BasePath={basePath}&MainLogName={pathMain}&LEDName={pathRaw}";
//_logger.Debug($"Request Url: { tmpUrl}");
////ToDO: Update to service URl
//LocalWebRequest.GetRequest(tmpUrl);
}
}
}
}
#endregion
}
}