iPerl and iPerlHead separated, iPerl removed (WaterMeter should be used instead).

This commit is contained in:
Milan Hanajik
2017-06-08 09:14:30 +02:00
parent 8a4ad1c2d4
commit 21016a1500
27 changed files with 587 additions and 802 deletions
@@ -16,7 +16,7 @@ using log4net;
using Config.Entities;
using TBF.Resources;
using TBF.BenchControl.Sequences;
using TBF.BenchControl.WaterMeters.iPerl;
using TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead;
namespace TBF.BenchControl.TestMethods.iPerlCommunication
{
@@ -74,17 +74,17 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// <param name="boardNr">0..3</param>
/// <param name="comPort">Com port number</param>
/// <returns>Value returned by openPort(...)</returns>
public static unsafe int OpenPort(WaterMeters.iPerl.WaterMeter wm)
public static unsafe int OpenPort(IperlHead iperlHead)
{
if (wm.DebugLevel != DebugMode.Normal) return 0; /// No function in debug mode
if (iperlHead.DebugLevel != DebugMode.Normal) return 0; /// No function in debug mode
if (wm.RfidComPortNr > 0)
if (iperlHead.RfidComPortNr > 0)
{
return openPort1(wm.RfidComPortNr);
return openPort1(iperlHead.RfidComPortNr);
}
else
{
switch (wm.MuxBoardNr)
switch (iperlHead.MuxBoardNr)
{
default:
case 1: return openPort1(cfg.RfidPortNrBoard1);
@@ -101,17 +101,17 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// <param name="boardNr">0..3</param>
/// <param name="comPort">Com port number</param>
/// <returns>Value returned by openPort(...)</returns>
public static unsafe int ClosePort(WaterMeters.iPerl.WaterMeter wm)
public static unsafe int ClosePort(IperlHead iperlHead)
{
if (wm.DebugLevel != DebugMode.Normal) return 0; /// No function in debug mode
if (iperlHead.DebugLevel != DebugMode.Normal) return 0; /// No function in debug mode
if (wm.RfidComPortNr > 0)
if (iperlHead.RfidComPortNr > 0)
{
return closePort1();
}
else
{
switch (wm.MuxBoardNr)
switch (iperlHead.MuxBoardNr)
{
default:
case 1: return closePort1();
@@ -126,11 +126,11 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// Wrapper function with safe interface and unsafe body
/// </summary>
/// <returns>Value returned by readRequestPort(...)</returns>
public static unsafe int ReadRequestPort(WaterMeters.iPerl.WaterMeter wm, MessageID messageID, int offset, int lenght, out byte[] buffer, int timeout)
public static unsafe int ReadRequestPort(IperlHead iperlHead, MessageID messageID, int offset, int lenght, out byte[] buffer, int timeout)
{
buffer = new byte[lenght];
if (wm.DebugLevel != DebugMode.Normal) return wm.Name.Equals("iPerl13") ? 2 : 0; /// Simulates an error on position 13
if (iperlHead.DebugLevel != DebugMode.Normal) return iperlHead.Name.Equals("iPerl13") ? 2 : 0; /// Simulates an error on position 13
byte[] buf = new byte[200];
@@ -139,13 +139,13 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
{
int retv;
if (wm.RfidComPortNr > 0)
if (iperlHead.RfidComPortNr > 0)
{
retv = readRequestPort1(messageID, offset, lenght, pBuf, timeout);
}
else
{
switch (wm.MuxBoardNr)
switch (iperlHead.MuxBoardNr)
{
default:
case 1: retv = readRequestPort1(messageID, offset, lenght, pBuf, timeout); break;
@@ -160,11 +160,11 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
/// Logging
///
string name = string.Format("{0}({1})", wm.Name, wm.SerialNr);
if ((messageID == MessageID.Configuration) && (offset == 0) && (lenght == WaterMeters.iPerl.ConfigStruct.Length))
rfidDataLogger.InfoFormat("{0}: ReadRequestPort({1},...) returned {2} {3}", name, messageID, retv, (retv != 0) ? "!" : WaterMeters.iPerl.ConfigStruct.FromByteArray(buffer).ToString());
else if ((messageID == MessageID.Calibration) && (offset == 0) && (lenght == WaterMeters.iPerl.CalibrationStruct.Length))
rfidDataLogger.InfoFormat("{0}: ReadRequestPort({1},...) returned {2} {3}", name, messageID, retv, (retv != 0) ? "!" : WaterMeters.iPerl.CalibrationStruct.FromByteArray(buffer).ToString());
string name = string.Format("{0}({1})", iperlHead.Name, iperlHead.SerialNr);
if ((messageID == MessageID.Configuration) && (offset == 0) && (lenght == ConfigStruct.Length))
rfidDataLogger.InfoFormat("{0}: ReadRequestPort({1},...) returned {2} {3}", name, messageID, retv, (retv != 0) ? "!" : ConfigStruct.FromByteArray(buffer).ToString());
else if ((messageID == MessageID.Calibration) && (offset == 0) && (lenght == CalibrationStruct.Length))
rfidDataLogger.InfoFormat("{0}: ReadRequestPort({1},...) returned {2} {3}", name, messageID, retv, (retv != 0) ? "!" : CalibrationStruct.FromByteArray(buffer).ToString());
else if ((messageID == MessageID.Calibration) && (offset == 2) && (lenght == 2))
rfidDataLogger.InfoFormat("{0}: ReadRequestPort({1},2,2,...) returned {2} {3}", name, messageID, retv, (retv != 0) ? "!" : string.Format("Cal={0}", buf[0] + 256 * buf[1]));
else
@@ -178,21 +178,21 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// Wrapper function with safe interface adn unsafe body
/// </summary>
/// <returns>Value returned by writeRequestPort(...)</returns>
public static unsafe int WriteRequestPort(WaterMeters.iPerl.WaterMeter wm, MessageID messageID, int offset, int lenght, byte[] buffer, int timeout)
public static unsafe int WriteRequestPort(IperlHead iperlHead, MessageID messageID, int offset, int lenght, byte[] buffer, int timeout)
{
if (wm.DebugLevel != DebugMode.Normal) return 0;
if (iperlHead.DebugLevel != DebugMode.Normal) return 0;
fixed (byte* pBuf = buffer)
{
int retv;
if (wm.RfidComPortNr > 0)
if (iperlHead.RfidComPortNr > 0)
{
retv = writeRequestPort1(messageID, offset, lenght, pBuf, timeout);
}
else
{
switch (wm.MuxBoardNr)
switch (iperlHead.MuxBoardNr)
{
default:
case 1: retv = writeRequestPort1(messageID, offset, lenght, pBuf, timeout); break;
@@ -207,7 +207,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
/// Logging
///
string name = string.Format("{0}({1})", wm.Name, wm.SerialNr);
string name = string.Format("{0}({1})", iperlHead.Name, iperlHead.SerialNr);
if (lenght == 1)
rfidDataLogger.InfoFormat("{0}: WriteRequestPort({2}, {3}, {4}, {5}) returned {1} {6}", name, retv, messageID, offset, lenght, pBuf[0].ToString("X2"), (retv != 0) ? "!" : "");
else if (lenght == 2)
@@ -260,7 +260,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
PictureBox[] counters;
TextBox[] messages;
static IList<WaterMeters.iPerl.WaterMeter> waterMeters;
static IList<IperlHead> iperlHeads;
static IList<int> waterMeterPositions; /// keeps original indices in RegisterReaders list
Modbus.QuidoRS.QuidoRS quido;
@@ -331,7 +331,11 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
wmTextBox46, wmTextBox47, wmTextBox48,
};
formCompleted = false;
/// Initialize lists
iperlHeads = new List<IperlHead>();
waterMeterPositions = new List<int>();
formCompleted = false;
startTime = DateTime.Now;
startTimeSec = StateMachine.Time;
@@ -412,21 +416,18 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
void ConstructorCommon()
{
waterMeters = new List<WaterMeters.iPerl.WaterMeter>();
waterMeterPositions = new List<int>();
///
for (int wmPos = 0; wmPos < ProcessData.RegisterReaders.Length; wmPos++)
{
WaterMeters.iPerl.WaterMeter iPerl = ProcessData.RegisterReaders[wmPos] as WaterMeters.iPerl.WaterMeter;
IperlHead iperlHead = ProcessData.RegisterReaders[wmPos] as IperlHead;
if (iPerl != null)
if (iperlHead != null)
{
waterMeters.Add(iPerl);
iperlHeads.Add(iperlHead);
waterMeterPositions.Add(wmPos);
}
}
WaterMetersCount = waterMeters.Count;
WaterMetersCount = iperlHeads.Count;
ShuffleTextBoxes(WaterMetersCount, Config.Data.LineSize);
@@ -442,7 +443,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
completedCommCount = 0;
stopWorkerThreads = false;
foreach (var iPerl in iPerlCommunicationForm.waterMeters)
foreach (var iPerl in iPerlCommunicationForm.iperlHeads)
{
if (!rfidPortNrs.Contains(iPerl.MuxBoardNr))
{
@@ -510,9 +511,9 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
void Localize()
{
Text = Strings.Water_Meter_States;
for (int i = 0; i < Math.Min(textBoxesCount, waterMeters.Count); i++)
for (int i = 0; i < Math.Min(textBoxesCount, iperlHeads.Count); i++)
{
labels[i].Text = waterMeters[i].Name;
labels[i].Text = iperlHeads[i].Name;
}
}
@@ -541,9 +542,9 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
Top = (ls.iPerlCommunicationsFormTop != 0) ? ls.iPerlCommunicationsFormTop : 150;
/// Reset opto-data indication
for (int i = 0; i < waterMeters.Count; i++)
for (int i = 0; i < iperlHeads.Count; i++)
{
waterMeters[i].FlushedDataCount = 0;
iperlHeads[i].FlushedDataCount = 0;
counters[i].BackColor = Color.Red;
}
@@ -661,26 +662,29 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
int wmNr = 0;
bool wmFound = false;
foreach (var wm in waterMeters)
for (int j = 0; j < iperlHeads.Count; j++)
{
if ((wm.MuxBoardNr == rfidPortNr) && (wm.Group == group))
IperlHead ihead = iperlHeads[j];
if ((ihead.MuxBoardNr == rfidPortNr) && (ihead.Group == group))
{
wmFound = true;
WaterMeters.WaterMeter.WaterMeter wm = SequenceBase.WaterMeters[waterMeterPositions[j]] as WaterMeters.WaterMeter.WaterMeter; /// WaterMeters.WaterMeter.WaterMeter implements iPerl specific variables
CommErr error;
string resultStr = string.Empty;
if (activity.ToLower().Contains(ReadConfigurationStr.ToLower())) error = ReadConfiguration(wm, ref resultStr);
else if (activity.ToLower().Contains(SetTestModeStr.ToLower())) error = SetTestMode(wm, ref resultStr);
else if (activity.ToLower().Equals(SetActiveModeStr.ToLower())) error = SetActiveMode(wm, ref resultStr);
else if (activity.ToLower().Equals(ReadCalibrationStr.ToLower())) error = ReadCalibration(wm, ref resultStr);
else if (activity.ToLower().Contains(WriteCalibrationFactorStr.ToLower())) error = WriteCalibrationFactor(wm, ref resultStr);
else if (activity.ToLower().Equals(NormalizeCalibrationFactorStr.ToLower())) error = NormalizeCalibrationFactor(wm, ref resultStr);
else if (activity.ToLower().Equals(ResetQ2CorrectionStr.ToLower())) error = ResetQ2Correction(wm, ref resultStr);
else if (activity.ToLower().Equals(WriteQ2CorrectionStr.ToLower())) error = WriteQ2Correction(wm, ref resultStr, false); /// standard iPerl
else if (activity.ToLower().Equals(WriteQ2CorrectionAltStr.ToLower())) error = WriteQ2Correction(wm, ref resultStr, true); /// DEWA iPerl
else if (activity.ToLower().Equals(Reset2HzCorrectionStr.ToLower())) error = Reset2HzCorrection(wm, ref resultStr);
else if (activity.ToLower().Equals(Write2HzCorrectionStr.ToLower())) error = Write2HzCorrection(wm, ref resultStr);
if (activity.ToLower().Contains(ReadConfigurationStr.ToLower())) error = ReadConfiguration(ihead, wm, ref resultStr);
else if (activity.ToLower().Contains(SetTestModeStr.ToLower())) error = SetTestMode(ihead, wm, ref resultStr);
else if (activity.ToLower().Equals(SetActiveModeStr.ToLower())) error = SetActiveMode(ihead, wm, ref resultStr);
else if (activity.ToLower().Equals(ReadCalibrationStr.ToLower())) error = ReadCalibration(ihead, wm, ref resultStr);
else if (activity.ToLower().Contains(WriteCalibrationFactorStr.ToLower())) error = WriteCalibrationFactor(ihead, wm, ref resultStr);
else if (activity.ToLower().Equals(NormalizeCalibrationFactorStr.ToLower())) error = NormalizeCalibrationFactor(ihead, wm, ref resultStr);
else if (activity.ToLower().Equals(ResetQ2CorrectionStr.ToLower())) error = ResetQ2Correction(ihead, wm, ref resultStr);
else if (activity.ToLower().Equals(WriteQ2CorrectionStr.ToLower())) error = WriteQ2Correction(ihead, wm, ref resultStr, false); /// standard iPerl
else if (activity.ToLower().Equals(WriteQ2CorrectionAltStr.ToLower())) error = WriteQ2Correction(ihead, wm, ref resultStr, true); /// DEWA iPerl
else if (activity.ToLower().Equals(Reset2HzCorrectionStr.ToLower())) error = Reset2HzCorrection(ihead, wm, ref resultStr);
else if (activity.ToLower().Equals(Write2HzCorrectionStr.ToLower())) error = Write2HzCorrection(ihead, wm, ref resultStr);
else
{
error = CommErr.None;
@@ -692,20 +696,20 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
{
OnCommCompleted(null, new CommCompletedEventArgs(threadId, wmNr, resultStr));
}
else if (wm.CommFailed || error == CommErr.CommFailed)
else if (ihead.CommFailed || error == CommErr.CommFailed)
{
OnCommCompleted(null, new CommCompletedEventArgs(threadId, wmNr, "Watermeter is disabled"));
}
else
{
OnCommCompleted(null, new CommCompletedEventArgs(threadId, wmNr, string.Format("{0} failed ({1}) !!!", activity, error)));
rfidDataLogger.ErrorFormat("Group={0}, Board={1}, {2} failed ({3}) !!!", currentGroup, wm.MuxBoardNr, activity, error);
wm.CommFailed = true;
rfidDataLogger.ErrorFormat("Group={0}, Board={1}, {2} failed ({3}) !!!", currentGroup, ihead.MuxBoardNr, activity, error);
ihead.CommFailed = true;
}
break;
}
wmNr++;
TBF.UiBridge.Bridge.OnTestProgress(null, new TBF.UiBridge.TestProgressEventArgs(tests[i], Config.Entities.Progress.FlowSetting));
TBF.UiBridge.Bridge.OnTestProgress(null, new TBF.UiBridge.TestProgressEventArgs(tests[i], Config.Entities.Progress.FlowSetting));
}
if (!wmFound)
@@ -730,10 +734,10 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// <summary>
/// Read a complete configuration structure of the watermeter
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr ReadConfiguration(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr ReadConfiguration(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
///
/// The activity is "Read configuration" (this enables the watermeter, resets error flag)
@@ -741,12 +745,12 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
if (!multiTestParams[currentActivityStep].Activity.ToLower().Contains(" if enabled"))
{
wm.CommFailed = false;
ihead.CommFailed = false;
}
if (wm.CommFailed) return CommErr.CommFailed;
if (ihead.CommFailed) return CommErr.CommFailed;
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.Read;
@@ -754,16 +758,16 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
byte[] config = null;
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == ReadRequestPort(wm, MessageID.Configuration, 0, ConfigStruct.Length, out config, cfg.CommTimeout))
if (0 == ReadRequestPort(ihead, MessageID.Configuration, 0, ConfigStruct.Length, out config, cfg.CommTimeout))
{
error = CommErr.None;
wm.ConfigStruct = ConfigStruct.FromByteArray(config);
resultStr = wm.ConfigStruct.ToString(1);
ihead.ConfigStruct = ConfigStruct.FromByteArray(config);
resultStr = ihead.ConfigStruct.ToString(1);
break;
}
}
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -775,12 +779,12 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// whether the testModeConfig is correctly set, if necessary it is changed to the specified value.
/// Read a part of configuration afterwards to verify the mode was set correctly.
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr SetTestMode(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr SetTestMode(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
if (wm.CommFailed) return CommErr.CommFailed;
if (ihead.CommFailed) return CommErr.CommFailed;
Byte testModeConfig = 0xA0; /// Default value
///
@@ -794,41 +798,41 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
}
}
if (wm.ConfigStruct.MeterState == MeterState.Test && wm.ConfigStruct.TestModeConfig == testModeConfig)
if (ihead.ConfigStruct.MeterState == MeterState.Test && ihead.ConfigStruct.TestModeConfig == testModeConfig)
{
/// Already in the correct test mode
resultStr = "Already " + wm.ConfigStruct.ToString(1);
resultStr = "Already " + ihead.ConfigStruct.ToString(1);
return CommErr.None;
}
/// Communication necessary
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.None;
if (error==CommErr.None && (wm.ConfigStruct.TestModeConfig != testModeConfig) && (wm.ConfigStruct.MeterState != MeterState.Active))
if (error==CommErr.None && (ihead.ConfigStruct.TestModeConfig != testModeConfig) && (ihead.ConfigStruct.MeterState != MeterState.Active))
{
/// Switch to Active mode in order to change TestModeConfig
error = CommErr.CmdActive;
byte[] cmd = new byte[1] { (byte)6 };
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.Command, 0, 1, cmd, cfg.CommTimeout)) { error = CommErr.None; break; }
if (0 == WriteRequestPort(ihead, MessageID.Command, 0, 1, cmd, cfg.CommTimeout)) { error = CommErr.None; break; }
}
Thread.Sleep(250);
}
if (error == CommErr.None && (wm.ConfigStruct.TestModeConfig != testModeConfig))
if (error == CommErr.None && (ihead.ConfigStruct.TestModeConfig != testModeConfig))
{
/// Change the TestModeConfig if necessary
error = CommErr.Write;
byte[] tstMdCfg = new byte[1] { testModeConfig };
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.Configuration, 21, 1, tstMdCfg, cfg.CommTimeout))
if (0 == WriteRequestPort(ihead, MessageID.Configuration, 21, 1, tstMdCfg, cfg.CommTimeout))
{
wm.ConfigStruct.Update(21, tstMdCfg);
ihead.ConfigStruct.Update(21, tstMdCfg);
error = CommErr.None;
break;
}
@@ -844,7 +848,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
byte[] cmd = new byte[1] { (byte)7 };
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.Command, 0, 1, cmd, cfg.CommTimeout)) { error = CommErr.None; break; }
if (0 == WriteRequestPort(ihead, MessageID.Command, 0, 1, cmd, cfg.CommTimeout)) { error = CommErr.None; break; }
}
Thread.Sleep(250);
@@ -858,20 +862,20 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
byte[] cfg_0_3 = null;
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == ReadRequestPort(wm, MessageID.Configuration, 0, 4, out cfg_0_3, cfg.CommTimeout))
if (0 == ReadRequestPort(ihead, MessageID.Configuration, 0, 4, out cfg_0_3, cfg.CommTimeout))
{
wm.ConfigStruct.Update(0, cfg_0_3);
if (wm.ConfigStruct.MeterState == MeterState.Test)
ihead.ConfigStruct.Update(0, cfg_0_3);
if (ihead.ConfigStruct.MeterState == MeterState.Test)
{
error = CommErr.None;
resultStr = wm.ConfigStruct.ToString(1);
resultStr = ihead.ConfigStruct.ToString(1);
break;
}
}
}
}
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -881,12 +885,12 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// Set the watermeter to the active mode.
/// Read a part of configuration afterwards to verify the mode was set correctly.
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr SetActiveMode(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr SetActiveMode(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.CmdActive;
@@ -894,7 +898,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
byte[] cmd = new byte[1] { (byte)6 };
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.Command, 0, 1, cmd, cfg.CommTimeout))
if (0 == WriteRequestPort(ihead, MessageID.Command, 0, 1, cmd, cfg.CommTimeout))
{
error = CommErr.None;
break;
@@ -928,14 +932,14 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
#else
if (error == CommErr.None)
{
if (wm.ConfigStruct == null)
if (ihead.ConfigStruct == null)
resultStr = "OK (Config not available)";
else
resultStr = wm.ConfigStruct.ToString(1);
resultStr = ihead.ConfigStruct.ToString(1);
}
#endif
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -944,14 +948,14 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// <summary>
/// Read a complete calibration structure from the watermeter
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr ReadCalibration(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr ReadCalibration(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
if (wm.CommFailed) return CommErr.CommFailed;
if (ihead.CommFailed) return CommErr.CommFailed;
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.Read;
@@ -959,16 +963,19 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
byte[] calib = null;
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == ReadRequestPort(wm, MessageID.Calibration, 0, CalibrationStruct.Length, out calib, cfg.CommTimeout))
if (0 == ReadRequestPort(ihead, MessageID.Calibration, 0, CalibrationStruct.Length, out calib, cfg.CommTimeout))
{
wm.CalibrationStruct = CalibrationStruct.FromByteArray(calib);
resultStr = wm.CalibrationStruct.ToString();
error = wm.VerifyIPerlType() ? CommErr.None : CommErr.WrongIPerlType;
ihead.CalibrationStruct = CalibrationStruct.FromByteArray(calib);
#if IPERL
if (wm != null && wm.OriginalCalibFactor == 0) wm.OriginalCalibFactor = ihead.CalibrationStruct.Calibration;
#endif
resultStr = ihead.CalibrationStruct.ToString();
error = ihead.VerifyIPerlType() ? CommErr.None : CommErr.WrongIPerlType;
break;
}
}
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -978,12 +985,12 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// Write the calculated calibration factor to the water meter.
/// Read a part of CalibrationStruct afterwards to verify factor was written correctly.
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr WriteCalibrationFactor(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr WriteCalibrationFactor(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
if (wm.CommFailed) return CommErr.CommFailed;
if (ihead.CommFailed) return CommErr.CommFailed;
///
/// Parse calibration factor (1 argument) or calibration factor limits (2 arguments)
@@ -1002,7 +1009,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
UInt16.TryParse(arguments[0], out factorLimitLo) && factorLimitLo > 0 &&
UInt16.TryParse(arguments[1], out factorLimitHi) && factorLimitHi > 0)
{
newCalibFactor = wm.CalculateNewCalibFactor(wm.CalibrationFactor, factorLimitLo, factorLimitHi);
newCalibFactor = ihead.CalculateNewCalibFactor(ihead.CalibrationFactor, factorLimitLo, factorLimitHi);
}
else if (arguments.Length == 1 && UInt16.TryParse(arguments[0], out val) && val > 0)
{
@@ -1010,12 +1017,12 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
}
else
{
newCalibFactor = wm.CalculateNewCalibFactor(wm.CalibrationFactor, wm.FactorLimitLo, wm.FactorLimitHi);
newCalibFactor = ihead.CalculateNewCalibFactor(ihead.CalibrationFactor, ihead.FactorLimitLo, ihead.FactorLimitHi);
}
}
else
{
newCalibFactor = wm.CalculateNewCalibFactor(wm.CalibrationFactor, wm.FactorLimitLo, wm.FactorLimitHi);
newCalibFactor = ihead.CalculateNewCalibFactor(ihead.CalibrationFactor, ihead.FactorLimitLo, ihead.FactorLimitHi);
}
if (newCalibFactor == 0) return CommErr.CalibFactorOoRange;
@@ -1023,7 +1030,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
/// Start communication with iPerl
///
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error;
byte[] data = new byte[2] { (byte)(newCalibFactor & 0x00FF), (byte)((newCalibFactor >> 8) & 0x00FF) };
@@ -1034,31 +1041,34 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// Write the new calibration factor (up to cfg.MaxCommRetries tims)
///
error = CommErr.Write;
if (0 == WriteRequestPort(wm, MessageID.Calibration, 2, 2, data, cfg.CommTimeout))
if (0 == WriteRequestPort(ihead, MessageID.Calibration, 2, 2, data, cfg.CommTimeout))
{
///
/// Read and verify the calibration factor
///
error = CommErr.ReadAfterWrite;
byte[] calib_2_3 = null;
if (0 == ReadRequestPort(wm, MessageID.Calibration, 2, 2, out calib_2_3, cfg.CommTimeout))
if (0 == ReadRequestPort(ihead, MessageID.Calibration, 2, 2, out calib_2_3, cfg.CommTimeout))
{
error = CommErr.Verify;
if (calib_2_3 != null && calib_2_3.Length == 2 && data[0] == calib_2_3[0] && data[1] == calib_2_3[1])
{
error = CommErr.None;
wm.CalibrationStruct.Update(data, 2);
resultStr = wm.CalibrationStruct.ToString();
ihead.CalibrationStruct.Update(data, 2);
#if IPERL
if (wm != null) wm.CalibFactor = newCalibFactor;
#endif
resultStr = ihead.CalibrationStruct.ToString();
break;
}
}
}
wm.CalibrationStruct.Update(data, 2);
ihead.CalibrationStruct.Update(data, 2);
}
while (++writeAndVerifyRetries <= cfg.MaxCommRetries);
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -1067,26 +1077,26 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// <summary>
/// Normalize calibration factor in case ti is close to value 8000.
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr NormalizeCalibrationFactor(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr NormalizeCalibrationFactor(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
if (wm.CommFailed) return CommErr.CommFailed;
if (ihead.CommFailed) return CommErr.CommFailed;
if (wm.CalibrationFactor <= 5000)
if (ihead.CalibrationFactor <= 5000)
{
resultStr = "Calibratin factor is OK";
return CommErr.None; /// No need to update the calibration factor
}
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.Write;
/// Determine the new calibration factor
UInt16 newCalibFactor = 0;
switch (wm.CalibrationStruct.MeterType)
switch (ihead.CalibrationStruct.MeterType)
{
case MeterType.DN15: newCalibFactor = 2650; break;
case MeterType.DN20: newCalibFactor = 3746; break;
@@ -1104,10 +1114,10 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
byte[] data = new byte[2] { (byte)(newCalibFactor & 0x00FF), (byte)((newCalibFactor >> 8) & 0x00FF) };
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.Calibration, 2, 2, data, cfg.CommTimeout))
if (0 == WriteRequestPort(ihead, MessageID.Calibration, 2, 2, data, cfg.CommTimeout))
{
error = CommErr.None;
wm.CalibrationStruct.Update(data, 2);
ihead.CalibrationStruct.Update(data, 2);
break;
}
}
@@ -1120,17 +1130,17 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
byte[] calib_2_3 = null;
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == ReadRequestPort(wm, MessageID.Calibration, 2, 2, out calib_2_3, cfg.CommTimeout))
if (0 == ReadRequestPort(ihead, MessageID.Calibration, 2, 2, out calib_2_3, cfg.CommTimeout))
{
error = CommErr.None;
wm.CalibrationStruct.Update(calib_2_3, 2);
resultStr = wm.CalibrationStruct.ToString();
ihead.CalibrationStruct.Update(calib_2_3, 2);
resultStr = ihead.CalibrationStruct.ToString();
break;
}
}
}
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -1144,14 +1154,14 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// Reset both Q2 correction factors in the memory to 0.
/// Read them back to verify factors were written correctly.
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr ResetQ2Correction(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr ResetQ2Correction(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
if (wm.CommFailed) return CommErr.CommFailed;
if (ihead.CommFailed) return CommErr.CommFailed;
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.Write;
@@ -1160,7 +1170,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.MetrologyMemory, Q2CorrFactorsAddr, wrData.Length, wrData, cfg.CommTimeout))
if (0 == WriteRequestPort(ihead, MessageID.MetrologyMemory, Q2CorrFactorsAddr, wrData.Length, wrData, cfg.CommTimeout))
{
error = CommErr.None;
break;
@@ -1194,11 +1204,11 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
if (error == CommErr.None)
{
resultStr = "Q2 corrections reset to 0";
wm.Q2CorrRFlow = 0;
ihead.Q2CorrRFlow = 0;
}
#endif
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -1207,14 +1217,14 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// <summary>
/// Reset 2Hz correction factor in the memory to 0.
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr Reset2HzCorrection(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr Reset2HzCorrection(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
if (wm.CommFailed) return CommErr.CommFailed;
if (ihead.CommFailed) return CommErr.CommFailed;
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.Write;
@@ -1223,7 +1233,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.MetrologyMemory, Hz2CorrFactorsAddr, wrData.Length, wrData, cfg.CommTimeout))
if (0 == WriteRequestPort(ihead, MessageID.MetrologyMemory, Hz2CorrFactorsAddr, wrData.Length, wrData, cfg.CommTimeout))
{
error = CommErr.None;
break;
@@ -1257,11 +1267,11 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
if (error == CommErr.None)
{
resultStr = "2Hz correction reset to 0";
wm.Hz2CorrectionFactor = 0;
ihead.Hz2CorrectionFactor = 0;
}
#endif
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -1271,17 +1281,17 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// Write the calculated Q2 correction factors to the memory.
/// Read them back to verify factors were written correctly.
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr WriteQ2Correction(WaterMeters.iPerl.WaterMeter wm, ref string resultStr, bool DEWA)
static CommErr WriteQ2Correction(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr, bool DEWA)
{
if (wm.CommFailed) return CommErr.CommFailed;
if (wm.LastTestResult == null) return CommErr.CommFailed; /// This should never happen
if (ihead.CommFailed) return CommErr.CommFailed;
if (ihead.LastTestResult == null) return CommErr.CommFailed; /// This should never happen
wm.Q2ErrorWOCorrection = wm.LastTestResult.Error;
wm.Q2CorrectionDone = false;
wm.Q2CorrRFlow = 0;
ihead.Q2ErrorWOCorrection = ihead.LastTestResult.Error;
ihead.Q2CorrectionDone = false;
ihead.Q2CorrRFlow = 0;
double q2Correction = 0;
Byte q2CorrRFlow = 0;
@@ -1292,13 +1302,13 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
/// Standard process
///
if (Math.Abs(wm.LastTestResult.Error) <= 0.5)
if (Math.Abs(ihead.LastTestResult.Error) <= 0.5)
{
resultStr = string.Format("Q2 correction = 0 (writing bypassed)");
return CommErr.None;
}
if (!wm.CalculateQ2CorrectionFactor(wm.LastTestResult, out q2Correction))
if (!ihead.CalculateQ2CorrectionFactor(ihead.LastTestResult, out q2Correction))
{
return CommErr.None; /// Q2 error is too large, water meter failed anyhow
}
@@ -1311,18 +1321,18 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
/// DEWA process
///
if (wm.LastTestResult.Error >= 0 && wm.LastTestResult.Error <= 1.0)
if (ihead.LastTestResult.Error >= 0 && ihead.LastTestResult.Error <= 1.0)
{
resultStr = string.Format("Q2 correction = 0 (writing bypassed)");
return CommErr.None;
}
if (!wm.CalculateQ2CorrectionFactor(wm.LastTestResult, out q2Correction))
if (!ihead.CalculateQ2CorrectionFactor(ihead.LastTestResult, out q2Correction))
{
return CommErr.None; /// Q2 error is too large, water meter failed anyhow
}
if (wm.LastTestResult.Error < 0)
if (ihead.LastTestResult.Error < 0)
{
q2CorrRFlow = (byte)((int)Math.Round(1.1 * q2Correction) & 0x000000FF);
q2CorrLFlow = (byte)((int)Math.Round(1.1 * q2Correction) & 0x000000FF);
@@ -1334,7 +1344,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
}
}
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.Write;
@@ -1342,7 +1352,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.MetrologyMemory, Q2CorrFactorsAddr, wrData.Length, wrData, cfg.CommTimeout))
if (0 == WriteRequestPort(ihead, MessageID.MetrologyMemory, Q2CorrFactorsAddr, wrData.Length, wrData, cfg.CommTimeout))
{
error = CommErr.None;
break;
@@ -1366,9 +1376,21 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
{
error = CommErr.None;
resultStr = string.Format("Q2 factors: R-flow={0}, L-flow={1}", (SByte)q2CorrRFlow, (SByte)q2CorrLFlow);
rfidDataLogger.Warn(wm.Name + ": " + resultStr);
wm.Q2CorrectionDone = true;
wm.Q2CorrectionFactor = q2CorrectionFactor;
rfidDataLogger.Warn(ihead.Name + ": " + resultStr);
ihead.Q2CorrectionDone = true;
ihead.Q2Correction = q2Correction;
ihead.Q2CorrRFlow = (int)(sbyte)q2CorrRFlow;
ihead.Q2CorrLFlow = (int)(sbyte)q2CorrLFlow;
#if IPERL
if (wm != null)
{
wm.Q2ErrorWOCorrection = ihead.Q2ErrorWOCorrection;
wm.Q2CorrectionDone = ihead.Q2CorrectionDone;
wm.Q2Correction = ihead.Q2Correction;
wm.Q2CorrRFlow = ihead.Q2CorrRFlow;
wm.Q2CorrLFlow = ihead.Q2CorrLFlow;
}
#endif
break;
}
}
@@ -1377,15 +1399,25 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
if (error == CommErr.None)
{
resultStr = string.Format("Q2 correction: R-flow={0}, L-flow={1}", (SByte)q2CorrRFlow, (SByte)q2CorrLFlow);
rfidDataLogger.Warn(wm.Name + ": " + resultStr);
wm.Q2CorrectionDone = true;
wm.Q2Correction = q2Correction;
wm.Q2CorrRFlow = (int)(sbyte)q2CorrRFlow;
wm.Q2CorrLFlow = (int)(sbyte)q2CorrLFlow;
rfidDataLogger.Warn(ihead.Name + ": " + resultStr);
ihead.Q2CorrectionDone = true;
ihead.Q2Correction = q2Correction;
ihead.Q2CorrRFlow = (int)(sbyte)q2CorrRFlow;
ihead.Q2CorrLFlow = (int)(sbyte)q2CorrLFlow;
#if IPERL
if (wm != null)
{
wm.Q2ErrorWOCorrection = ihead.Q2ErrorWOCorrection;
wm.Q2CorrectionDone = ihead.Q2CorrectionDone;
wm.Q2Correction = ihead.Q2Correction;
wm.Q2CorrRFlow = ihead.Q2CorrRFlow;
wm.Q2CorrLFlow = ihead.Q2CorrLFlow;
}
#endif
}
#endif
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -1394,17 +1426,17 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
/// <summary>
/// Write the calculated 2Hz correction factor to the memory.
/// </summary>
/// <param name="wm">Water meter object</param>
/// <param name="ihead">Water meter object</param>
/// <param name="resultStr">String passed to caller</param>
/// <returns>true on success</returns>
static CommErr Write2HzCorrection(WaterMeters.iPerl.WaterMeter wm, ref string resultStr)
static CommErr Write2HzCorrection(IperlHead ihead, WaterMeters.WaterMeter.WaterMeter wm, ref string resultStr)
{
if (wm.CommFailed) return CommErr.CommFailed;
if (ihead.CommFailed) return CommErr.CommFailed;
/// Calculate the correction
wm.Hz2CorrectionDone = false;
ihead.Hz2CorrectionDone = false;
int hz2CorrectionFactor;
bool wmOK = wm.Calculate2HzCorrectionFactor(wm.LastTestResult2, wm.LastTestResult, out wm.Diff2Hz8Hz, out hz2CorrectionFactor);
bool wmOK = ihead.Calculate2HzCorrectionFactor(ihead.LastTestResult2, ihead.LastTestResult, out ihead.Diff2Hz8Hz, out hz2CorrectionFactor);
if (hz2CorrectionFactor == 0)
{
@@ -1412,7 +1444,7 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
return CommErr.None;
}
if (OpenPort(wm) != 0) return CommErr.OpenPort; /// Open RFID port
if (OpenPort(ihead) != 0) return CommErr.OpenPort; /// Open RFID port
CommErr error = CommErr.Write;
@@ -1421,9 +1453,18 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
///
for (int j = 0; j < cfg.MaxCommRetries; j++)
{
if (0 == WriteRequestPort(wm, MessageID.MetrologyMemory, Hz2CorrFactorsAddr, wrData.Length, wrData, cfg.CommTimeout))
if (0 == WriteRequestPort(ihead, MessageID.MetrologyMemory, Hz2CorrFactorsAddr, wrData.Length, wrData, cfg.CommTimeout))
{
error = CommErr.None;
ihead.Hz2CorrectionFactor = hz2CorrectionFactor;
ihead.Hz2CorrectionDone = true;
#if IPERL
if (wm != null)
{
wm.Hz2CorrectionDone = ihead.Hz2CorrectionDone;
wm.Hz2CorrectionFactor = ihead.Hz2CorrectionFactor;
}
#endif
break;
}
}
@@ -1455,13 +1496,13 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
if (error == CommErr.None)
{
resultStr = string.Format("2Hz correction = {0}", (SByte)hz2CorrectionByte);
rfidDataLogger.Warn(wm.Name + ": " + resultStr);
wm.Hz2CorrectionDone = true;
wm.Hz2CorrectionFactor = hz2CorrectionFactor;
rfidDataLogger.Warn(ihead.Name + ": " + resultStr);
ihead.Hz2CorrectionDone = true;
ihead.Hz2CorrectionFactor = hz2CorrectionFactor;
}
#endif
ClosePort(wm); /// Close RFID port
ClosePort(ihead); /// Close RFID port
return error;
}
@@ -1482,9 +1523,9 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
{
if (data.WMNr >= 0) messages[data.WMNr].Text = data.CommMessage;
for (int i = 0; i < waterMeters.Count; i++)
for (int i = 0; i < iperlHeads.Count; i++)
{
counters[i].BackColor = (waterMeters[i].FlushedDataDelta == 0) ? Color.Red : Color.Green;
counters[i].BackColor = (iperlHeads[i].FlushedDataDelta == 0) ? Color.Red : Color.Green;
}
lock (this)
@@ -1567,21 +1608,19 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
tstRslt.EndTime = endTime;
tstRslt.FlowSetTime = 0;
tstRslt.TestTime += testTime; /// [s] total communication time of all tests
for (int i = 0; i < waterMeters.Count; i++)
{
Results.Entities.MeterTestRslt meterRslt =
for (int i = 0; i < iperlHeads.Count; i++)
{
Results.Entities.MeterTestRslt meterRslt =
ProcessData.BatchRslts.GetMeterTestRslt(test.Name, waterMeterPositions[i], Config.Entities.CompoundMeterId.Single);
WaterMeters.iPerl.WaterMeter iPerl = waterMeters[i] as WaterMeters.iPerl.WaterMeter;
if (meterRslt != null && iPerl != null)
{
meterRslt.WaterMeter.SerialNr = iPerl.SerialNr;
meterRslt.Passed = (!iPerl.CommFailed && !iPerl.Disabled);
meterRslt.TestDone = true;
}
}
if (meterRslt != null && iperlHeads[i] != null)
{
meterRslt.WaterMeter.SerialNr = iperlHeads[i].SerialNr;
meterRslt.Passed = (!iperlHeads[i].CommFailed && !iperlHeads[i].Disabled);
meterRslt.TestDone = true;
}
}
}
}
}
@@ -124,14 +124,14 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
for (int i = 0; i < Config.Data.WMsCount; i++)
{
WaterMeters.iPerl.WaterMeter iPerl = ((sensPath.RegisterReaders != null) && (i < sensPath.RegisterReaders.Length))
? (sensPath.RegisterReaders[i] as WaterMeters.iPerl.WaterMeter)
: null;
TestMethods.iPerlCommunication.iPerlHead.IperlHead iPerl = ((sensPath.RegisterReaders != null) && (i < sensPath.RegisterReaders.Length))
? (sensPath.RegisterReaders[i] as TestMethods.iPerlCommunication.iPerlHead.IperlHead)
: null;
if (iPerl != null)
{
/// TODO: Reimplement
//iPerl.LastTestResult = meterRslt; /// Save this water meter test result to iPerl WM
iPerl.NominalTestFlow = 500.0 * (double)(test.Qfrom + test.Qto); /// Ave. + convert to liter/hour
iPerl.NominalTestFlowLph = 500.0 * (double)(test.Qfrom + test.Qto); /// Ave. + convert to liter/hour
}
}
@@ -293,9 +293,9 @@ namespace TBF.BenchControl.TestMethods.iPerlCommunication
Results.Entities.MeterTestRslt meterRslt = ProcessData.BatchRslts.GetMeterTestRslt(testName, i, CompoundMeterId.Single);
/// Reference to iPerl water meter or null:
WaterMeters.iPerl.WaterMeter iPerl = ((sensPath.RegisterReaders != null) && (i < sensPath.RegisterReaders.Length))
? (sensPath.RegisterReaders[i] as WaterMeters.iPerl.WaterMeter)
: null;
TestMethods.iPerlCommunication.iPerlHead.IperlHead iPerl = ((sensPath.RegisterReaders != null) && (i < sensPath.RegisterReaders.Length))
? (sensPath.RegisterReaders[i] as TestMethods.iPerlCommunication.iPerlHead.IperlHead)
: null;
if (meterRslt != null && oriMeterRslt != null)
{
@@ -0,0 +1,188 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public class CalibrationStruct
{
public static readonly int Length = 35;
public Byte Version;
public MeterType MeterType;
public UInt16 Calibration;
public VolumeUnits VolumeUnits;
public FlowArrow FlowArrow;
public UInt16 FWVersion;
public UInt16[] TargetField;
public UInt16 RecipMeanCurrent;
public UInt16 ThresholdVolume;
public UInt16 ThresholdTime;
public UInt16 FlowActivationThr;
public UInt16 VolumeArrowThr;
public UInt32 CalibrationTime;
public ulong SerialNumber;
public MeterSealed MeterSealed;
public byte CheckSum;
public CalibrationStruct()
{
TargetField = new UInt16[3];
}
public byte[] ToByteArray()
{
byte[] result = new byte[Length];
result[0] = Version;
result[1] = (byte)MeterType;
result[2] = (byte)(Calibration & 0x00FF);
result[3] = (byte)((Calibration >> 8) & 0x00FF);
result[4] = (byte)VolumeUnits;
result[5] = (byte)FlowArrow;
result[6] = (byte)(FWVersion & 0x00FF);
result[7] = (byte)((FWVersion >> 8) & 0x00FF);
result[8] = (byte)( TargetField[0] & 0x00FF);
result[9] = (byte)((TargetField[0] >> 8) & 0x00FF);
result[10] = (byte)( TargetField[1] & 0x00FF);
result[11] = (byte)((TargetField[1] >> 8) & 0x00FF);
result[12] = (byte)( TargetField[2] & 0x00FF);
result[13] = (byte)((TargetField[2] >> 8) & 0x00FF);
result[14] = (byte)(RecipMeanCurrent & 0x00FF);
result[15] = (byte)((RecipMeanCurrent >> 8) & 0x00FF);
result[16] = (byte)(ThresholdVolume & 0x00FF);
result[17] = (byte)((ThresholdVolume >> 8) & 0x00FF);
result[18] = (byte)(ThresholdTime & 0x00FF);
result[19] = (byte)((ThresholdTime >> 8) & 0x00FF);
result[20] = (byte)(FlowActivationThr & 0x00FF);
result[21] = (byte)((FlowActivationThr >> 8) & 0x00FF);
result[22] = (byte)(VolumeArrowThr & 0x00FF);
result[23] = (byte)((VolumeArrowThr >> 8) & 0x00FF);
result[24] = (byte)(CalibrationTime & 0x000000FF);
result[25] = (byte)((CalibrationTime >> 8) & 0x000000FF);
result[26] = (byte)((CalibrationTime >> 16) & 0x000000FF);
result[27] = (byte)((CalibrationTime >> 24) & 0x000000FF);
result[28] = (byte)(SerialNumber & 0x00000000000000FF);
result[29] = (byte)((SerialNumber >> 8) & 0x00000000000000FF);
result[30] = (byte)((SerialNumber >> 16) & 0x00000000000000FF);
result[31] = (byte)((SerialNumber >> 24) & 0x00000000000000FF);
result[32] = (byte)((SerialNumber >> 32) & 0x00000000000000FF);
result[33] = (byte)MeterSealed;
result[34] = CheckSum;
return result;
}
/// <summary>
/// Create a calibration structure from a complete byte array
/// </summary>
/// <param name="data">A complete byte array data</param>
/// <returns>CalibrationStruct or null when byte array was not complete</returns>
public static CalibrationStruct FromByteArray(byte[] data)
{
if (data.Length != Length) return null;
CalibrationStruct result = new CalibrationStruct();
result.Version = data[0];
result.MeterType = (MeterType)data[1];
result.Calibration = (UInt16)(data[2] + 256 * data[3]);
result.VolumeUnits = (VolumeUnits)data[4];
result.FlowArrow = (FlowArrow)data[5];
result.FWVersion = (UInt16)(data[6] + 256 * data[7]);
result.TargetField[0] = (UInt16)(data[8] + 256 * data[9]);
result.TargetField[1] = (UInt16)(data[10] + 256 * data[11]);
result.TargetField[2] = (UInt16)(data[12] + 256 * data[13]);
result.RecipMeanCurrent = (UInt16)(data[14] + 256 * data[15]);
result.ThresholdVolume = (UInt16)(data[16] + 256 * data[17]);
result.ThresholdTime = (UInt16)(data[18] + 256 * data[19]);
result.FlowActivationThr = (UInt16)(data[20] + 256 * data[21]);
result.VolumeArrowThr = (UInt16)(data[22] + 256 * data[23]);
result.CalibrationTime = (((UInt32)data[27] * 256 + data[26]) * 256 + data[25]) * 256 + data[24];
result.SerialNumber = ((((UInt64)data[32] * 256 + data[31]) * 256 + data[30]) * 256 + data[29]) * 256 + data[28];
result.MeterSealed = (MeterSealed)data[33];
result.CheckSum = data[34];
return result;
}
/// <summary>
/// Update the calibration structure from an incomplete byte array
/// </summary>
/// <param name="data">Byte array data</param>
/// <param name="offset">Offset of byte array data in CalibrationStruct</param>
/// <returns>true when successful, false when data are not appropriate</returns>
public bool Update(byte[] data, int offset)
{
if (offset == 2 && data.Length == 2)
{
/// Data containing iPerl calibration factor
Calibration = (UInt16)(data[2 - offset] + 256 * data[3 - offset]);
return true;
}
else if (offset == 0 && data.Length == Length)
{
/// Data containing a complete CalibrationStruct
Version = data[0];
MeterType = (MeterType)data[1];
Calibration = (UInt16)(data[2] + 256 * data[3]);
VolumeUnits = (VolumeUnits)data[4];
FlowArrow = (FlowArrow)data[5];
FWVersion = (UInt16)(data[6] + 256 * data[7]);
TargetField[0] = (UInt16)(data[8] + 256 * data[9]);
TargetField[1] = (UInt16)(data[10] + 256 * data[11]);
TargetField[2] = (UInt16)(data[12] + 256 * data[13]);
RecipMeanCurrent = (UInt16)(data[14] + 256 * data[15]);
ThresholdVolume = (UInt16)(data[16] + 256 * data[17]);
ThresholdTime = (UInt16)(data[18] + 256 * data[19]);
FlowActivationThr = (UInt16)(data[20] + 256 * data[21]);
VolumeArrowThr = (UInt16)(data[22] + 256 * data[23]);
CalibrationTime = (((UInt32)data[27] * 256 + data[26]) * 256 + data[25]) * 256 + data[24];
SerialNumber = ((((UInt64)data[32] * 256 + data[31]) * 256 + data[30]) * 256 + data[29]) * 256 + data[28];
MeterSealed = (MeterSealed)data[33];
CheckSum = data[34];
return true;
}
else
return false;
}
public override string ToString()
{
return string.Format("Calibration: V{0} Type={1} Cal={2} Units={3} FlowArrow.{4} FW={5} Hi={6} Norm={7} Low={8} RMC={9} ThrVol={10} ThrTime={11} FlActThr={12} VolArrThr={13} CalTm={14} SN={15} MeterSealed={16} Chksum={17}",
Version,
MeterType,
Calibration,
VolumeUnits,
FlowArrow,
FWVersion,
TargetField[0],
TargetField[1],
TargetField[2],
RecipMeanCurrent,
ThresholdVolume,
ThresholdTime,
FlowActivationThr,
VolumeArrowThr,
CalibrationTime,
SerialNumber,
MeterSealed,
CheckSum.ToString("X2"));
}
}
}
@@ -0,0 +1,225 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public class ConfigStruct
{
public static readonly int Length = 32;
public Byte Version;
public MeterState MeterState;
public UInt32 TargetTimeVeryLowBatt; /// in seconds
public UInt32 TargetTimeLowBatt; /// in seconds
public UInt32 TestModeTime; /// Max. test mode time in seconds
public UInt16 EmptyPipeThreshold;
public byte[] PCBNumber; /// 5 bytes
public byte TestModeConfig;
public UInt32 RadioAddress;
public UInt16 TempCalibration;
public UInt16 AlarmMask; /// Default 0xA3F7
public UInt16 ConfigCheckSum;
public ConfigStruct()
{
PCBNumber = new byte[5];
}
public byte[] ToByteArray()
{
byte[] result = new byte[Length];
result[0] = Version;
result[1] = (byte)MeterState;
result[2] = (byte)(TargetTimeVeryLowBatt & 0x000000FF);
result[3] = (byte)((TargetTimeVeryLowBatt >> 8) & 0x000000FF);
result[4] = (byte)((TargetTimeVeryLowBatt >> 16) & 0x000000FF);
result[5] = (byte)((TargetTimeVeryLowBatt >> 24) & 0x000000FF);
result[6] = (byte)(TargetTimeLowBatt & 0x000000FF);
result[7] = (byte)((TargetTimeLowBatt >> 8) & 0x000000FF);
result[8] = (byte)((TargetTimeLowBatt >> 16) & 0x000000FF);
result[9] = (byte)((TargetTimeLowBatt >> 24) & 0x000000FF);
result[10] = (byte)(TestModeTime & 0x000000FF);
result[11] = (byte)((TestModeTime >> 8) & 0x000000FF);
result[12] = (byte)((TestModeTime >> 16) & 0x000000FF);
result[13] = (byte)((TestModeTime >> 24) & 0x000000FF);
result[14] = (byte)(EmptyPipeThreshold & 0x00FF);
result[15] = (byte)((EmptyPipeThreshold >> 8) & 0x00FF);
result[16] = PCBNumber[0];
result[17] = PCBNumber[1];
result[18] = PCBNumber[2];
result[19] = PCBNumber[3];
result[20] = PCBNumber[4];
result[21] = TestModeConfig;
result[22] = (byte)(RadioAddress & 0x000000FF);
result[23] = (byte)((RadioAddress >> 8) & 0x000000FF);
result[24] = (byte)((RadioAddress >> 16) & 0x000000FF);
result[25] = (byte)((RadioAddress >> 24) & 0x000000FF);
result[26] = (byte)(TempCalibration & 0x00FF);
result[27] = (byte)((TempCalibration >> 8) & 0x00FF);
result[28] = (byte)(AlarmMask & 0x00FF);
result[29] = (byte)((AlarmMask >> 8) & 0x00FF);
result[30] = (byte)(ConfigCheckSum & 0x00FF);
result[31] = (byte)((ConfigCheckSum >> 8) & 0x00FF);
return result;
}
/// <summary>
/// Create a configuration structure from a complete byte array
/// </summary>
/// <param name="data">A complete byte array data</param>
/// <returns>ConfigStruct or null when byte array was not complete</returns>
public static ConfigStruct FromByteArray(byte[] data)
{
if (data.Length != Length) return null;
ConfigStruct result = new ConfigStruct();
result.Version = data[0];
result.MeterState = (MeterState)data[1];
result.TargetTimeVeryLowBatt = (((UInt32)data[5] * 256 + data[4]) * 256 + data[3]) * 256 + data[2];
result.TargetTimeLowBatt = (((UInt32)data[9] * 256 + data[8]) * 256 + data[7]) * 256 + data[6];
result.TestModeTime = (((UInt32)data[13] * 256 + data[12]) * 256 + data[11]) * 256 + data[10];
result.EmptyPipeThreshold = (UInt16)(data[15] * 256 + data[14]);
result.PCBNumber[0] = data[16];
result.PCBNumber[1] = data[17];
result.PCBNumber[2] = data[18];
result.PCBNumber[3] = data[19];
result.PCBNumber[4] = data[20];
result.TestModeConfig = data[21];
result.RadioAddress = (((UInt32)data[25] * 256 + data[24]) * 256 + data[23]) * 256 + data[22];
result.TempCalibration = (UInt16)(data[27] * 256 + data[26]);
result.AlarmMask = (UInt16)(data[29] * 256 + data[28]);
result.ConfigCheckSum = (UInt16)(data[31] * 256 + data[30]);
return result;
}
/// <summary>
/// Update the configuration structure from an incomplete byte array
/// </summary>
/// <param name="offset">Offset of byte array data in ConfigStruct</param>
/// <param name="data">Byte array data</param>
/// <returns>true when successful, false when data are not appropriate</returns>
public bool Update(int offset, byte[] data)
{
if (offset == 0 && data.Length == 2)
{
/// iPerl mode of function
Version = data[0];
MeterState = (MeterState)data[1];
return true;
}
else if (offset == 0 && data.Length == 4)
{
/// iPerl mode of function and extra 2 bytes
Version = data[0];
MeterState = (MeterState)data[1];
return true;
}
else if (offset == 21 && data.Length == 1)
{
/// TestModeConfig value
TestModeConfig = data[21 - offset];
return true;
}
else if (offset == 0 && data.Length == Length)
{
/// Complete ConfigStruct
Version = data[0];
MeterState = (MeterState)data[1];
TargetTimeVeryLowBatt = (((UInt32)data[5] * 256 + data[4]) * 256 + data[3]) * 256 + data[2];
TargetTimeLowBatt = (((UInt32)data[9] * 256 + data[8]) * 256 + data[7]) * 256 + data[6];
TestModeTime = (((UInt32)data[13] * 256 + data[12]) * 256 + data[11]) * 256 + data[10];
EmptyPipeThreshold = (UInt16)(data[15] * 256 + data[14]);
PCBNumber[0] = data[16];
PCBNumber[1] = data[17];
PCBNumber[2] = data[18];
PCBNumber[3] = data[19];
PCBNumber[4] = data[20];
TestModeConfig = data[21];
RadioAddress = (((UInt32)data[25] * 256 + data[24]) * 256 + data[23]) * 256 + data[22];
TempCalibration = (UInt16)(data[27] * 256 + data[26]);
AlarmMask = (UInt16)(data[29] * 256 + data[28]);
ConfigCheckSum = (UInt16)(data[31] * 256 + data[30]);
return true;
}
else
return false;
}
/// <summary>
/// Converts PCBNumber to string
/// </summary>
/// <param name="pcbNumber"></param>
/// <returns>PCB number string</returns>
public static string PCBNumber2String(byte[] pcbNumber)
{
if (pcbNumber.Length != 5) return string.Empty;
Int64 number = 0;
for (int i = 4; i >= 0; i--)
{
number = 256 * number + (Int64)pcbNumber[i];
}
return number.ToString();
}
/// <summary>
/// Converts PCBNumber to string
/// </summary>
/// <returns>PCB number string</returns>
public string PCBNumber2String()
{
return ConfigStruct.PCBNumber2String(PCBNumber);
}
public override string ToString()
{
return string.Format("Config: V{0} State={1} VLoBattT={2}s LoBattT={3}s TestModeT={4}s EPThld={5} PCB#={6} TMCfg={7} RadioAddr={8} TempCalib={9} AlarmMask={10} CfgCheckSum={11}",
Version,
MeterState,
TargetTimeVeryLowBatt,
TargetTimeLowBatt,
TestModeTime,
EmptyPipeThreshold,
PCBNumber2String(),
TestModeConfig.ToString("X2"),
RadioAddress,
TempCalibration,
AlarmMask.ToString("X4"),
ConfigCheckSum.ToString("X4"));
}
public string ToString(int sel)
{
return string.Format("{1} PCB#={6} TMCfg={7}",
Version,
MeterState,
TargetTimeVeryLowBatt,
TargetTimeLowBatt,
TestModeTime,
EmptyPipeThreshold,
PCBNumber2String(),
TestModeConfig.ToString("X2"),
RadioAddress,
TempCalibration,
AlarmMask.ToString("X4"),
ConfigCheckSum.ToString("X4"));
}
}
}
@@ -0,0 +1,110 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public enum MessageID
{
Calibration = 0x00, /// Access to stCalibration
Configuration = 0x01, /// Access to stConfig
Status = 0x02, /// Access to stStaus, read only
Power = 0x03, /// Access to stPower, containing power info from both processors
LCD = 0x04, /// Access to stLCD
EventData = 0x05, /// NOT USED
IntervalData = 0x06, /// NOT USED
Diagnostics = 0x07, /// Access tostMetroDiagArray, read onl
MetrologyMemory = 0x08, /// Memory block access, read only
Error_LongAck = 0x09, /// Error message
Command = 0x0A, /// Command to execute, with no arguments
Parameterizing = 0x0B, /// Parameterizing message is used in MCI-SPI interface only
Error_ShortAck = 0x0C, /// Short acknowledge message is used in MCI-SPI interface only
ChanelAlive = 0x0D, /// Channel alive message is used in MCI-SPI interface only
RadioPassthrough = 0x0E, /// RFID <-> Metrology <-> Radio passthrough message
ASICRegisterReadTest = 0x0F, /// ASIC Register read test
IMIDebugMessagesAccess = 0x10, /// IMI debug messages read test
ProductionChecksumsRead = 0x11, /// Production checksum read: Calibration (1 byte), Configuration (2 bytes), spare (4 bytes)
HardwareParametersTest = 0x12, /// Hardware Parameters Testing: User configurable fixed field drive time (1 byte)
/// <summary>
/// Notes:
/// 1. Short Ack message contains 1-byte error code and all the fields (Offset, Payload length, payload and password) will not be present.
/// 2. Channel Alive message does not contain the fields (Offset, Payload length, payload and password).
/// 3. Except the above two special messages, rest all the messages in the above table will follow the message format mentioned in sections 3.1 and 3.2.
/// </summary>
Count /// Number of MessageID-s
}
public enum MeterType : byte
{
DN15 = 0,
CoaxManifold = 1,
DN20 = 2,
DN25 = 3,
DN26 = 4, /// DN25*
DN32 = 5,
DN40 = 6,
AutoDetect,
Count /// Number of meter types
}
public enum VolumeUnits : byte
{
m3 = 0,
UK_gallon = 1,
US_gallon = 2,
Count /// Number of volume units
}
public enum FlowArrow : byte
{
No = 0,
Right = 1,
Left = 2,
Count /// Number of flow arrows
}
public enum MeterSealed : byte
{
InProduction = 0x00,
OutOfProduction = 0xA5,
Sealed = 0x5A,
}
public enum MeterState : byte
{
None = 0,
Idle = 1,
Active = 2,
Test = 3,
EndOfLife = 4,
Count /// Number of meter states
}
public enum FlowState : byte
{
No = 0,
Reverse = 1,
Forward = 2,
EmptyPipe = 3,
Count /// Number of flow states
}
public enum OptoTelegramFlags : byte
{
OK = 0,
OK_TestStart,
OK_TestEnd,
InvalidTelegram, /// Wrong telegram format of checksum error
SyncError,
}
public enum OptoState
{
Read,
Flush,
}
}
@@ -0,0 +1,26 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System.Collections.Generic;
using TBF.BenchControl.Generic;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public class Factory : IComponentFactory
{
public string ClassName { get { return "RegisterReader for iPerl/iPerl Head"; } }
public void ResetStaticProperties() { IperlHead.ResetStaticProperties(); }
public IComponent DummyComponent() { return new IperlHead(); }
public IComponent GetComponent(IComponentCfg cfg, IList<IComponent> components) { return new IperlHead(cfg); }
public IComponentCfg DefaultConfig() { return new IperlHeadCfg(this); }
public IComponentCfg CmpntCfgFromCmpntEntity(Config.Entities.Component component)
{
return ComponentCfgBase.CreateFromDbEntity(typeof(IperlHeadCfg), component, this);
}
}
}
@@ -0,0 +1,845 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
using log4net;
using Config.Entities;
using TBF.BenchControl;
using TBF.BenchControl.Generic;
using TBF.Resources;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
/// <summary>
/// This component = instance of this class is a placeholder for a combined main watermeter
/// </summary>
public class IperlHead : ComponentBase, IDevice, GenericDevices.IRegisterReader, IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(IperlHead));
public override string ToString() { return string.Format("iPerl({0})", Cfg.ToString(1)); }
readonly IperlHeadCfg iperlHeadCfg;
public int RfidComPortNr { get { return iperlHeadCfg.RfidComPortNr; } }
public int MuxBoardNr { get { return iperlHeadCfg.MuxBoardNr; } }
public int Group { get { return iperlHeadCfg.Group; } }
public double PulsesPerLtr { get { return 1000.0; } }
public double LtrsPerPulse { get { return 1 / PulsesPerLtr; } }
#if ORACLE_DB
public int WMType_ID { get { return iperlHeadCfg.ProcParams.WMType_ID; } } /// Required by Oracle DB
public int WMType_Rev { get { return iperlHeadCfg.ProcParams.WMType_Rev; } } /// Required by Oracle DB
#endif
public ushort FactorLimitLo { get { return (ushort)iperlHeadCfg.ProcParams.FactorLimitLo; } }
public ushort FactorLimitHi { get { return (ushort)iperlHeadCfg.ProcParams.FactorLimitHi; } }
/// Properties set by the Begin and the End form
public string SerialNr
{
get
{
if (ConfigStruct != null) return configStruct.PCBNumber2String();
else return string.Empty;
}
set { }
}
public string EndState
{
get { return endState; }
set { endState = value; }
}
string endState;
public string BeginState
{
get { return beginState; }
set { beginState = value; }
}
string beginState;
public bool Disabled
{
get { return disabled; }
set { disabled = value; }
}
bool disabled;
public bool CommFailed
{
get { return commFailed; }
set { commFailed = value; }
}
bool commFailed;
/// <summary>
/// Passed to OptoTelegramRaw.UpdateFromString(...)
/// </summary>
Int64 volumeRawExtLast;
Int64 timestampExtLast;
public bool PositiveCounting;
/// <summary> ConfigStruct of the water meter obtained or updated by iPerlCommunication </summary>
public ConfigStruct ConfigStruct
{
get { return configStruct; }
set { configStruct = value; }
}
ConfigStruct configStruct;
/// <summary> CalibrationStruct of the water meter obtained or updated by iPerlCommunication </summary>
public CalibrationStruct CalibrationStruct
{
get { return calibrationStruct; }
set { calibrationStruct = value; }
}
CalibrationStruct calibrationStruct;
public ushort OriginalCalibFactor;
public ushort CalibrationFactor { get { return (CalibrationStruct != null) ? CalibrationStruct.Calibration : (ushort)0; } }
public double Q2ErrorWOCorrection;
public bool Q2CorrectionDone;
public double Q2Correction;
public int Q2CorrRFlow;
public int Q2CorrLFlow;
public double Diff2Hz8Hz;
public bool Hz2CorrectionDone;
public int Hz2CorrectionFactor;
/// <summary> Result of the last test used to calculate Q2 correction factors, etc </summary>
public Results.Entities.MeterTestRslt LastTestResult2;
public Results.Entities.MeterTestRslt LastTestResult;
public double NominalTestFlowLph; /// in liter per hour
///
/// Required for IRegisterReader interface
///
public int WMPulses { get { return wmPulses; } }
public int WMRefPulses { get { return wmRefPulses; } }
public double WMVolume { get { return wmVolume; } }
public double BeginWMState { get { return beginWMState; } }
public double EndWMState { get { return endWMState; } }
public double WMTestTime { get { return wmTestTime; } }
double beginWMState;
double endWMState;
double wmVolume;
int wmPulses;
int wmRefPulses;
double wmTestTime;
/// <summary>
/// New calibration factor calculated from the original factor (argument)
/// and results of the last test.
/// </summary>
/// <param name="originalCalibrationFactor">Original calibration factor</param>
/// <returns>New calibration factor or 0 (= Out of range)</returns>
public UInt16 CalculateNewCalibFactor(UInt16 originalCalibrationFactor, UInt16 FactorLimitLo, UInt16 FactorLimitHi)
{
OriginalCalibFactor = originalCalibrationFactor;
double volumeMeter = Math.Abs(VolumeLtrEnd - VolumeLtrStart);
if (volumeMeter > 1E-2)
{
PositiveCounting = VolumeLtrEnd > VolumeLtrStart;
UInt16 newFactor = (UInt16)((double)originalCalibrationFactor * VolumeLtrRef / volumeMeter + 0.5);
log.InfoFormat("Calibration factor: orig={0} new={1} V_1={2} V_2={3} Vdiff={4} Vref={5}",
originalCalibrationFactor, newFactor,
VolumeLtrStart.ToString("F3"), VolumeLtrEnd.ToString("F3"), volumeMeter.ToString("F3"),
VolumeLtrRef.ToString("F3"));
if (newFactor < FactorLimitLo || newFactor > FactorLimitHi) return 0;
return newFactor;
}
else
{
log.ErrorFormat("Calibration factor: orig={0} new={0} (unchanged!) Vdiff={1}",
originalCalibrationFactor, volumeMeter.ToString("F3"));
return originalCalibrationFactor; /// Too small volume in the denominator -> no correction at all
}
}
/// <summary>
/// Q2 correction factor calculated from the last test (Q2).
/// This factors should be used only for R800 meters.
/// </summary>
/// <param name="q2TestResult">Test result from which to calculate the factor</param>
/// <param name="q2CorrectionFactor">The calculated Q2 correction factor</param>
/// <returns>true = OK, false = failed</returns>
public bool CalculateQ2CorrectionFactor(Results.Entities.MeterTestRslt q2TestResult, out double q2CorrectionFactor)
{
q2CorrectionFactor = 0;
if (q2TestResult == null) return false; /// Q2 test result is missing ==> water meter failed
double errLimitLo = q2TestResult.ErrLimLo() + q2TestResult.Uncertainty();
double errLimitHi = q2TestResult.ErrLimHi() - q2TestResult.Uncertainty();
if ((q2TestResult.Error < errLimitLo) || (q2TestResult.Error > errLimitHi))
{
return false; /// Q2 error too large ==> water meter failed
}
double A = 16.0 / ScalingFactor(); /// Raw units per ml: DN15=16, DN20=8, DN25=4, DN32=2, DN40=1
const double B = 8.0; /// Raw units per minute, 8
const double C = B * 60.0; /// Raw units per hour, 480
double D = C / A; /// ml correction per hour
double F = D / (NominalTestFlowLph * 10.0); /// Error corrected with 8 Raw Units per minute [%]
double G = F / B; /// Error corrected with 1 Raw Unit per minute [%]
q2CorrectionFactor = (-1) * (q2TestResult.Error / G) * (q2TestResult.VolumeRef / q2TestResult.VolumeMeter);
log.WarnFormat("Q2 correction: Pos={0}, PCB#={1}, corrFactor={2}, error={3}% [Lo={4}%, Hi={5}%]",
Name,
SerialNr,
q2CorrectionFactor.ToString("F1"),
q2TestResult.Error.ToString("F2"),
errLimitLo.ToString("F1"),
errLimitHi.ToString("F1"));
return true;
}
/// <summary>
/// 2 Hz correction factor calculated from two Q3 tests - done at 2Hz and at 8Hz.
/// This factors should be used only for DN32 and DN40 meters.
/// </summary>
/// <param name="resultAt2Hz">Test result @2Hz from which to calculate the factor</param>
/// <param name="resultAt8Hz">Test result @8Hz from which to calculate the factor</param>
/// <param name="hz2CorrectionFactor">The calculated Q2 correction factor</param>
/// <returns>true = OK, false = failed</returns>
public bool Calculate2HzCorrectionFactor(Results.Entities.MeterTestRslt resultAt2Hz,
Results.Entities.MeterTestRslt resultAt8Hz,
out double diff2Hz8Hz, out int hz2CorrectionFactor)
{
hz2CorrectionFactor = 0;
diff2Hz8Hz = 0;
if ((resultAt2Hz == null) || (resultAt8Hz == null))
{
return false; /// Test result @2Hz and/or @8Hz is missing ==> water meter failed
}
diff2Hz8Hz = resultAt2Hz.Error - resultAt8Hz.Error;
if (Math.Abs(diff2Hz8Hz) > 2.5) return false; /// Difference of errors > 2.5 % ==> water meter failed
hz2CorrectionFactor = -1 * (int)Math.Round(10 * diff2Hz8Hz);
log.WarnFormat("2Hz correction: Pos={0}, PCB#={1}, corrFactor={2}, erro@2Hz={3}%, erro@8Hz={4}%",
Name,
SerialNr,
hz2CorrectionFactor,
resultAt2Hz.Error.ToString("F2"),
resultAt8Hz.Error.ToString("F2"));
return true;
}
/// <summary> Name set by the test, to be used as a part of the opto-data log file name </summary>
public string TestName;
/// <summary> Name set by the test, to be used as a part of the opto-data log file name </summary>
public string BenchName;
///
/// Volume of water from the opto telegram
///
private Int64 lastVolumeRaw; /// Last read raw volume
private double volumeLtr; ///
private double volumeLtr0;
public double VolumeLtrStart; /// Test start volume for metrology
public double VolumeLtrEnd; /// Test end volume for metrology
public double VolumeLtrRef; /// Reference volume or metrology
double volumeLtrEnd1; /// auxiliary buffer1 to keep the end volume before test stops
double volumeLtrEnd2; /// auxiliary buffer2 to keep the end volume before test stops
double volumeLtrEnd3; /// auxiliary buffer3 to keep the end volume before test stops
///
/// Timestamp from the opto telegram
///
bool lastTimestampValid;
private Int64 lastTimestamp;
private double timestampSec;
private double timestampSec0;
public bool NoSamples { get { return (timestampSecEnd - timestampSecStart) < float.Epsilon; } }
public double TimestampSecStart { get { return timestampSecStart; } }
public double TimestampSecEnd { get { return timestampSecEnd; } }
double timestampSecStart;
double timestampSecEnd;
double timestampSecEnd1;
double timestampSecEnd2;
double timestampSecEnd3;
private int telegramIx;
public int TestStartTelegramIx;
public int TestEndTelegramIx;
OptoTelegramRaw[] optoData;
const int MaxOptoDataCount = 40000;
int optoDataCount;
string optoDataLogFileName;
OptoTelegramRaw toBeFlushed;
int flushedDataCount;
public int FlushedDataCount
{
get { return flushedDataCount; }
set { flushedDataCount = lastFlushedDataCount = lastFlushedDataCount_1 = value; }
}
int lastFlushedDataCount_1;
int lastFlushedDataCount;
public int FlushedDataDelta
{
get
{
int retval = Math.Max(flushedDataCount - lastFlushedDataCount, lastFlushedDataCount - lastFlushedDataCount_1);
lastFlushedDataCount_1 = lastFlushedDataCount;
lastFlushedDataCount = flushedDataCount;
return retval;
}
}
///
/// Opto serial port and worker thread related private variables
///
private SerialPort optoSerialPort;
public IperlHead()
{
ClearData();
}
public IperlHead(Generic.IComponentCfg cfg)
: base(cfg)
{
ClearData();
iperlHeadCfg = cfg as IperlHeadCfg;
log.Debug(this.ToString());
}
/// <summary>
/// Clear data related to a specific water meter
/// </summary>
public void ClearData()
{
disabled = false;
commFailed = false;
endState = string.Empty;
beginState = string.Empty;
configStruct = null;
calibrationStruct = null;
LastTestResult = null;
NominalTestFlowLph = 0;
OriginalCalibFactor = 0;
Q2ErrorWOCorrection = 0;
Q2CorrectionDone = false;
Q2CorrRFlow = 0;
optoDataCount = 0;
}
public void Initialize()
{
ClearData();
if (DebugLevel == DebugMode.Normal)
{
optoSerialPortParsingEnabled = false;
/// Allocate memory for opto-data from iPerl
optoData = new OptoTelegramRaw[MaxOptoDataCount];
for (int i = 0; i < MaxOptoDataCount; i++) optoData[i] = new OptoTelegramRaw();
toBeFlushed = new OptoTelegramRaw();
flushedDataCount = 0;
synchronized = false;
synchronized2 = false;
partOfTelegram = string.Empty;
/// Prepare serial port
optoSerialPort = new SerialPort(string.Format("COM{0}", iperlHeadCfg.OptoComPortNr),
9600, Parity.None, 8, StopBits.One);
optoSerialPort.Handshake = Handshake.None;
optoSerialPort.Open();
}
}
public void RunDeviceBefore()
{
if (DebugLevel == DebugMode.Normal)
{
try
{
if (optoSerialPortParsingEnabled)
ReadOptoData(OptoState.Read);
else
ReadOptoData(OptoState.Flush);
}
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 (DebugLevel == DebugMode.Normal && optoSerialPort != null)
{
optoSerialPort.Close();
optoSerialPort = null;
}
}
catch
{
}
}
/// <summary>
/// Events: Event.ReadRegisterDone, Event.Error
/// </summary>
/// <returns>ReadWaterMeter instance reference casted to IOperaton</returns>
public IOperation ReadRegisterOp()
{
return this;
}
/// <summary>
/// Clear data/counters related to a specific tests
/// </summary>
public void Clear()
{
sampleNr = 0;
volumeLtr = 0;
volumeLtr0 = 0;
timestampSec = 0;
timestampSec0 = 0;
ReadPulses();
}
public void TestCompleted()
{
/// TODO: Implement
}
int sampleNr; /// This is to determine when the test start sample should be taken
/// <summary>Start this operation</summary>
public void Start()
{
Clear();
/// Reset opto data
optoDataCount = 0;
TestStartTelegramIx = 0;
TestEndTelegramIx = 0;
/// File name is: PCB_AA_BB_HH_MI_SS..txt
string wmPosition = Name.Substring(5);
if (wmPosition.Length == 1) wmPosition = "0" + wmPosition;
string flowNr;
if (TestName != null && TestName.ToLower().Contains("q1")) flowNr = "01";
else if (TestName != null && TestName.ToLower().Contains("q2")) flowNr = "02";
else if (TestName != null && TestName.ToLower().Contains("q3")) flowNr = "03";
else if (TestName != null && TestName.ToLower().Contains("adj")) flowNr = "0-1";
else flowNr = "99";
optoDataLogFileName = string.Format("{0}_{1}_{2}_{3}.txt",
(ConfigStruct != null) ? ConfigStruct.PCBNumber2String() : "UnknownPcbNr",
wmPosition,
flowNr,
StateMachine.CycleStartTimeStamp.ToString("HH_mm_ss"));
StartParsingOptoSerialPort();
}
/// <summary>Run this operation</summary>
/// <returns>eventDone</returns>
public Event Run()
{
sampleNr++;
ReadPulses();
if (sampleNr == 4)
{
/// Take the test start sample
VolumeLtrStart = volumeLtr;
timestampSecStart = timestampSec;
TestStartTelegramIx = telegramIx;
}
/// Shift data in pipelines
VolumeLtrEnd = volumeLtrEnd3;
volumeLtrEnd3 = volumeLtrEnd2;
volumeLtrEnd2 = volumeLtrEnd1;
volumeLtrEnd1 = volumeLtr;
timestampSecEnd = timestampSecEnd3;
timestampSecEnd3 = timestampSecEnd2;
timestampSecEnd2 = timestampSecEnd1;
timestampSecEnd1 = timestampSec;
TestEndTelegramIx = telegramIx - 3;
return Event.ReadRegisterDone;
}
/// <summary>Stop this operation</summary>
public void Stop()
{
if (TestStartTelegramIx > 0 && TestStartTelegramIx < optoData.Length && optoData[TestStartTelegramIx].Flags == OptoTelegramFlags.OK)
{
optoData[TestStartTelegramIx].Flags = OptoTelegramFlags.OK_TestStart;
OptoTelegramRaw.TestStartTimestampDec = optoData[TestStartTelegramIx].TimestampDec();
}
if (TestEndTelegramIx > 0 && TestEndTelegramIx < optoData.Length && optoData[TestEndTelegramIx].Flags == OptoTelegramFlags.OK)
{
optoData[TestEndTelegramIx].Flags = OptoTelegramFlags.OK_TestEnd;
}
StopParsingOptoSerialPort();
OptoTelegramRaw.FIRFilterFlow(optoData, optoDataCount);
SaveOptoData();
}
void SaveOptoData()
{
string directory = string.Format("C:\\TBF\\ProcessData\\{0}\\{1}\\{2}\\",
StateMachine.CycleStartTimeStamp.ToString("yy"),
StateMachine.CycleStartTimeStamp.ToString("MM"),
StateMachine.CycleStartTimeStamp.ToString("dd"));
try
{
Directory.CreateDirectory(directory);
double scalFact = ScalingFactor();
using (TextWriter optoLogFile = new StreamWriter(directory + optoDataLogFileName))
{
optoLogFile.WriteLine(optoData[0].ToString(scalFact, null));
for (int i = 1; i < optoDataCount; i++) optoLogFile.WriteLine(optoData[i].ToString(scalFact, optoData[i - 1]));
optoLogFile.Close();
}
}
catch (Exception exc)
{
MessageBox.Show(Strings.Error_writing_into_file_ + Environment.NewLine +
string.Format("{0}\\{1}\r\n{2}", directory, optoDataLogFileName, exc.Message),
Strings.Error,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
void ReadPulses()
{
beginWMState = volumeLtr0;
endWMState = volumeLtr;
wmVolume = Math.Abs(endWMState - beginWMState);
wmPulses = (int)(wmVolume * (double)PulsesPerLtr + 0.5);
wmRefPulses = StateMachine.ControlBoard.EtPulses(0);
wmTestTime = timestampSec - timestampSec0;
}
bool optoSerialPortParsingEnabled;
/// <summary> Flush internal buffers and start parsing the opto serial port data </summary>
void StartParsingOptoSerialPort()
{
optoSerialPortParsingEnabled = true;
}
/// <summary> Stop parsig the opto serial port data </summary>
void StopParsingOptoSerialPort()
{
optoSerialPortParsingEnabled = false;
}
///
/// Variables storing the context of serial port data parsing (ReadOptoSerialPort(...))
///
bool synchronized;
bool synchronized2;
string partOfTelegram;
/// <summary>
/// 9600 Bd, 8 data bits, 1 stop bit, no parity
///
/// 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(OptoState optoState)
{
int nrBytes = optoSerialPort.BytesToRead;
if (nrBytes > 0)
{
char[] buffer = new char[nrBytes];
optoSerialPort.Read(buffer, 0, nrBytes);
string received = new string(buffer);
string allRcvd = partOfTelegram + received;
while (true)
{
int pos = allRcvd.IndexOf("\r\n");
if (pos < 0)
{
/// No CR+LF found, wait for more characters in the next invocation
partOfTelegram = allRcvd;
return;
}
else
{
// CR+LF found
if (optoState == OptoState.Read)
{
if (pos < OptoTelegramRaw.Length - 2)
{
/// CR+LF found too early, truncate the beginning incl CR+LF and keep scanning in this loop
allRcvd = allRcvd.Substring(pos + 2);
if (synchronized)
{
optoData[optoDataCount].Counter = optoDataCount;
optoData[optoDataCount++].SetFlags(OptoTelegramFlags.SyncError);
}
synchronized = true;
}
// CR+LF found and (pos >= OptoTelegramRaw.Length - 2)
else if (optoData[optoDataCount].UpdateFromString(allRcvd.Substring(pos - OptoTelegramRaw.Length + 2), optoDataCount, ref volumeRawExtLast, ref timestampExtLast))
{
OptoTelegramRreceived(optoDataCount++, synchronized2);
synchronized2 = synchronized;
allRcvd = allRcvd.Substring(pos + 2);
}
else
{
optoData[optoDataCount].Counter = optoDataCount;
optoDataCount++;
allRcvd = allRcvd.Substring(pos + 2);
}
}
else /// optoState == OptoState.Flush
{
if (pos < OptoTelegramRaw.Length - 2)
{
/// CR+LF found too early, truncate the beginning incl CR+LF and keep scanning in this loop
allRcvd = allRcvd.Substring(pos + 2);
synchronized = true;
}
// CR+LF found and (pos >= OptoTelegram.Length - 2)
else if (toBeFlushed.UpdateFromStringDummy(allRcvd.Substring(pos - OptoTelegramRaw.Length + 2)))
{
flushedDataCount++;
synchronized2 = synchronized;
allRcvd = allRcvd.Substring(pos + 2);
}
else
{
allRcvd = allRcvd.Substring(pos + 2);
}
}
}
}
//OnOptoReceived(this, new OptoReceivedEventArgs(s));
}
else
{
//OnOptoReceived(this, new OptoReceivedEventArgs("."));
}
}
void OptoTelegramRreceived(int currentIx, bool async)
{
OptoTelegramRaw optoTelegram = optoData[currentIx];
telegramIx = currentIx;
lastVolumeRaw = volumeRawExtLast;
lastTimestamp = timestampExtLast;
if (volumeLtr == 0 && volumeLtr0 == 0)
{
volumeLtr = (double)lastVolumeRaw * ScalingFactor() / 16000.0;
volumeLtr0 = volumeLtr;
}
else
{
volumeLtr = (double)lastVolumeRaw * ScalingFactor() / 16000.0;
}
if (timestampSec == 0 && timestampSec0 == 0)
{
timestampSec = (double)lastTimestamp / 8192.0;
timestampSec0 = timestampSec;
}
else
{
timestampSec = (double)lastTimestamp / 8192.0;
}
//optoDataLogger.InfoFormat("{0} {1} {2} ltr {3} {4}", optoTelegram, lastTimestamp, lastVolumeRaw.ToString("X8"), timestampSec.ToString("F1"), volumeLtr.ToString("F3"));
}
/// <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;
/// <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 (iperlHeadCfg.MeterType == MeterType.AutoDetect || CalibrationStruct == null)
{
return true;
}
return iperlHeadCfg.MeterType == CalibrationStruct.MeterType;
}
public static double UnitVolume(VolumeUnits units)
{
switch (units)
{
default:
case VolumeUnits.m3: return Config.Units.ConvertFrom(Config.Unit.m3, 1.0); /// liter
case VolumeUnits.UK_gallon: return Config.Units.ConvertFrom(Config.Unit.gal_UK, 1.0); /// liter
case VolumeUnits.US_gallon: return Config.Units.ConvertFrom(Config.Unit.gal_US, 1.0); /// liter
}
}
public double ScalingFactor()
{
if ((iperlHeadCfg.MeterType == MeterType.AutoDetect) && (CalibrationStruct != null))
{
return IperlHead.ScalingFactor(CalibrationStruct.MeterType);
}
else if (iperlHeadCfg.MeterType != MeterType.AutoDetect)
{
return IperlHead.ScalingFactor(iperlHeadCfg.MeterType);
}
else
{
return IperlHead.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.DN26:
case MeterType.DN32: return 8.0;
case MeterType.DN40: return 16.0;
}
}
int PositionNrFormWMName(string name)
{
int len = name.Length;
if (len < 2) return 0;
int loNr = (int)name[len - 1] - (int)'0';
int hiNr = (int)name[len - 2] - (int)'0';
if (hiNr < 1 || hiNr > 4) hiNr = 0;
return 10 * hiNr + loNr;
}
}
}
@@ -0,0 +1,73 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Xml.Serialization;
using Config.Entities;
using TBF.BenchControl.Generic;
using TBF.Resources;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public class IperlHeadCfg : ComponentCfgBase, Generic.IComponentCfg
{
public IComponentCfgCtrl GetControl() { return new IperlHeadCfgCtrl(); }
///
/// Serialized parameters
///
public bool UseTcpIP;
public string OptoIPAddress;
public ushort OptoTcpipPortNr;
public int OptoComPortNr;
public int RfidComPortNr; /// 0 = use MuxBoardNr
public int MuxBoardNr; /// 0 = use RfidComPort(Nr), otherwise mux. board nr. 1 .. 4
public int Group; /// Number written to QuidoRS to connct the watermeter to RfidComPort
/// <summary> Procedure parameters </summary>
[XmlIgnore]
public ProcParams ProcParams;
public override IParamsProvider GetProcedureParams() { return ProcParams; }
public override IParamsProvider CreateProcedureParams(Procedure procedure)
{
ProcParams procParams = new ProcParams(true);
procParams.UpdateProcedureParams(Name, procedure);
return procParams;
}
[XmlIgnore]
public MeterType MeterType { get { return (ProcParams != null) ? ProcParams.MeterType : MeterType.AutoDetect; } }
/// Private parameterless constructor invoked by all other (public) constructors
IperlHeadCfg()
{
Name = "iPerl";
ParentName = string.Empty;
OptoComPortNr = 10;
RfidComPortNr = 0; /// = use mux. board
MuxBoardNr = 1;
ProcParams = new ProcParams(true);
}
public IperlHeadCfg(IComponentFactory factory)
: this()
{
this.Factory = factory;
}
public string ToString(int i)
{
return string.Format("Name={0}, Opto=COM{1}, RFID=COM{2}, MuxBoard#={3}, Group={4}",
Name,
OptoComPortNr,
RfidComPortNr,
MuxBoardNr,
Group);
}
}
}
@@ -0,0 +1,161 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using log4net;
using TBF.BenchControl.Generic;
using TBF.Resources;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public partial class IperlHeadCfgCtrl : UserControl, IComponentCfgCtrl
{
static readonly ILog log = LogManager.GetLogger(typeof(IperlHeadCfgCtrl));
public bool ShowMore { get { return false; } }
IperlHeadCfg config;
public IComponentCfg Config
{
get { return config as IComponentCfg; }
set
{
config = value as IperlHeadCfg;
Redraw();
}
}
public IperlHeadCfgCtrl()
{
InitializeComponent();
}
private void WaterMeterCfgCtrl_Load(object sender, EventArgs e)
{
nameLabel.Text = Strings.Name;
classNameLabel.Text = config.Factory.ClassName;
Redraw();
}
public void Closing()
{
}
void Redraw()
{
if (config == null) return; /// Control was not loaded, settings were not changed
nameTextBox.Text = config.Name;
radioButton1.Checked = config.UseTcpIP;
radioButton2.Checked = !config.UseTcpIP;
ipAddressTextBox.Text = (config.OptoIPAddress != null) ? config.OptoIPAddress : "0.0.0.0";
tcpipPortTextBox.Text = config.OptoTcpipPortNr.ToString();
optoSerialPortTextBox.Text = config.OptoComPortNr.ToString();
rfidPortNrTextBox.Text = config.RfidComPortNr.ToString();
muxBoardNrTextBox.Text = config.MuxBoardNr.ToString();
groupTextBox.Text = config.Group.ToString();
}
public void Unlock()
{
nameTextBox.Enabled = true;
radioButton1.Enabled = true;
radioButton2.Enabled = true;
ipAddressTextBox.Enabled = true;
tcpipPortTextBox.Enabled = true;
optoSerialPortTextBox.Enabled = true;
rfidPortNrTextBox.Enabled = true;
muxBoardNrTextBox.Enabled = true;
groupTextBox.Enabled = true;
}
public CfgUpdateFlags VerifyCfg(ref string message)
{
CfgUpdateFlags flags = CfgUpdateFlags.None;
int dummy, dummy2;
if (radioButton1.Checked)
{
IPAddress dummyIPAddress;
if (!IPAddress.TryParse(ipAddressTextBox.Text, out dummyIPAddress))
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'IP address' is not valid";
}
ushort sdummy;
if (!ushort.TryParse(tcpipPortTextBox.Text, out sdummy))
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'TCP/IP port nr.' is not valid";
}
}
else
{
if (!int.TryParse(optoSerialPortTextBox.Text, out dummy) || dummy < 1 || dummy > 999)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'Opto serial port nr.' is not valid";
}
}
if (!int.TryParse(rfidPortNrTextBox.Text, out dummy) || dummy < 0 || dummy > 999)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'RFID serial port nr.' is not valid";
}
if (!int.TryParse(muxBoardNrTextBox.Text, out dummy2) || dummy2 < 0 || dummy2 > 4)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'Mux. board nr.' is not valid";
}
if (dummy == 0 && dummy2 == 0)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Either 'RFID serial port nr.' or 'Mux. board nr.' should be nonzero";
}
if (dummy != 0 && dummy2 != 0)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Either 'RFID serial port nr.' or 'Mux. board nr.' should be zero";
}
if (!int.TryParse(groupTextBox.Text, out dummy) || dummy < 1 || dummy > 10)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'Group' is not valid";
}
return flags;
}
public CfgUpdateFlags UpdateCfg()
{
CfgUpdateFlags flags = CfgUpdateFlags.RestartRqrd;
if (config == null) return CfgUpdateFlags.Error; /// Control was not loaded, settings were not changed
config.Name = nameTextBox.Text;
if (radioButton1.Checked)
{
config.UseTcpIP = true;
config.OptoIPAddress = ipAddressTextBox.Text;
config.OptoTcpipPortNr = ushort.Parse(tcpipPortTextBox.Text);
}
else
{
config.UseTcpIP = false;
config.OptoComPortNr = int.Parse(optoSerialPortTextBox.Text);
}
config.RfidComPortNr = int.Parse(rfidPortNrTextBox.Text);
config.MuxBoardNr = int.Parse(muxBoardNrTextBox.Text);
config.Group = int.Parse(groupTextBox.Text);
return flags;
}
}
}
@@ -0,0 +1,269 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
partial class IperlHeadCfgCtrl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.nameTextBox = new System.Windows.Forms.TextBox();
this.nameLabel = new System.Windows.Forms.Label();
this.classNameLabel = new System.Windows.Forms.Label();
this.optoSerialPortTextBox = new System.Windows.Forms.TextBox();
this.optoSerialPortLabel = new System.Windows.Forms.Label();
this.muxBoardNrTextBox = new System.Windows.Forms.TextBox();
this.muxBoardNrLabel = new System.Windows.Forms.Label();
this.groupTextBox = new System.Windows.Forms.TextBox();
this.groupLabel = new System.Windows.Forms.Label();
this.rfidPortNrTextBox = new System.Windows.Forms.TextBox();
this.rfidSerialPortNrLabel = new System.Windows.Forms.Label();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.optoDataGroupBox = new System.Windows.Forms.GroupBox();
this.tcpipPortLabel = new System.Windows.Forms.Label();
this.tcpipPortTextBox = new System.Windows.Forms.TextBox();
this.ipAddressLabel = new System.Windows.Forms.Label();
this.ipAddressTextBox = new System.Windows.Forms.TextBox();
this.optoDataGroupBox.SuspendLayout();
this.SuspendLayout();
//
// nameTextBox
//
this.nameTextBox.Enabled = false;
this.nameTextBox.Location = new System.Drawing.Point(135, 39);
this.nameTextBox.Name = "nameTextBox";
this.nameTextBox.Size = new System.Drawing.Size(121, 20);
this.nameTextBox.TabIndex = 2;
//
// nameLabel
//
this.nameLabel.AutoSize = true;
this.nameLabel.Location = new System.Drawing.Point(25, 42);
this.nameLabel.Name = "nameLabel";
this.nameLabel.Size = new System.Drawing.Size(35, 13);
this.nameLabel.TabIndex = 1;
this.nameLabel.Text = "Name";
//
// classNameLabel
//
this.classNameLabel.AutoSize = true;
this.classNameLabel.Location = new System.Drawing.Point(132, 18);
this.classNameLabel.Name = "classNameLabel";
this.classNameLabel.Size = new System.Drawing.Size(60, 13);
this.classNameLabel.TabIndex = 0;
this.classNameLabel.Text = "ClassName";
//
// optoSerialPortTextBox
//
this.optoSerialPortTextBox.Enabled = false;
this.optoSerialPortTextBox.Location = new System.Drawing.Point(329, 42);
this.optoSerialPortTextBox.Name = "optoSerialPortTextBox";
this.optoSerialPortTextBox.Size = new System.Drawing.Size(34, 20);
this.optoSerialPortTextBox.TabIndex = 7;
//
// optoSerialPortLabel
//
this.optoSerialPortLabel.AutoSize = true;
this.optoSerialPortLabel.Location = new System.Drawing.Point(241, 45);
this.optoSerialPortLabel.Name = "optoSerialPortLabel";
this.optoSerialPortLabel.Size = new System.Drawing.Size(72, 13);
this.optoSerialPortLabel.TabIndex = 6;
this.optoSerialPortLabel.Text = "Serial port nr.:";
//
// muxBoardNrTextBox
//
this.muxBoardNrTextBox.Enabled = false;
this.muxBoardNrTextBox.Location = new System.Drawing.Point(135, 207);
this.muxBoardNrTextBox.Name = "muxBoardNrTextBox";
this.muxBoardNrTextBox.Size = new System.Drawing.Size(34, 20);
this.muxBoardNrTextBox.TabIndex = 9;
//
// muxBoardNrLabel
//
this.muxBoardNrLabel.AutoSize = true;
this.muxBoardNrLabel.Location = new System.Drawing.Point(25, 210);
this.muxBoardNrLabel.Name = "muxBoardNrLabel";
this.muxBoardNrLabel.Size = new System.Drawing.Size(78, 13);
this.muxBoardNrLabel.TabIndex = 8;
this.muxBoardNrLabel.Text = "Mux. board nr.:";
//
// groupTextBox
//
this.groupTextBox.Enabled = false;
this.groupTextBox.Location = new System.Drawing.Point(135, 230);
this.groupTextBox.Name = "groupTextBox";
this.groupTextBox.Size = new System.Drawing.Size(34, 20);
this.groupTextBox.TabIndex = 11;
//
// groupLabel
//
this.groupLabel.AutoSize = true;
this.groupLabel.Location = new System.Drawing.Point(25, 233);
this.groupLabel.Name = "groupLabel";
this.groupLabel.Size = new System.Drawing.Size(39, 13);
this.groupLabel.TabIndex = 10;
this.groupLabel.Text = "Group:";
//
// rfidPortNrTextBox
//
this.rfidPortNrTextBox.Enabled = false;
this.rfidPortNrTextBox.Location = new System.Drawing.Point(135, 184);
this.rfidPortNrTextBox.Name = "rfidPortNrTextBox";
this.rfidPortNrTextBox.Size = new System.Drawing.Size(34, 20);
this.rfidPortNrTextBox.TabIndex = 7;
//
// rfidSerialPortNrLabel
//
this.rfidSerialPortNrLabel.AutoSize = true;
this.rfidSerialPortNrLabel.Location = new System.Drawing.Point(25, 187);
this.rfidSerialPortNrLabel.Name = "rfidSerialPortNrLabel";
this.rfidSerialPortNrLabel.Size = new System.Drawing.Size(98, 13);
this.rfidSerialPortNrLabel.TabIndex = 6;
this.rfidSerialPortNrLabel.Text = "RFID serial port nr.:";
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Enabled = false;
this.radioButton1.Location = new System.Drawing.Point(22, 19);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(83, 17);
this.radioButton1.TabIndex = 0;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "Use TCP/IP";
this.radioButton1.UseVisualStyleBackColor = true;
//
// radioButton2
//
this.radioButton2.AutoSize = true;
this.radioButton2.Enabled = false;
this.radioButton2.Location = new System.Drawing.Point(234, 19);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(92, 17);
this.radioButton2.TabIndex = 1;
this.radioButton2.TabStop = true;
this.radioButton2.Text = "Use serial port";
this.radioButton2.UseVisualStyleBackColor = true;
//
// optoDataGroupBox
//
this.optoDataGroupBox.Controls.Add(this.tcpipPortLabel);
this.optoDataGroupBox.Controls.Add(this.tcpipPortTextBox);
this.optoDataGroupBox.Controls.Add(this.ipAddressLabel);
this.optoDataGroupBox.Controls.Add(this.ipAddressTextBox);
this.optoDataGroupBox.Controls.Add(this.radioButton1);
this.optoDataGroupBox.Controls.Add(this.radioButton2);
this.optoDataGroupBox.Controls.Add(this.optoSerialPortLabel);
this.optoDataGroupBox.Controls.Add(this.optoSerialPortTextBox);
this.optoDataGroupBox.Location = new System.Drawing.Point(28, 67);
this.optoDataGroupBox.Name = "optoDataGroupBox";
this.optoDataGroupBox.Size = new System.Drawing.Size(414, 101);
this.optoDataGroupBox.TabIndex = 5;
this.optoDataGroupBox.TabStop = false;
this.optoDataGroupBox.Text = "Opto-data";
//
// tcpipPortLabel
//
this.tcpipPortLabel.AutoSize = true;
this.tcpipPortLabel.Location = new System.Drawing.Point(31, 71);
this.tcpipPortLabel.Name = "tcpipPortLabel";
this.tcpipPortLabel.Size = new System.Drawing.Size(47, 13);
this.tcpipPortLabel.TabIndex = 4;
this.tcpipPortLabel.Text = "Port nr..:";
//
// tcpipPortTextBox
//
this.tcpipPortTextBox.Enabled = false;
this.tcpipPortTextBox.Location = new System.Drawing.Point(107, 68);
this.tcpipPortTextBox.Name = "tcpipPortTextBox";
this.tcpipPortTextBox.Size = new System.Drawing.Size(39, 20);
this.tcpipPortTextBox.TabIndex = 5;
//
// ipAddressLabel
//
this.ipAddressLabel.AutoSize = true;
this.ipAddressLabel.Location = new System.Drawing.Point(31, 48);
this.ipAddressLabel.Name = "ipAddressLabel";
this.ipAddressLabel.Size = new System.Drawing.Size(63, 13);
this.ipAddressLabel.TabIndex = 2;
this.ipAddressLabel.Text = "IP address.:";
//
// ipAddressTextBox
//
this.ipAddressTextBox.Enabled = false;
this.ipAddressTextBox.Location = new System.Drawing.Point(107, 45);
this.ipAddressTextBox.Name = "ipAddressTextBox";
this.ipAddressTextBox.Size = new System.Drawing.Size(98, 20);
this.ipAddressTextBox.TabIndex = 3;
//
// WaterMeterCfgCtrl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.optoDataGroupBox);
this.Controls.Add(this.rfidPortNrTextBox);
this.Controls.Add(this.rfidSerialPortNrLabel);
this.Controls.Add(this.groupTextBox);
this.Controls.Add(this.groupLabel);
this.Controls.Add(this.muxBoardNrTextBox);
this.Controls.Add(this.muxBoardNrLabel);
this.Controls.Add(this.nameTextBox);
this.Controls.Add(this.nameLabel);
this.Controls.Add(this.classNameLabel);
this.Name = "WaterMeterCfgCtrl";
this.Size = new System.Drawing.Size(500, 300);
this.Load += new System.EventHandler(this.WaterMeterCfgCtrl_Load);
this.optoDataGroupBox.ResumeLayout(false);
this.optoDataGroupBox.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox nameTextBox;
private System.Windows.Forms.Label nameLabel;
private System.Windows.Forms.Label classNameLabel;
private System.Windows.Forms.TextBox optoSerialPortTextBox;
private System.Windows.Forms.Label optoSerialPortLabel;
private System.Windows.Forms.TextBox muxBoardNrTextBox;
private System.Windows.Forms.Label muxBoardNrLabel;
private System.Windows.Forms.TextBox groupTextBox;
private System.Windows.Forms.Label groupLabel;
private System.Windows.Forms.TextBox rfidPortNrTextBox;
private System.Windows.Forms.Label rfidSerialPortNrLabel;
private System.Windows.Forms.RadioButton radioButton1;
private System.Windows.Forms.RadioButton radioButton2;
private System.Windows.Forms.GroupBox optoDataGroupBox;
private System.Windows.Forms.Label tcpipPortLabel;
private System.Windows.Forms.TextBox tcpipPortTextBox;
private System.Windows.Forms.Label ipAddressLabel;
private System.Windows.Forms.TextBox ipAddressTextBox;
}
}
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,20 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public class OptoReceivedEventArgs : EventArgs
{
public string Data;
public OptoReceivedEventArgs(string data)
{
this.Data = data;
}
}
}
@@ -0,0 +1,296 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.Globalization;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public class OptoTelegramRaw
{
public static readonly int Length = 42;
private static CultureInfo culture;
///
/// Strobed value
///
public static decimal TestStartTimestampDec;
///
/// Stored values
///
public OptoTelegramFlags Flags;
public DateTime DateTime; /// From PC
public float RefFlow; /// [m3/h]
public int Counter;
public UInt32 EmfRaw; /// From iPerl opto data
public Int16 MagneticFieldRaw;
public Int16 FlowRaw;
public UInt32 VolumeRaw;
public Int64 VolumeRawExt;
public Int16 Impedance;
public UInt32 Timestamp;
public Int64 TimestampExt;
public byte CheckSum;
///
/// Calculated values
///
public double EMF()
{
Int32 signedEmf = (EmfRaw > 0x7FFFFF) ? ((int)EmfRaw - 0x1000000) : (int)EmfRaw;
return 0.000000333 * (double)signedEmf;
}
public double MagneticField() { return (double)MagneticFieldRaw; }
public double Flow(double scalingFactor) { return 0.225 * scalingFactor * (double)FlowRaw; }
public double Volume(double scalingFactor) { return 0.0000625 * scalingFactor * (double)VolumeRawExt; }
public Int32 FlipTime() { return Impedance; }
public decimal TimestampDec() { return (decimal)TimestampExt / (decimal)8192; }
public double VolumeDelta(double scalingFactor, OptoTelegramRaw previous) { return (previous == null) ? 0 : Volume(scalingFactor) - previous.Volume(scalingFactor); }
public decimal TimeDelta() { return TimestampDec() - TestStartTimestampDec; }
public string Label()
{
if (Flags == OptoTelegramFlags.OK_TestStart) return "#### start test ####";
else if (Flags == OptoTelegramFlags.OK_TestEnd) return "#### end of test ####";
else return string.Empty;
}
static OptoTelegramRaw()
{
culture = CultureInfo.CreateSpecificCulture("DE"); /// This is to use comma as decimal number separator
}
public OptoTelegramRaw()
{
}
/// <summary>
/// Parses optical telegram and returns OptoTelegramRaw object
/// </summary>
/// <description>
/// Create a configuration structure from a complete byte array
///
/// Telegram description:
///
/// AAAAAA[tab]BBBB[tab]CCCC[tab]DDDDDD[tab]EEEE[tab]FFFFFFFF[tab]GG[cr][lf] (42 bytes)
///
/// Data Comment Type Calculate to decimal
/// ----------------------------------------------------------------
/// AAAAAA EMF Int24 Value * 0.000000333
/// BBBB Magnetic field Int16 Value
/// CCCC Flow Int16 Value * 0.225 * Scalig factor
/// DDDDDD Volume Int24 Value / 16000 * Scaling factor
/// EEEE Impedance Int16 Value
/// FFFFFFFF Timestamp Uint32 Value / 8192
/// GG Checksum Byte
/// ----------------------------------------------------------------
///
/// Example:
/// FFFFFE 51EA 0000 65324E 0087 F6319DFF 86
/// FFDD3A 51F9 0000 65324E 0088 F631A60B 45
/// ...
/// </description>
/// <param name="data">A complete byte array data</param>
/// <returns>true = telegram OK, false = telegram NOK</returns>
public bool UpdateFromString(string telegram, int counter, ref Int64 volumeRawExtLast, ref Int64 timestampExtLast)
{
DateTime = DateTime.Now;
Counter = counter;
RefFlow = (float)Sequences.ProcessData.RefFlow.Val;
if ((telegram == null) || (telegram.Length < Length) ||
(telegram[6] != '\t') || (telegram[11] != '\t') || (telegram[16] != '\t') ||
(telegram[23] != '\t') || (telegram[28] != '\t') || (telegram[37] != '\t') ||
(telegram[40] != '\r') || (telegram[41] != '\n'))
{
Flags = OptoTelegramFlags.InvalidTelegram;
return false;
}
bool f1 = UInt32.TryParse(telegram.Substring(0, 6), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out EmfRaw);
bool f2 = Int16.TryParse(telegram.Substring(7, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out MagneticFieldRaw);
bool f3 = Int16.TryParse(telegram.Substring(12, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out FlowRaw);
bool f4 = UInt32.TryParse(telegram.Substring(17, 6), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out VolumeRaw);
bool f5 = Int16.TryParse(telegram.Substring(24, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out Impedance);
bool f6 = UInt32.TryParse(telegram.Substring(29, 8), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out Timestamp);
bool f7 = byte.TryParse(telegram.Substring(38, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CheckSum);
bool allOk = f1 && f2 && f3 && f4 && f5 && f6 && f7;
Flags = allOk ? OptoTelegramFlags.OK : OptoTelegramFlags.InvalidTelegram;
///
/// Cope with 'VolumeRaw' overflow
///
Int64 uncorrected = (Int64)(((UInt64)volumeRawExtLast & 0xFFFFFFFFFF000000UL) | VolumeRaw);
if (Math.Abs(uncorrected - volumeRawExtLast) <= 0x800000L)
{
VolumeRawExt = volumeRawExtLast = uncorrected;
}
else if (Math.Abs(uncorrected + 0x1000000L - volumeRawExtLast) <= 0x800000L)
{
VolumeRawExt = volumeRawExtLast = uncorrected + 0x1000000L;
}
else if (Math.Abs(uncorrected - 0x1000000L - volumeRawExtLast) <= 0x800000L)
{
VolumeRawExt = volumeRawExtLast = uncorrected - 0x1000000L;
}
else
{
VolumeRawExt = volumeRawExtLast = uncorrected;
}
///
/// Cope with 'Timestamp' overflow
///
uncorrected = (Int64)(((UInt64)timestampExtLast & 0xFFFFFFFF00000000UL) | Timestamp);
if (Math.Abs(uncorrected - timestampExtLast) <= 0x80000000L)
{
TimestampExt = timestampExtLast = uncorrected;
}
else if (Math.Abs(uncorrected + 0x100000000L - timestampExtLast) <= 0x80000000L)
{
TimestampExt = timestampExtLast = uncorrected + 0x100000000L;
}
else if (Math.Abs(uncorrected - 0x100000000L - timestampExtLast) <= 0x80000000L)
{
TimestampExt = timestampExtLast = uncorrected - 0x100000000L;
}
else
{
TimestampExt = timestampExtLast = uncorrected;
}
return allOk;
}
/// <summary>
/// Alternative to UpdateFromString(...) when data are flushed
/// </summary>
public bool UpdateFromStringDummy(string telegram)
{
DateTime = DateTime.Now;
RefFlow = (float)Sequences.ProcessData.RefFlow.Val;
if ((telegram == null) || (telegram.Length < Length) ||
(telegram[6] != '\t') || (telegram[11] != '\t') || (telegram[16] != '\t') ||
(telegram[23] != '\t') || (telegram[28] != '\t') || (telegram[37] != '\t') ||
(telegram[40] != '\r') || (telegram[41] != '\n'))
{
Flags = OptoTelegramFlags.InvalidTelegram;
return false;
}
//bool f1 = UInt32.TryParse(telegram.Substring(0, 6), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out EmfRaw);
//bool f2 = Int16.TryParse(telegram.Substring(7, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out MagneticFieldRaw);
//bool f3 = Int16.TryParse(telegram.Substring(12, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out FlowRaw);
//bool f4 = UInt32.TryParse(telegram.Substring(17, 6), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out VolumeRaw);
//bool f5 = Int16.TryParse(telegram.Substring(24, 4), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out Impedance);
//bool f6 = UInt32.TryParse(telegram.Substring(29, 8), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out Timestamp);
//bool f7 = byte.TryParse(telegram.Substring(38, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CheckSum);
//return f1 && f2 && f3 && f4 && f5 && f6 && f7;
return true;
}
public void SetFlags(OptoTelegramFlags flags)
{
this.Flags = flags;
}
public string ToString(double scalingFactor, OptoTelegramRaw previous)
{
if (Flags == OptoTelegramFlags.SyncError)
{
return "Sychronization error";
}
else if (Flags == OptoTelegramFlags.InvalidTelegram)
{
return "Invalid telegram";
}
else /// if (flags == OptoTelegramFlags.OK / OptoTelegramFlags.OK_TestStart / OptoTelegramFlags.OK_TestEnd)
{
return string.Format("{0}:{1}:{2}.{3}\t{4} :\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t{17}\t{18}\t{19}\t{20}\t{21}\t{22}",
DateTime.Hour.ToString("D2"),
DateTime.Minute.ToString("D2"),
DateTime.Second.ToString("D2"),
DateTime.Millisecond.ToString("D4"),
Counter,
EmfRaw.ToString("X6"),
MagneticFieldRaw.ToString("X4"),
FlowRaw.ToString("X4"),
VolumeRaw.ToString("X6"),
Impedance.ToString("X4"),
Timestamp.ToString("X8"),
CheckSum.ToString("X2"),
EMF().ToString("F4", culture),
MagneticField().ToString("F0", culture),
Flow(scalingFactor).ToString("F2", culture),
Volume(scalingFactor).ToString("F4", culture),
FlipTime().ToString("F0", culture),
TimestampDec().ToString("F4", culture),
(RefFlow * 1000).ToString("F2", culture),
VolumeDelta(scalingFactor, previous).ToString("F4", culture),
TimeDelta().ToString("F3", culture),
scalingFactor.ToString("F1", culture),
Label());
}
}
/// <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="optoDataCount">number of objects to process</param>
public static void FIRFilterFlow(OptoTelegramRaw[] optoData, int optoDataCount)
{
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 = 0; i < optoDataCount; i++)
{
int k = i - kSize;
if (k >= 0) optoData[k].RefFlow = filtered[i % kSize];
if (i < kSize2 || i >= optoDataCount - kSize2)
{
filtered[i % kSize] = optoData[i].RefFlow;
}
else
{
float weoightedSum = 0;
for (int j = -kSize2; j <= kSize2; j++)
weoightedSum += optoData[i + j].RefFlow * kernel[j + kSize2];
filtered[i % kSize] = weoightedSum;
}
}
for (int k = optoDataCount - kSize; k < optoDataCount; k++)
{
if (k >= 0) optoData[k].RefFlow = filtered[k % kSize];
}
}
}
}
@@ -0,0 +1,169 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Config.Entities;
using TBF.BenchControl.Generic;
using TBF.Resources;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public class ProcParams : ProcedureParamsBase, IParamsProvider, IProcedureParams
{
public MeterType MeterType;
public int FactorLimitLo; /// Lower limit for the calibration factor
public int FactorLimitHi; /// Upper limit for the calibration factor
#if ORACLE_DB
public int WMType_ID; /// Required for Oracle DB: ID_WZTyp in table VT_PRUEFPUNKT_SOLL_SD
public int WMType_Rev; /// Required for Oracle DB: Rev_WZTyp in table VT_PRUEFPUNKT_SOLL_SD
#endif
public override void InitializeAll()
{
MeterType = MeterType.AutoDetect;
FactorLimitLo = 1000;
FactorLimitHi = 8000;
#if ORACLE_DB
WMType_ID = 2; /// Value for iPerl DN15
WMType_Rev = 1; /// Value for iPerl DN15
#endif
}
string[] paramNames = new string[]
{
"iPerl type",
"Calib. factor Lo",
"Calib. factor Hi",
#if ORACLE_DB
"WMType ID",
"WMType Rev.",
#endif
};
public override string ParamName(int i) { return paramNames[i]; }
public override int ParamsCount() { return paramNames.Length; }
public override string ToString(int i)
{
switch (i)
{
case 0: return MeterType.ToString();
case 1: return FactorLimitLo.ToString();
case 2: return FactorLimitHi.ToString();
#if ORACLE_DB
case 3: return WMType_ID.ToString();
case 4: return WMType_Rev.ToString();
#endif
default: return string.Empty;
}
}
public void UpdateParam(int i, string strValue)
{
switch (i)
{
case 0:
for (MeterType mt = 0; mt < MeterType.Count; mt++)
{
if (mt.ToString().Equals(strValue)) { MeterType = mt; return; }
}
break;
case 1: FactorLimitLo = int.Parse(strValue); return;
case 2: FactorLimitHi = int.Parse(strValue); return;
#if ORACLE_DB
case 3: WMType_ID = int.Parse(strValue); return;
case 4: WMType_Rev = int.Parse(strValue); return;
#endif
default: return;
}
}
public bool ValidateParam(int i, string strValue, out string message)
{
message = string.Empty;
int iDummy;
switch (i)
{
case 0:
for (MeterType mt = 0; mt < MeterType.Count; mt++) if (mt.ToString().Equals(strValue)) return true;
break;
case 1:
case 2:
if (int.TryParse(strValue, out iDummy) && iDummy >= 1000 && iDummy <= 8000) return true;
break;
#if ORACLE_DB
case 3: /// WMType_ID
case 4: /// WMType_Rev
if (int.TryParse(strValue, out iDummy)) return true;
break;
#endif
default:
message = "Invalid index";
return false;
}
message = ParamName(i) + " is invalid";
return false;
}
void CopyContentTo(ProcParams prms)
{
prms.MeterType = this.MeterType;
prms.FactorLimitLo = this.FactorLimitLo;
prms.FactorLimitHi = this.FactorLimitHi;
#if ORACLE_DB
prms.WMType_ID = this.WMType_ID;
prms.WMType_Rev = this.WMType_Rev;
#endif
}
public IParamsProvider Clone()
{
ProcParams pars = new ProcParams();
CopyContentTo(pars);
return pars;
}
public override void UpdateProcedureParams(ComponentProcedure dbEntity)
{
if (dbEntity == null) return;
try
{
ProcParams tmp = (ProcParams)(new XmlSerializer(typeof(ProcParams)))
.Deserialize(new StringReader(dbEntity.Parameters));
procedureParamsEntity = dbEntity;
componentName = dbEntity.CmpntName;
procedure = dbEntity.Procedure;
tmp.CopyContentTo(this);
}
catch
{
}
}
public ProcParams()
{
}
public ProcParams(bool initialize)
{
if (initialize) InitializeAll();
}
public ProcParams(ComponentProcedure procParamsEntity, string componentName, Procedure procedure)
{
this.procedureParamsEntity = procParamsEntity;
this.componentName = componentName;
this.procedure = procedure;
}
}
}
@@ -0,0 +1,160 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
namespace TBF.BenchControl.TestMethods.iPerlCommunication.iPerlHead
{
public class StatusStruct
{
public static readonly int Length = 48;
public Byte Version;
public FlowState FlowState;
public UInt32 BillingVolume;
public UInt32 ForwardVolume;
public UInt32 ReverseVolume;
public UInt32 SecondsActive;
public UInt32 SecondsIdle;
public UInt32 SecondsUsed;
public UInt32 UTC;
public Int32 ScaledAvgFlowRate;
public UInt16 PeakFlowRate;
public UInt16 AlarmState;
public byte RebootCount;
public byte[] AlarmCount;
public UInt16 FlipTime;
public StatusStruct()
{
AlarmCount = new byte[7];
}
public byte[] ToByteArray()
{
byte[] result = new byte[Length];
result[0] = Version;
result[1] = (byte)FlowState;
result[2] = (byte)(BillingVolume & 0x000000FF);
result[3] = (byte)((BillingVolume >> 8) & 0x000000FF);
result[4] = (byte)((BillingVolume >> 16) & 0x000000FF);
result[5] = (byte)((BillingVolume >> 24) & 0x000000FF);
result[6] = (byte)(ForwardVolume & 0x000000FF);
result[7] = (byte)((ForwardVolume >> 8) & 0x000000FF);
result[8] = (byte)((ForwardVolume >> 16) & 0x000000FF);
result[9] = (byte)((ForwardVolume >> 24) & 0x000000FF);
result[10] = (byte)(ReverseVolume & 0x000000FF);
result[11] = (byte)((ReverseVolume >> 8) & 0x000000FF);
result[12] = (byte)((ReverseVolume >> 16) & 0x000000FF);
result[13] = (byte)((ReverseVolume >> 24) & 0x000000FF);
result[14] = (byte)(SecondsActive & 0x000000FF);
result[15] = (byte)((SecondsActive >> 8) & 0x000000FF);
result[16] = (byte)((SecondsActive >> 16) & 0x000000FF);
result[17] = (byte)((SecondsActive >> 24) & 0x000000FF);
result[18] = (byte)(SecondsIdle & 0x000000FF);
result[19] = (byte)((SecondsIdle >> 8) & 0x000000FF);
result[20] = (byte)((SecondsIdle >> 16) & 0x000000FF);
result[21] = (byte)((SecondsIdle >> 24) & 0x000000FF);
result[22] = (byte)(SecondsUsed & 0x000000FF);
result[23] = (byte)((SecondsUsed >> 8) & 0x000000FF);
result[24] = (byte)((SecondsUsed >> 16) & 0x000000FF);
result[25] = (byte)((SecondsUsed >> 24) & 0x000000FF);
result[26] = (byte)(UTC & 0x000000FF);
result[27] = (byte)((UTC >> 8) & 0x000000FF);
result[28] = (byte)((UTC >> 16) & 0x000000FF);
result[29] = (byte)((UTC >> 24) & 0x000000FF);
result[30] = (byte)(ScaledAvgFlowRate & 0x000000FF);
result[31] = (byte)((ScaledAvgFlowRate >> 8) & 0x000000FF);
result[32] = (byte)((ScaledAvgFlowRate >> 16) & 0x000000FF);
result[33] = (byte)((ScaledAvgFlowRate >> 24) & 0x000000FF); /// TODO: test with negative value
result[34] = (byte)(PeakFlowRate & 0x00FF);
result[35] = (byte)((PeakFlowRate >> 8) & 0x00FF);
result[36] = (byte)(AlarmState & 0x00FF);
result[37] = (byte)((AlarmState >> 8) & 0x00FF);
result[38] = RebootCount;
result[39] = AlarmCount[0];
result[40] = AlarmCount[1];
result[41] = AlarmCount[2];
result[42] = AlarmCount[3];
result[43] = AlarmCount[4];
result[44] = AlarmCount[5];
result[45] = AlarmCount[6];
result[46] = (byte)(FlipTime & 0x00FF);
result[47] = (byte)((FlipTime >> 8) & 0x00FF);
return result;
}
public static StatusStruct FromByteArray(byte[] data)
{
if (data.Length != Length) return null;
StatusStruct result = new StatusStruct();
result.Version = data[0];
result.FlowState = (FlowState)data[1];
result.BillingVolume = (((UInt32)data[5] * 256 + data[4]) * 256 + data[3]) * 256 + data[2];
result.ForwardVolume = (((UInt32)data[9] * 256 + data[8]) * 256 + data[7]) * 256 + data[6];
result.ReverseVolume = (((UInt32)data[13] * 256 + data[12]) * 256 + data[11]) * 256 + data[10];
result.SecondsActive = (((UInt32)data[17] * 256 + data[16]) * 256 + data[15]) * 256 + data[14];
result.SecondsIdle = (((UInt32)data[21] * 256 + data[20]) * 256 + data[19]) * 256 + data[18];
result.SecondsUsed = (((UInt32)data[25] * 256 + data[24]) * 256 + data[23]) * 256 + data[22];
result.UTC = (((UInt32)data[29] * 256 + data[28]) * 256 + data[27]) * 256 + data[26];
result.ScaledAvgFlowRate = (((Int32)data[33] * 256 + data[32]) * 256 + data[31]) * 256 + data[30]; /// TODO: test with negative value
result.PeakFlowRate = (UInt16)(data[34] + 256 * data[35]);
result.AlarmState = (UInt16)(data[36] + 256 * data[37]);
result.RebootCount = data[38];
result.AlarmCount[0] = data[39];
result.AlarmCount[1] = data[40];
result.AlarmCount[2] = data[41];
result.AlarmCount[3] = data[42];
result.AlarmCount[4] = data[43];
result.AlarmCount[5] = data[44];
result.AlarmCount[6] = data[45];
result.FlipTime = (UInt16)(data[46] * 256 + data[47]);
return result;
}
public override string ToString()
{
return string.Format("Status: V{0} Flow={1} BillVol={2} ForwVol={3} RevVol={4} SecActive={5}s SecIdle={6}s SecUsed={7}s UTC={8} AvgFlowRate={9} PeekFlowRate={10} AlarmState={11} RebootCount={12} A0={13} A1={14} A2={15} A3={16} A4={17} A5={18} A6={19} FlipTime={20}",
Version,
FlowState,
BillingVolume,
ForwardVolume,
ReverseVolume,
SecondsActive,
SecondsIdle,
SecondsUsed,
UTC,
ScaledAvgFlowRate,
PeakFlowRate,
AlarmState,
RebootCount,
AlarmCount[0],
AlarmCount[1],
AlarmCount[2],
AlarmCount[3],
AlarmCount[4],
AlarmCount[5],
AlarmCount[6],
FlipTime);
}
}
}