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;
}
///
public Int32 Slot
{
get; set;
}
///
public Int32 IntermediateUpdateTimeS
{
get;
set;
} = 10;
///
/// to reduce the IrdA communication in test bench, preparation will be done once (when SkipPreparationForTestBench is true)
///
public Boolean SkipPreparationForTestBench
{
get; set;
}
private String _currentActionText = "";
///
/// Hold the current process name e.g. FlowTest, Preadjustment for logging
///
public String CurrentActionText
{
get => _currentActionText;
set
{
_currentActionText = value;
SetLogger();
}
}
private ILogger _logger;
///
/// streaming port assignment/info
///
private IPort StreamingPort
{
get;
set;
}
///
/// streaming protocol assignment/info
///
private StreamingProtocol StreamingProtocol;
///
/// List of ongoing measurements, base- and calibration-measurements
///
private List _listOfIMeasurement = new List();
///
/// Enable raw record logging, if set every incoming package will be logged
///
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;
///
/// do not use it to set ProcessStatus
/// if you want to change ProcessStatus of this genesis use
/// is just store for some routines
///
private ProcessState _myProcessStatus;
///
/// if state is change
///
/// 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;
}
///
/// A helper to invoke events only if someone is listening, otherwise nothing will happen
///
/// Event handler to call
/// Sender (can be null)
/// Event arguments (can be null)
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
}
}
///
///
/// Start Event listening, has to be called after
///
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");
}
///
/// Add a port to working queue
///
/// On should one once added in runtime
///
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)dataToSend.GetData();
port.PortWrite(data.ToArray());
};
}
///
/// Track all incoming led record packages (Calibration and Flow)
///
///
///
/// I should be
/// otherwise this method does nothing
///
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 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();
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(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");
}
///
/// just internal setup. called on ctor or from vb6 setup function
///
/// Slot Number for test-bench
/// for RFID/UART/IrDA Port
/// for LED Port
/// don´t send CRC error or telegrams with error flag to caller
///
/// 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
///
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
{
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);
}
}
///
/// Synchronization of the record for the streaming interface
///
///
///
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
}
}