Compare commits

..
Author SHA1 Message Date
michal bcb33cde78 Store changes on Iperl
Add and expand unit tests for iPerl communication, refactor OptoHead methods, update log4net reference, and increment AssemblyVersion.
2026-03-03 14:34:30 +01:00
michal 8229c5eb63 Improve logging and error handling in FlyingStart and FlyingStartMassCollection sequences. 2026-03-03 12:19:03 +01:00
michal 6dc9520897 Add simulation mode in UniCB. 2026-03-03 12:17:45 +01:00
michal 90cd53b05f Iperl -> Iperl ASIC
Refactor iPerl communication system:

- Consolidate redundant OptoHead methods.
- Introduce new utilities for diagnostic LED state handling and volume unit conversions.
- Improve FIFO logic in flow direction detection with enhanced regression calculation.
- Add enhanced debugging and logging within communication layers (`SerialDriver` and `RadioService`).
- Update communication protocols for improved response handling and configuration management.
- Replace raw volume with meaningful unit-based values (`RawVolume1to4`).
2026-02-19 19:47:26 +01:00
michal aa0d775b8e Add unit tests for iPerl communication protocols, including hex logger, LED parsers, wired protocols, and frame builders. Update project file to include new test suites. 2026-02-15 22:45:37 +01:00
michal 2b3eb5f10a Refactor iPerl communication services: replace legacy calibration and configuration methods with OptoHeadTest functionality, streamline diagnostic LED state handling, and clean up unused code. 2026-02-15 22:45:13 +01:00
michal 010bc7131a Update AssemblyVersion to 3.9.2200.1 and fix incorrect references to OpticalHeadTest in iPerl communication logic. 2026-02-13 09:39:25 +01:00
michal e22a0767f4 Update iPerl communication: adjust baud rate to 38400, refactor opto-datastream processing, integrate diagnostic LED parser, and enhance serial port configuration. 2026-02-13 09:26:56 +01:00
michal 66b43350cc Add iPerl communication services and utilities. Include OptoTelegramRaw, RadioService, OpthoHeadService, SerialDriver, and related diagnostic parsers for enhanced communication with iPerl devices. 2026-02-13 08:41:32 +01:00
127 changed files with 7117 additions and 17942 deletions
-2
View File
@@ -32,8 +32,6 @@ LabelPrinting/bin/
LabelPrinting/obj/
MergeResultsDBs/bin/
MergeResultsDBs/obj/
NfcC7_Dll/bin/
NfcC7_Dll/obj/
OrderManagement/bin/
OrderManagement/obj/
ProductionTracing/bin/
+2 -2
View File
@@ -19,7 +19,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
@@ -30,7 +30,7 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;JUZNA_AFRIKA_NEW;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;JUZNA_AFRIKA_NEW;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
+2 -2
View File
@@ -23,7 +23,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;HEAT_METERS;</DefineConstants>
<DefineConstants>DEBUG;TRACE;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
@@ -32,7 +32,7 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
-17
View File
@@ -1,17 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Copyright>Copyright © 2025</Copyright>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DefineConstants>TRACE;</DefineConstants>
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
</PropertyGroup>
</Project>
-160
View File
@@ -1,160 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
//*****************************************************************************
// Copyright 2020 Sensus GmbH Ludwigshafen. All rights reserved.
// Author: Venkat, Rajeshwar
//*****************************************************************************
namespace Sensus.Poseidon.NfcHandler
{
public static class Tools
{
public static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
// thanks to https://stackoverflow.com/questions/43289/comparing-two-byte-arrays-in-net
if (a1.Length != a2.Length)
return false;
for (int i = 0; i < a1.Length; i++)
if (a1[i] != a2[i])
return false;
return true;
}
public static string SwapHex(string sHex)
{
string sResult = "";
int iPos = sHex.Length - 2;
while (iPos >= 0)
{
sResult += sHex.Substring(iPos, 2);
sHex = sHex.Remove(iPos, 2);
iPos = sHex.Length - 2;
}
return sResult;
}
public static string DecimalToHexString(string value, int size = 1)
{
try
{
long Lval = long.Parse(value);
if (size == 1) return Lval.ToString("X2");
if (size == 2) return Lval.ToString("X4");
if (size == 4) return Lval.ToString("X8");
}
catch (Exception)
{
if (size == 1) return "00";
if (size == 2) return "0000";
if (size == 4) return "00000000";
}
return "00";
}
public static string ByteToHexString(byte data)
{
List<byte> val = new List<byte>();
val.Add(data);
byte[] arr = val.ToArray();
return BytesToHex(arr);
}
public static string BytesToHex(byte[] data)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in data)
sb.Append(b.ToString("X2"));
return sb.ToString();
}
public static byte[] HexStringToByteArray(String hexString)
{
int numberChars = hexString.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
return bytes;
}
public enum InitialCrcValue
{
Zeros,
NonZero1 = 0xffff,
NonZero2 = 0x1D0F
}
public class Crc16Ccitt
{
private const ushort poly = 0x1021;
ushort[] table = new ushort[256];
ushort initialValue = 0;
public ushort ComputeChecksum(byte[] bytes)
{
ushort crc = this.initialValue;
for (int i = 0; i < bytes.Length; ++i)
{
crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xff & bytes[i]))]);
}
return crc;
}
public byte[] ComputeChecksumBytes(byte[] bytes)
{
ushort crc = ComputeChecksum(bytes);
return BitConverter.GetBytes(crc);
}
public Crc16Ccitt(InitialCrcValue initialValue)
{
this.initialValue = (ushort) initialValue;
ushort temp, a;
for (int i = 0; i < table.Length; ++i)
{
temp = 0;
a = (ushort) (i << 8);
for (int j = 0; j < 8; ++j)
{
if (((temp ^ a) & 0x8000) != 0)
{
temp = (ushort) ((temp << 1) ^ poly);
}
else
{
temp <<= 1;
}
a <<= 1;
}
table[i] = temp;
}
}
public byte[] calcCRCfromMessage(byte[] message)
{
// CRC calculation goes from MessageID to Password
// For Read this means MsgID (1) + Offset (2) + PayloadLength (1) + Password (2) = 6
// for write the length of the payload comes on top.
// STX(1), length(1), CRC(2) and ETX(1) are excluded, in total 5 bytes.
//
// the method works both for sending messages (where the CRC and ETX are not in message)
// and for receiving messages (where the CRC and ETX are included at the end)
byte[] crc_msg = new byte[message[1]]; // message length is 2nd byte
Array.Copy(message, 2, crc_msg, 0, crc_msg.Length);
return ComputeChecksumBytes(crc_msg);
}
public string commentCRC(byte[] crc_meter, byte[] crc_computed)
{
bool crc_do_match = Tools.ByteArrayCompare(crc_meter, crc_computed);
string crcComment = crc_do_match ? "ok." : "CRC DOESN'T MATCH!!";
return "CRC Meter: " + Tools.BytesToHex(crc_meter) + (crc_do_match ? " == " : " != ")
+ "CRC Computed: " + Tools.BytesToHex(crc_computed) + ". " + crcComment;
}
public bool crc_do_match(byte[] a, byte[] b)
{
return ByteArrayCompare(a, b);
}
}
}
}
+2 -2
View File
@@ -19,7 +19,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;IPERL;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;DEBUG;IPERL;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -29,7 +29,7 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;IPERL;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;IPERL;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
+2 -2
View File
@@ -17,7 +17,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;LANG_PL;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;DEBUG;LANG_PL;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
@@ -25,7 +25,7 @@
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;HEAT_METERS;</DefineConstants>
<DefineConstants>TRACE;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
-14
View File
@@ -119,8 +119,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sensus.iPerl.TestConsole",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NfcS5_DLL", "..\NfcS5_DLL\NfcS5_DLL.csproj", "{5954D496-CAAB-4F7A-BDE2-BDC8F47DAB19}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NfcC7_DLL", "NfcC7_DLL\NfcC7_DLL.csproj", "{53E75979-B530-4805-8FC9-B314F14A62BE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -541,18 +539,6 @@ Global
{5954D496-CAAB-4F7A-BDE2-BDC8F47DAB19}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{5954D496-CAAB-4F7A-BDE2-BDC8F47DAB19}.Release|x86.ActiveCfg = Release|Any CPU
{5954D496-CAAB-4F7A-BDE2-BDC8F47DAB19}.Release|x86.Build.0 = Release|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Debug|x86.ActiveCfg = Debug|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Debug|x86.Build.0 = Debug|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Release|Any CPU.Build.0 = Release|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Release|x86.ActiveCfg = Release|Any CPU
{53E75979-B530-4805-8FC9-B314F14A62BE}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
-44
View File
@@ -1,44 +0,0 @@
///
/// Copyright (c) 2017 Sensus Metering Systems
///
using System.Drawing;
using System.Windows.Forms;
namespace TBF.Boxes
{
public class CheckBoxImage : PictureBox
{
private bool cbChecked;
private readonly Image checkedImg;
private readonly Image uncheckedImg;
public CheckBoxImage()
: this(new Bitmap(TBF.Properties.Resources.SwitchOn), new Bitmap(TBF.Properties.Resources.SwitchOff), true)
{
SizeMode = PictureBoxSizeMode.StretchImage;
}
public CheckBoxImage(Image checkedImg, Image uncheckedImg, bool initState)
: base()
{
this.checkedImg = checkedImg;
this.uncheckedImg = uncheckedImg;
Click += (sender, e) => { Checked = !Checked; };
Checked = initState;
}
public bool Checked
{
get { return cbChecked; }
set
{
if (Enabled)
{
Image = value ? checkedImg : uncheckedImg;
cbChecked = value;
}
}
}
}
}
+2 -2
View File
@@ -29,5 +29,5 @@ using System.Runtime.InteropServices;
// Build Number
// Revision
//
[assembly: AssemblyVersion("3.9.2149.0")]
[assembly: AssemblyFileVersion("3.9.2149.0")]
[assembly: AssemblyVersion("3.9.2201.1")]
[assembly: AssemblyFileVersion("3.9.2201.1")]
-5
View File
@@ -1,5 +0,0 @@
## Version History
| Version | Target Environment | Title | Description |
|------------|--------------------------------------------------------------|-----------------------------------------------------|------------------------------------|
| 3.9.2149.0 | HeatMeters, Heat meter sensors, Procedure Dilog, Tab Process | Excanged columns value 'Sensor' and 'Heat meter sensor' | Fix in code ProcedureDlg, row 1851 |
+12
View File
@@ -8,6 +8,7 @@ using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using Common;
using Config.Entities;
@@ -526,6 +527,17 @@ namespace TBF.Rig.ControlBoard.Uni
Bridge.OnStateMachineTick(this, new StateMachineTickEventArgs(route, ProcessData.MsrmntAvailableFlags, ProcessData.MeasuredValues,
ProcessData.AltStrings, ProcessData.Setpoints, ProcessData.CustomBitmaps));
/// Make simulation to finish - count
if (cbCfg.DebugLevel == DebugMode.Simulate)
{
_ = Task.Run(async () =>
{
await Task.Delay(5000);
Data.State |= (ulong)StatusP.TestCompleted;
log.Debug("Simulation StatusP.TestCompleted in background.");
});
}
/// Make sure the serial port is open
if (cbCfg.DebugLevel == DebugMode.Normal && (serialPort == null || !serialPort.IsOpen))
{
@@ -1,23 +0,0 @@
using TBF.Rig.Generic;
using System.Collections.Generic;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
{
public class Factory: IComponentFactory
{
public string ClassName { get { return this.GetType().Namespace.Substring(8); } }
public override string ToString() { return ClassName; }
public IComponent DummyComponent() { return new IPerlReader(); }
public IComponent GetComponent(IComponentCfg cfg, IList<IComponent> components) { return new IPerlReader(cfg); }
public IComponentCfg DefaultConfig() { return new IPerlCfg(this); }
public IComponentCfg CmpntCfgFromCmpntEntity(Config.Entities.Component component)
{
return ComponentCfgBase.CreateFromDbEntity(IPerlCfg.Serializer, component, this);
}
}
}
@@ -1,70 +0,0 @@
using System.Collections.Generic;
using System.Xml.Serialization;
using Common;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
{
public class IPerlCfg : ComponentCfgBase, Generic.IComponentCfg
{
public static XmlSerializer Serializer = XmlSerializer.FromTypes(new[] { typeof(IPerlCfg) })[0];
public override XmlSerializer GetSerializer() { return Serializer; }
public IComponentCfgCtrl GetControl(IList<Component> cmpntEntities)
{
return new IPerlCfgCtrl();
}
///
/// Serialized parameters
///
public bool UseTcpIP;
public string OptoIPAddress;
public ushort OptoTcpipPortNr;
public int HeadCommunicationComPortNr;
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, 1 .. 10
public CommunicationInterface CommunicationInterface; /// Communication Interface: RFID or NFC
/// <summary> Procedure parameters </summary>
[XmlIgnore]
public ProcParams ProcParams;
public override IParamsProvider GetRuntimeProcParamsProvider() { return ProcParams; }
public override IParamsProvider CreateProcParamsProvider() { return new ProcParams(true); }
[XmlIgnore]
public MeterType MeterType { get { return (ProcParams != null) ? ProcParams.MeterType : MeterType.AutoDetect; } }
/// Private parameterless constructor invoked by all other (public) constructors
IPerlCfg()
{
Name = "iPerl";
ParentName = string.Empty;
OptoComPortNr = 10;
RfidComPortNr = 0; /// = use mux. board
MuxBoardNr = 1;
ProcParams = CreateProcParamsProvider() as ProcParams;
CommunicationInterface = CommunicationInterface.RFID;
HeadCommunicationComPortNr = 0;
}
public IPerlCfg(IComponentFactory factory)
: this()
{
this.Factory = factory;
}
public string ToString(int i)
{
return $"{Name} Group1 (mux#)={MuxBoardNr}, Group2={Group}, Opto=Com{OptoComPortNr}, {CommunicationInterface}=Com{RfidComPortNr}";
}
}
}
@@ -1,163 +0,0 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.Net;
using System.Windows.Forms;
using Common;
using TBF.Rig.Generic;
using TBF.Resources;
using TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
{
public partial class IPerlCfgCtrl : UserControl, IComponentCfgCtrl
{
public bool ShowMore { get { return false; } }
IPerlCfg config;
public IComponentCfg Config
{
get { return config as IComponentCfg; }
set
{
config = value as IPerlCfg;
Redraw();
}
}
public IPerlCfgCtrl()
{
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();
headPortNrTextBox.Text = config.HeadCommunicationComPortNr.ToString();
optoSerialPortTextBox.Text = config.OptoComPortNr.ToString();
rfidPortNrTextBox.Text = config.RfidComPortNr.ToString();
muxBoardNrTextBox.Text = config.MuxBoardNr.ToString();
groupTextBox.Text = config.Group.ToString();
comboBoxCommunicationInterface.SelectedItem = config.CommunicationInterface.ToString();
tabPage2.Controls.Add(new IperlHeadTestCtrl(config));
}
public void Unlock()
{
nameTextBox.Enabled = true;
radioButton1.Enabled = true;
radioButton2.Enabled = true;
ipAddressTextBox.Enabled = true;
tcpipPortTextBox.Enabled = true;
optoSerialPortTextBox.Enabled = true;
rfidPortNrTextBox.Enabled = true;
headPortNrTextBox.Enabled = true;
muxBoardNrTextBox.Enabled = true;
groupTextBox.Enabled = true;
comboBoxCommunicationInterface.Enabled = true;
}
public CfgUpdateFlags VerifyCfg(ref string message)
{
CfgUpdateFlags flags = CfgUpdateFlags.None;
int dummy;
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(headPortNrTextBox.Text, out dummy) || dummy < 0 || dummy > 999)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'Head communication serial port nr.' is not valid";
}
if (!int.TryParse(muxBoardNrTextBox.Text, out dummy) || dummy < 1 || dummy > 4)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + string.Format(Strings.Invalid_0, muxBoardNrLabel.Text);
}
if (!int.TryParse(groupTextBox.Text, out dummy) || dummy < 1 || dummy > 10)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + string.Format(Strings.Invalid_0, groupLabel.Text);
}
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);
config.CommunicationInterface = (CommunicationInterface)comboBoxCommunicationInterface.SelectedIndex;
config.HeadCommunicationComPortNr = int.Parse(headPortNrTextBox.Text);
return flags;
}
}
}
@@ -1,441 +0,0 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
{
partial class IPerlCfgCtrl
{
/// <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.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.comboBoxCommunicationInterface = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.rfidPortNrTextBox = new System.Windows.Forms.TextBox();
this.rfidSerialPortNrLabel = new System.Windows.Forms.Label();
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.radioButton1 = new System.Windows.Forms.RadioButton();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.optoSerialPortLabel = new System.Windows.Forms.Label();
this.optoSerialPortTextBox = new System.Windows.Forms.TextBox();
this.groupTextBox = new System.Windows.Forms.TextBox();
this.groupLabel = new System.Windows.Forms.Label();
this.muxBoardNrTextBox = new System.Windows.Forms.TextBox();
this.muxBoardNrLabel = new System.Windows.Forms.Label();
this.nameTextBox = new System.Windows.Forms.TextBox();
this.nameLabel = new System.Windows.Forms.Label();
this.classNameLabel = new System.Windows.Forms.Label();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.headPortNrTextBox = new System.Windows.Forms.TextBox();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.optoDataGroupBox.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(3, 3);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(611, 432);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.groupBox2);
this.tabPage1.Controls.Add(this.label4);
this.tabPage1.Controls.Add(this.label3);
this.tabPage1.Controls.Add(this.groupBox1);
this.tabPage1.Controls.Add(this.optoDataGroupBox);
this.tabPage1.Controls.Add(this.groupTextBox);
this.tabPage1.Controls.Add(this.groupLabel);
this.tabPage1.Controls.Add(this.muxBoardNrTextBox);
this.tabPage1.Controls.Add(this.muxBoardNrLabel);
this.tabPage1.Controls.Add(this.nameTextBox);
this.tabPage1.Controls.Add(this.nameLabel);
this.tabPage1.Controls.Add(this.classNameLabel);
this.tabPage1.Location = new System.Drawing.Point(4, 25);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(603, 403);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Config";
this.tabPage1.UseVisualStyleBackColor = true;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(208, 101);
this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(40, 16);
this.label4.TabIndex = 25;
this.label4.Text = "1 .. 10";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(208, 72);
this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(33, 16);
this.label3.TabIndex = 24;
this.label3.Text = "1 .. 4";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.comboBoxCommunicationInterface);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.rfidPortNrTextBox);
this.groupBox1.Controls.Add(this.rfidSerialPortNrLabel);
this.groupBox1.Location = new System.Drawing.Point(10, 259);
this.groupBox1.Margin = new System.Windows.Forms.Padding(4);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(4);
this.groupBox1.Size = new System.Drawing.Size(552, 68);
this.groupBox1.TabIndex = 23;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "RFID / NFC communication (in case mux. board is not used)";
//
// comboBoxCommunicationInterface
//
this.comboBoxCommunicationInterface.Enabled = false;
this.comboBoxCommunicationInterface.FormattingEnabled = true;
this.comboBoxCommunicationInterface.Items.AddRange(new object[] {
"RFID",
"NFC"});
this.comboBoxCommunicationInterface.Location = new System.Drawing.Point(201, 27);
this.comboBoxCommunicationInterface.Name = "comboBoxCommunicationInterface";
this.comboBoxCommunicationInterface.Size = new System.Drawing.Size(71, 24);
this.comboBoxCommunicationInterface.TabIndex = 9;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(41, 30);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(153, 16);
this.label1.TabIndex = 8;
this.label1.Text = "Communication Interface";
//
// rfidPortNrTextBox
//
this.rfidPortNrTextBox.Enabled = false;
this.rfidPortNrTextBox.Location = new System.Drawing.Point(439, 26);
this.rfidPortNrTextBox.Margin = new System.Windows.Forms.Padding(4);
this.rfidPortNrTextBox.Name = "rfidPortNrTextBox";
this.rfidPortNrTextBox.Size = new System.Drawing.Size(44, 22);
this.rfidPortNrTextBox.TabIndex = 7;
//
// rfidSerialPortNrLabel
//
this.rfidSerialPortNrLabel.AutoSize = true;
this.rfidSerialPortNrLabel.Location = new System.Drawing.Point(321, 30);
this.rfidSerialPortNrLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.rfidSerialPortNrLabel.Name = "rfidSerialPortNrLabel";
this.rfidSerialPortNrLabel.Size = new System.Drawing.Size(88, 16);
this.rfidSerialPortNrLabel.TabIndex = 6;
this.rfidSerialPortNrLabel.Text = "Serial port nr.:";
//
// 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(10, 131);
this.optoDataGroupBox.Margin = new System.Windows.Forms.Padding(4);
this.optoDataGroupBox.Name = "optoDataGroupBox";
this.optoDataGroupBox.Padding = new System.Windows.Forms.Padding(4);
this.optoDataGroupBox.Size = new System.Drawing.Size(552, 119);
this.optoDataGroupBox.TabIndex = 18;
this.optoDataGroupBox.TabStop = false;
this.optoDataGroupBox.Text = "Opto-data";
//
// tcpipPortLabel
//
this.tcpipPortLabel.AutoSize = true;
this.tcpipPortLabel.Location = new System.Drawing.Point(41, 87);
this.tcpipPortLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.tcpipPortLabel.Name = "tcpipPortLabel";
this.tcpipPortLabel.Size = new System.Drawing.Size(54, 16);
this.tcpipPortLabel.TabIndex = 4;
this.tcpipPortLabel.Text = "Port nr..:";
//
// tcpipPortTextBox
//
this.tcpipPortTextBox.Enabled = false;
this.tcpipPortTextBox.Location = new System.Drawing.Point(143, 84);
this.tcpipPortTextBox.Margin = new System.Windows.Forms.Padding(4);
this.tcpipPortTextBox.Name = "tcpipPortTextBox";
this.tcpipPortTextBox.Size = new System.Drawing.Size(51, 22);
this.tcpipPortTextBox.TabIndex = 5;
//
// ipAddressLabel
//
this.ipAddressLabel.AutoSize = true;
this.ipAddressLabel.Location = new System.Drawing.Point(41, 59);
this.ipAddressLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.ipAddressLabel.Name = "ipAddressLabel";
this.ipAddressLabel.Size = new System.Drawing.Size(78, 16);
this.ipAddressLabel.TabIndex = 2;
this.ipAddressLabel.Text = "IP address.:";
//
// ipAddressTextBox
//
this.ipAddressTextBox.Enabled = false;
this.ipAddressTextBox.Location = new System.Drawing.Point(143, 55);
this.ipAddressTextBox.Margin = new System.Windows.Forms.Padding(4);
this.ipAddressTextBox.Name = "ipAddressTextBox";
this.ipAddressTextBox.Size = new System.Drawing.Size(129, 22);
this.ipAddressTextBox.TabIndex = 3;
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Checked = true;
this.radioButton1.Enabled = false;
this.radioButton1.Location = new System.Drawing.Point(29, 23);
this.radioButton1.Margin = new System.Windows.Forms.Padding(4);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(99, 20);
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(312, 23);
this.radioButton2.Margin = new System.Windows.Forms.Padding(4);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(115, 20);
this.radioButton2.TabIndex = 1;
this.radioButton2.Text = "Use serial port";
this.radioButton2.UseVisualStyleBackColor = true;
//
// optoSerialPortLabel
//
this.optoSerialPortLabel.AutoSize = true;
this.optoSerialPortLabel.Location = new System.Drawing.Point(321, 55);
this.optoSerialPortLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.optoSerialPortLabel.Name = "optoSerialPortLabel";
this.optoSerialPortLabel.Size = new System.Drawing.Size(88, 16);
this.optoSerialPortLabel.TabIndex = 6;
this.optoSerialPortLabel.Text = "Serial port nr.:";
//
// optoSerialPortTextBox
//
this.optoSerialPortTextBox.Enabled = false;
this.optoSerialPortTextBox.Location = new System.Drawing.Point(439, 52);
this.optoSerialPortTextBox.Margin = new System.Windows.Forms.Padding(4);
this.optoSerialPortTextBox.Name = "optoSerialPortTextBox";
this.optoSerialPortTextBox.Size = new System.Drawing.Size(44, 22);
this.optoSerialPortTextBox.TabIndex = 7;
//
// groupTextBox
//
this.groupTextBox.Enabled = false;
this.groupTextBox.Location = new System.Drawing.Point(153, 97);
this.groupTextBox.Margin = new System.Windows.Forms.Padding(4);
this.groupTextBox.Name = "groupTextBox";
this.groupTextBox.Size = new System.Drawing.Size(44, 22);
this.groupTextBox.TabIndex = 22;
//
// groupLabel
//
this.groupLabel.AutoSize = true;
this.groupLabel.Location = new System.Drawing.Point(6, 101);
this.groupLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.groupLabel.Name = "groupLabel";
this.groupLabel.Size = new System.Drawing.Size(54, 16);
this.groupLabel.TabIndex = 21;
this.groupLabel.Text = "Group 2";
//
// muxBoardNrTextBox
//
this.muxBoardNrTextBox.Enabled = false;
this.muxBoardNrTextBox.Location = new System.Drawing.Point(153, 69);
this.muxBoardNrTextBox.Margin = new System.Windows.Forms.Padding(4);
this.muxBoardNrTextBox.Name = "muxBoardNrTextBox";
this.muxBoardNrTextBox.Size = new System.Drawing.Size(44, 22);
this.muxBoardNrTextBox.TabIndex = 20;
//
// muxBoardNrLabel
//
this.muxBoardNrLabel.AutoSize = true;
this.muxBoardNrLabel.Location = new System.Drawing.Point(6, 72);
this.muxBoardNrLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.muxBoardNrLabel.Name = "muxBoardNrLabel";
this.muxBoardNrLabel.Size = new System.Drawing.Size(131, 16);
this.muxBoardNrLabel.TabIndex = 19;
this.muxBoardNrLabel.Text = "Group 1 (mux. board)";
//
// nameTextBox
//
this.nameTextBox.Enabled = false;
this.nameTextBox.Location = new System.Drawing.Point(153, 40);
this.nameTextBox.Margin = new System.Windows.Forms.Padding(4);
this.nameTextBox.Name = "nameTextBox";
this.nameTextBox.Size = new System.Drawing.Size(160, 22);
this.nameTextBox.TabIndex = 17;
//
// nameLabel
//
this.nameLabel.AutoSize = true;
this.nameLabel.Location = new System.Drawing.Point(6, 44);
this.nameLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.nameLabel.Name = "nameLabel";
this.nameLabel.Size = new System.Drawing.Size(44, 16);
this.nameLabel.TabIndex = 16;
this.nameLabel.Text = "Name";
//
// classNameLabel
//
this.classNameLabel.AutoSize = true;
this.classNameLabel.Location = new System.Drawing.Point(149, 11);
this.classNameLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.classNameLabel.Name = "classNameLabel";
this.classNameLabel.Size = new System.Drawing.Size(78, 16);
this.classNameLabel.TabIndex = 15;
this.classNameLabel.Text = "ClassName";
//
// tabPage2
//
this.tabPage2.Location = new System.Drawing.Point(4, 25);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(603, 403);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Test";
this.tabPage2.UseVisualStyleBackColor = true;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.headPortNrTextBox);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Location = new System.Drawing.Point(10, 335);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(552, 50);
this.groupBox2.TabIndex = 26;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Head Communication";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(321, 18);
this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 16);
this.label2.TabIndex = 7;
this.label2.Text = "Serial port nr.:";
//
// headPortNrTextBox
//
this.headPortNrTextBox.Enabled = false;
this.headPortNrTextBox.Location = new System.Drawing.Point(439, 15);
this.headPortNrTextBox.Margin = new System.Windows.Forms.Padding(4);
this.headPortNrTextBox.Name = "headPortNrTextBox";
this.headPortNrTextBox.Size = new System.Drawing.Size(44, 22);
this.headPortNrTextBox.TabIndex = 8;
//
// IperlHeadCfgCtrl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tabControl1);
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "IPerlCfgCtrl";
this.Size = new System.Drawing.Size(617, 438);
this.Load += new System.EventHandler(this.WaterMeterCfgCtrl_Load);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.optoDataGroupBox.ResumeLayout(false);
this.optoDataGroupBox.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ComboBox comboBoxCommunicationInterface;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox rfidPortNrTextBox;
private System.Windows.Forms.Label rfidSerialPortNrLabel;
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;
private System.Windows.Forms.RadioButton radioButton1;
private System.Windows.Forms.RadioButton radioButton2;
private System.Windows.Forms.Label optoSerialPortLabel;
private System.Windows.Forms.TextBox optoSerialPortTextBox;
private System.Windows.Forms.TextBox groupTextBox;
private System.Windows.Forms.Label groupLabel;
private System.Windows.Forms.TextBox muxBoardNrTextBox;
private System.Windows.Forms.Label muxBoardNrLabel;
private System.Windows.Forms.TextBox nameTextBox;
private System.Windows.Forms.Label nameLabel;
private System.Windows.Forms.Label classNameLabel;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TextBox headPortNrTextBox;
private System.Windows.Forms.Label label2;
}
}
@@ -1,120 +0,0 @@
<?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>
File diff suppressed because it is too large Load Diff
@@ -1,137 +0,0 @@
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
{
partial class IperlHeadTestCtrl
{
/// <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.optoTestGroupBox = new System.Windows.Forms.GroupBox();
this.optoListBox = new System.Windows.Forms.ListBox();
this.rfidOutputListBox = new System.Windows.Forms.ListBox();
this.RfidTestGroupBox = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.rfidCommandComboBox = new System.Windows.Forms.ComboBox();
this.commandTestButton = new System.Windows.Forms.Button();
this.optoTestGroupBox.SuspendLayout();
this.RfidTestGroupBox.SuspendLayout();
this.SuspendLayout();
//
// optoTestGroupBox
//
this.optoTestGroupBox.Controls.Add(this.optoListBox);
this.optoTestGroupBox.Location = new System.Drawing.Point(5, 4);
this.optoTestGroupBox.Name = "optoTestGroupBox";
this.optoTestGroupBox.Size = new System.Drawing.Size(591, 161);
this.optoTestGroupBox.TabIndex = 2;
this.optoTestGroupBox.TabStop = false;
this.optoTestGroupBox.Text = "Opto-data";
//
// optoListBox
//
this.optoListBox.FormattingEnabled = true;
this.optoListBox.ItemHeight = 16;
this.optoListBox.Location = new System.Drawing.Point(7, 22);
this.optoListBox.Name = "optoListBox";
this.optoListBox.Size = new System.Drawing.Size(573, 132);
this.optoListBox.TabIndex = 0;
//
// rfidOutputListBox
//
this.rfidOutputListBox.FormattingEnabled = true;
this.rfidOutputListBox.ItemHeight = 16;
this.rfidOutputListBox.Location = new System.Drawing.Point(5, 54);
this.rfidOutputListBox.Name = "rfidOutputListBox";
this.rfidOutputListBox.SelectionMode = System.Windows.Forms.SelectionMode.None;
this.rfidOutputListBox.Size = new System.Drawing.Size(575, 164);
this.rfidOutputListBox.TabIndex = 3;
//
// RfidTestGroupBox
//
this.RfidTestGroupBox.Controls.Add(this.rfidOutputListBox);
this.RfidTestGroupBox.Controls.Add(this.label2);
this.RfidTestGroupBox.Controls.Add(this.rfidCommandComboBox);
this.RfidTestGroupBox.Controls.Add(this.commandTestButton);
this.RfidTestGroupBox.Location = new System.Drawing.Point(5, 171);
this.RfidTestGroupBox.Name = "RfidTestGroupBox";
this.RfidTestGroupBox.Size = new System.Drawing.Size(591, 224);
this.RfidTestGroupBox.TabIndex = 3;
this.RfidTestGroupBox.TabStop = false;
this.RfidTestGroupBox.Text = "RFID / NFC data";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(2, 25);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(69, 16);
this.label2.TabIndex = 2;
this.label2.Text = "Command";
//
// rfidCommandComboBox
//
this.rfidCommandComboBox.FormattingEnabled = true;
this.rfidCommandComboBox.Location = new System.Drawing.Point(86, 19);
this.rfidCommandComboBox.Name = "rfidCommandComboBox";
this.rfidCommandComboBox.Size = new System.Drawing.Size(341, 24);
this.rfidCommandComboBox.TabIndex = 1;
//
// commandTestButton
//
this.commandTestButton.Location = new System.Drawing.Point(449, 19);
this.commandTestButton.Name = "commandTestButton";
this.commandTestButton.Size = new System.Drawing.Size(126, 24);
this.commandTestButton.TabIndex = 0;
this.commandTestButton.Text = "Send command";
this.commandTestButton.UseVisualStyleBackColor = true;
this.commandTestButton.MouseClick += new System.Windows.Forms.MouseEventHandler(this.CommandTestButtonClick);
//
// IperlHeadTestCtrl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.optoTestGroupBox);
this.Controls.Add(this.RfidTestGroupBox);
this.Name = "IperlHeadTestCtrl";
this.Size = new System.Drawing.Size(611, 432);
this.Load += new System.EventHandler(this.UserControl_Load);
this.optoTestGroupBox.ResumeLayout(false);
this.RfidTestGroupBox.ResumeLayout(false);
this.RfidTestGroupBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox optoTestGroupBox;
private System.Windows.Forms.ListBox rfidOutputListBox;
private System.Windows.Forms.GroupBox RfidTestGroupBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox rfidCommandComboBox;
private System.Windows.Forms.Button commandTestButton;
private System.Windows.Forms.ListBox optoListBox;
}
}
@@ -1,192 +0,0 @@
using System;
using System.Threading;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication;
using TBF.Rig.RegisterReaders.iPerlReaderUNI.test;
using TBF.Rig.Sequences;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
{
public partial class IperlHeadTestCtrl : UserControl
{
IPerlCfg config;
IPerlReader _iPerlReader;
Thread optoThread;
private bool stopWorkerThread;
public event EventHandler<OptoReceivedEventArgs> OptoReceivedHandler;
public IperlHeadTestCtrl(IPerlCfg config)
{
this.config = config;
InitializeComponent();
if (config == null) return;
//TODO fix possibility set test method in config
//iPerlCommunicationForm.cfg = new TestMethodCfg(null); // default values for iPerlCommunication
foreach(var head in ProcessData.IperlHeadsUni)
{
if (head != null && head.Name == config.Name) { _iPerlReader = head; }
}
rfidCommandComboBox.DisplayMember = "Name";
rfidCommandComboBox.ValueMember = "Value";
var items = new[]
{
new {Name = "Read PCB", Value = "ReadPCB" },
new {Name = "Set Test Mode", Value = "SetTestMode" },
new {Name = "Set Active Mode", Value = "SetActiveMode" },
#if DEBUG
new {Name = "Start Read Opto Data", Value = "ReadOptoData" },
new {Name = "Stop Read Opto Data", Value = "StopReadOptoData" },
#endif
new {Name = " ", Value = "" },
new {Name = "Reset NFC Head", Value = "ResetNfcHead" },
new {Name = "Set NFC Head Interface", Value = "SetNfcHead" },
new {Name = "Set RFID Head interface", Value = "SetRfidHead" }
};
/*
// CTRL+ALT+double click - hidden poweruser menu
if (((Keyboard.ModifierKeys & Keys.Control) == Keys.Control) && ((Keyboard.ModifierKeys & Keys.Alt) == Keys.Alt) && Users.CurrentUser.AuthorizedAs == AuthorizedAs.PowerUser)
{
Array.Resize(ref items, items.Length + 1);
items[items.Length - 1] = new { Name = "Kluc", Value = "Kluc" };
}
*/
rfidCommandComboBox.DataSource = items;
stopWorkerThread = false;
OptoReceivedHandler += (EventHandler<OptoReceivedEventArgs>)((sndr, args) =>
{
if (this.InvokeRequired)
this.Invoke((Delegate)new EventHandler<OptoReceivedEventArgs>(this.OnOptoReceived2), sndr, (object)args);
else
this.OnOptoReceived2(sndr, args);
});
}
public void OnOptoReceived2(object sender, OptoReceivedEventArgs args)
{
optoListBox.Items.Insert(0,args.Data);
}
private void CommandTestButtonClick(object sender, MouseEventArgs e)
{
rfidOutputListBox.Items.Clear();
using (Tools.LogChecker logChecker = new Tools.LogChecker("RfidData", log4net.Core.Level.Debug))
{
ListItem rfidListItem = new ListItem();
rfidListItem.Attributes.Add("style", "font-weight:bold");
switch (rfidCommandComboBox.SelectedValue)
{
case "ReadPCB":
rfidListItem.Text = $"PCB: {OpticalHeadTest.ReadRequest_PCB(_iPerlReader)}";
break;
case "SetTestMode":
rfidListItem.Text = OpticalHeadTest.SetTestMode(_iPerlReader);
optoListBox.Items.Clear();
stopWorkerThread = false;
optoThread = new Thread(OptoWorker);
if (!optoThread.IsAlive)
{
_iPerlReader.StartDataStreamProcessing(); // open opto port
optoThread.Start();
}
break;
case "SetActiveMode":
rfidListItem.Text = OpticalHeadTest.SetActiveMode(_iPerlReader);
stopWorkerThread = true;
_iPerlReader.StopDataStreamProcessing(); // close opto port
break;
case "ResetNfcHead":
_iPerlReader.ResetNfcInterface();
break;
case "SetNfcHead":
_iPerlReader.SetNfcInterface();
break;
case "SetRfidHead":
_iPerlReader.SetRfidInterface();
break;
case "ReadOptoData":
optoListBox.Items.Clear();
stopWorkerThread = false;
optoThread = new Thread(OptoWorker);
if (optoThread.IsAlive)
{
stopWorkerThread = true;
_iPerlReader.StopDataStreamProcessing(); // close opto port
}
if (!optoThread.IsAlive)
{
_iPerlReader.StartDataStreamProcessing(); // open opto port
optoThread.Start();
}
break;
case "StopReadOptoData":
stopWorkerThread = true;
_iPerlReader.StopDataStreamProcessing(); // close opto port
break;
}
rfidOutputListBox.Items.Add(rfidListItem);
rfidOutputListBox.Items.AddRange(logChecker.Messages.ToArray());
}
}
private void OptoWorker()
{
while (!this.stopWorkerThread)
{
Thread.Sleep(250);
if (this.stopWorkerThread)
break;
try
{
string buffer = _iPerlReader.ReadOptoData();
if (string.IsNullOrEmpty(buffer))
{
this.OnOptoReceived((object)this, new OptoReceivedEventArgs("."));
}
else
OnOptoReceived((object)this, new OptoReceivedEventArgs(buffer));
}
catch (Exception ex)
{
this.OnOptoReceived((object)this, new OptoReceivedEventArgs(ex.Message));
}
}
}
public void OnOptoReceived(object sender, OptoReceivedEventArgs args)
{
if (this.OptoReceivedHandler == null)
return;
try
{
this.OptoReceivedHandler(sender, args);
}
catch (Exception ex)
{
}
}
private void UserControl_Load(object sender, EventArgs e)
{
this.ParentForm.FormClosing += new FormClosingEventHandler(ParentForm_FormClosing);
}
void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
{
//OnHandleDestroyed(new EventArgs());
stopWorkerThread = true;
if (optoThread != null)
{
optoThread.Abort();
}
}
}
}
@@ -1,120 +0,0 @@
<?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>
@@ -1,184 +0,0 @@
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using Common;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
{
public class ProcParams : ProcedureParamsBase, IParamsProvider, IProcedureParams
{
public static XmlSerializer Serializer = XmlSerializer.FromTypes(new[] { typeof(ProcParams) })[0];
public override XmlSerializer GetSerializer() { return Serializer; }
public int WMType_ID;
public MeterType MeterType;
public float CalibTarget; /// Target error after calibration in [%]
public int FactorLimitLo; /// Lower limit for the calibration factor
public int FactorLimitHi; /// Upper limit for the calibration factor
public Counting Counting; /// Initial iPerl counting (Artbitrary, Positive or Negative)
public override void InitializeAll()
{
MeterType = MeterType.AutoDetect;
CalibTarget = 0;
FactorLimitLo = 1000;
FactorLimitHi = 8000;
Counting = Counting.Arbitrary;
}
string[] paramNames = new string[]
{
"iPerl type",
"Calib. target [%]",
"Calib. factor Lo",
"Calib. factor Hi",
"Counting",
};
public override string ParamName(int i) { return paramNames[i]; }
public override int ParamsCount() { return paramNames.Length; }
public override ICollection<string> ParamValues(int i)
{
if (i == 0)
{
var retVal = new List<string>();
for (MeterType mt = 0; mt < MeterType.Count; mt++) retVal.Add(mt.ToString());
return retVal;
}
else if (i == 5)
{
var retVal = new List<string>();
for (Counting c = 0; c < Counting.Count; c++) retVal.Add(c.ToString());
return retVal;
}
return null;
}
public override string ToString(int i)
{
switch (i)
{
case 0: return MeterType.ToString();
case 1: return CalibTarget.ToString();
case 2: return FactorLimitLo.ToString();
case 3: return FactorLimitHi.ToString();
case 4: return Counting.ToString();
default: return string.Empty;
}
}
//implement IParamsProvider
public bool ValidateParam(int i, string strValue, out string message)
{
message = string.Empty;
int iDummy;
float fDummy;
switch (i)
{
case 0:
for (MeterType mt = 0; mt < MeterType.Count; mt++) if (mt.ToString().Equals(strValue)) return true;
break;
case 1:
if (Utils.TryParseSFloat(strValue, out fDummy) && fDummy >= -10.0f && fDummy <= 10.0f) return true;
break;
case 2:
case 3:
if (int.TryParse(strValue, out iDummy) && iDummy >= 1000 && iDummy <= 8000) return true;
break;
case 4:
for (Counting c = 0; c < Counting.Count; c++) if (c.ToString().Equals(strValue)) return true;
break;
default:
message = "Invalid index";
return false;
}
message = ParamName(i) + " is invalid";
return false;
}
public CfgUpdateFlags 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 CfgUpdateFlags.None; }
}
break;
case 1: CalibTarget = Utils.ParseSFloat(strValue); return CfgUpdateFlags.None;
case 2: FactorLimitLo = int.Parse(strValue); return CfgUpdateFlags.None;
case 3: FactorLimitHi = int.Parse(strValue); return CfgUpdateFlags.None;
case 4:
for (Counting c = 0; c < Counting.Count; c++)
{
if (c.ToString().Equals(strValue)) { Counting = c; return CfgUpdateFlags.None; }
}
break;
default: return CfgUpdateFlags.None;
}
return CfgUpdateFlags.None;
}
void CopyContentTo(ProcParams prms)
{
prms.MeterType = this.MeterType;
prms.CalibTarget = this.CalibTarget;
prms.FactorLimitLo = this.FactorLimitLo;
prms.FactorLimitHi = this.FactorLimitHi;
prms.Counting = this.Counting;
}
public IParamsProvider Clone()
{
ProcParams pars = new ProcParams();
CopyContentTo(pars);
return pars;
}
public override void UpdateFromDbEntity(ComponentProcedure dbEntity)
{
if (dbEntity == null) return;
try
{
ProcParams tmp = Serializer.Deserialize(new StringReader(dbEntity.Parameters)) as ProcParams;
procedureParamsEntity = dbEntity;
componentName = dbEntity.CmpntName;
procedure = dbEntity.Procedure;
if (tmp != null) 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;
}
}
}
@@ -1,100 +0,0 @@
///
/// Copyright (c) 2015-2021 Sensus Slovensko a.s.
///
using System.Collections.Generic;
using System.IO.Ports;
using System.Xml.Serialization;
using Common;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Rig.TestMethods.SmartTest;
using TBF.Rig.Uni.SharedDialogs.iPerlCommunication;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
{
public class TestMethodCfg : ComponentCfgBase, IComponentCfg
{
public static XmlSerializer Serializer = XmlSerializer.FromTypes(new[] { typeof(TestMethodCfg) })[0];
public override XmlSerializer GetSerializer() { return Serializer; }
public IComponentCfgCtrl GetControl(IList<Config.Entities.Component> cmpntEntities) { return new TestMethodCfgCtrl(); }
///
/// Serialized parameters
///
public int CommTimeout; /// Communication timeout in ms (500 .. 5000)
public int DelayBetweenRetries; /// Delay between communication retries in ms (0 .. 5000)
public int MaxCommRetries; /// Max. number of retries (1 .. 10)
public int WaitTimeAfterFailure; /// Wait time after communication failure in ms
public int PassThroughWaitTime; /// Pass Through wait time for radio parameters in ms
public int NrThreads; /// Numbwr of parallel threads (1, 2 or 4)
public int IperlCheckErrorsToStop;
///
/// NFC S4.5 Combihead params
///
public int MciTimeoutMs;
public int BaudRate;
public int DataBits;
public Parity ParityBit;
public StopBits StopBits;
public int DfltQ2c_15_rl;
public int DfltQ2c_15_lr;
public int DfltQ2c_20_rl;
public int DfltQ2c_20_lr;
public int DfltQ2c_25_63_rl;
public int DfltQ2c_25_63_lr;
public int DfltQ2c_25_10_rl;
public int DfltQ2c_25_10_lr;
public int DfltQ2c_32_rl;
public int DfltQ2c_32_lr;
public int DfltQ2c_40_rl;
public int DfltQ2c_40_lr;
public bool UseWebService;
public string BaseUrl;
public string RelativeUrl;
/// <summary> Test parameters </summary>
[XmlIgnore]
public iPerlCommunicationParams TestParams;
public override IParamsProvider GetRuntimeTestParamsProvider() { return TestParams; }
public override IParamsProvider CreateTestParamsProvider() { return new iPerlCommunicationParams(true); }
public override IParamsProvider GetUITestParamsProvider(Test test)
{
return (test.Method == Name) ? base.GetUITestParamsProvider(test) : null;
}
/// Private parameterless constructor invoked by all other (public) constructors
TestMethodCfg()
{
Name = "iPerlCommunication";
ParentName = string.Empty;
CommTimeout = 1800; /// ms
MaxCommRetries = 4;
WaitTimeAfterFailure = 2200;
PassThroughWaitTime = 1500;
NrThreads = 2; /// 1, 2 or 4 threads
IperlCheckErrorsToStop = 10;
MciTimeoutMs = 4000; // ms, NFC interface
BaudRate = 57600; // NFC Interface
DataBits = 8; // NFC Interface
ParityBit = Parity.None; // NFC Interface
StopBits = StopBits.Two; // NFC Interface
TestParams = CreateTestParamsProvider() as iPerlCommunicationParams;
}
public TestMethodCfg(IComponentFactory factory)
: this()
{
this.Factory = factory;
}
public string ToString(int i)
{
return string.Format("Name={0}, CommTimeout={1}, MaxRetries={2}, NrThreads={3}", Name, CommTimeout, MaxCommRetries, NrThreads);
}
}
}
@@ -1,242 +0,0 @@
///
/// Copyright (c) 2015-2020 Sensus Metering Systems
///
using System;
using System.IO;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
public class CalibrationStruct
{
public const 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 ((data.Length == 2) && (offset == 2))
{
/// Data containing iPerl calibration factor
Calibration = (UInt16)(data[0] + 256 * data[1]);
return true;
}
else if ((data.Length == Length) && (offset == 0))
{
/// 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 string FWVersionStr()
{
int d1 = (FWVersion >> 8) & 0x000F;
int d2 = (FWVersion >> 12) & 0x000F;
int d3 = (FWVersion >> 4) & 0x000F;
int d4 = FWVersion & 0x000F;
return string.Format("{0}.{1}{2}{3}", d1, d2, d3, d4);
}
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"));
}
public virtual void WriteBinary(BinaryWriter writer)
{
writer.Write(Version);
writer.Write((byte)MeterType);
writer.Write(Calibration);
writer.Write((byte)VolumeUnits);
writer.Write((byte)FlowArrow);
writer.Write(FWVersion);
writer.Write(TargetField[0]);
writer.Write(TargetField[1]);
writer.Write(TargetField[2]);
writer.Write(RecipMeanCurrent);
writer.Write(ThresholdVolume);
writer.Write(ThresholdTime);
writer.Write(FlowActivationThr);
writer.Write(VolumeArrowThr);
writer.Write(CalibrationTime);
writer.Write(SerialNumber);
writer.Write((byte)MeterSealed);
writer.Write(CheckSum);
}
public virtual void ReadBinary(BinaryReader reader)
{
Version = reader.ReadByte();
MeterType = (MeterType)reader.ReadByte();
Calibration = reader.ReadUInt16();
VolumeUnits = (VolumeUnits)reader.ReadByte();
FlowArrow = (FlowArrow)reader.ReadByte();
FWVersion = reader.ReadUInt16();
TargetField[0] = reader.ReadUInt16();
TargetField[1] = reader.ReadUInt16();
TargetField[2] = reader.ReadUInt16();
RecipMeanCurrent = reader.ReadUInt16();
ThresholdVolume = reader.ReadUInt16();
ThresholdTime = reader.ReadUInt16();
FlowActivationThr = reader.ReadUInt16();
VolumeArrowThr = reader.ReadUInt16();
CalibrationTime = reader.ReadUInt32();
SerialNumber = reader.ReadUInt64();
MeterSealed = (MeterSealed)reader.ReadByte();
CheckSum = reader.ReadByte();
}
}
}
@@ -1,258 +0,0 @@
///
/// Copyright (c) 2018-2020 Sensus Slovensko a.s.
///
using System;
using System.IO;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
public class CalibrationStructV4
{
public const int Length = 37;
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 UInt16 CalibrationLNA;
public byte CheckSum;
public CalibrationStructV4()
{
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] = (byte)(CalibrationLNA & 0x00FF);
result[35] = (byte)((CalibrationLNA >> 8) & 0x00FF);
result[36] = CheckSum;
return result;
}
/// <summary>
/// Create a calibration structure from a complete byte array
/// </summary>
/// <param name="data">A complete byte array data</param>
/// <returns>CalibrationStructV4 or null when byte array was not complete</returns>
public static CalibrationStructV4 FromByteArray(byte[] data)
{
if (data.Length != Length) return null;
CalibrationStructV4 result = new CalibrationStructV4();
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.CalibrationLNA = (UInt16)(data[34] + 256 * data[35]);
result.CheckSum = data[36];
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 CalibrationStructV2</param>
/// <returns>true when successful, false when data are not appropriate</returns>
public bool Update(byte[] data, int offset)
{
if ((data.Length == 2) && (offset == 2))
{
/// Data containing iPerl calibration factor
Calibration = (UInt16)(data[0] + 256 * data[1]);
return true;
}
else if ((data.Length == 2) && (offset == 34))
{
/// Data containing iPerl calibration factor
CalibrationLNA = (UInt16)(data[0] + 256 * data[1]);
return true;
}
else if ((data.Length == Length) && (offset == 0))
{
/// 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];
CalibrationLNA = (UInt16)(data[34] + 256 * data[35]);
CheckSum = data[36];
return true;
}
else
return false;
}
public string FWVersionStr()
{
int d1 = (FWVersion >> 8) & 0x000F;
int d2 = (FWVersion >> 12) & 0x000F;
int d3 = (FWVersion >> 4) & 0x000F;
int d4 = FWVersion & 0x000F;
return string.Format("{0}.{1}{2}{3}", d1, d2, d3, d4);
}
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} CalLNA={17} Chksum={18}",
Version,
MeterType,
Calibration,
VolumeUnits,
FlowArrow,
FWVersion,
TargetField[0],
TargetField[1],
TargetField[2],
RecipMeanCurrent,
ThresholdVolume,
ThresholdTime,
FlowActivationThr,
VolumeArrowThr,
CalibrationTime,
SerialNumber,
MeterSealed,
CalibrationLNA,
CheckSum.ToString("X2"));
}
public virtual void WriteBinary(BinaryWriter writer)
{
writer.Write(Version);
writer.Write((byte)MeterType);
writer.Write(Calibration);
writer.Write((byte)VolumeUnits);
writer.Write((byte)FlowArrow);
writer.Write(FWVersion);
writer.Write(TargetField[0]);
writer.Write(TargetField[1]);
writer.Write(TargetField[2]);
writer.Write(RecipMeanCurrent);
writer.Write(ThresholdVolume);
writer.Write(ThresholdTime);
writer.Write(FlowActivationThr);
writer.Write(VolumeArrowThr);
writer.Write(CalibrationTime);
writer.Write(SerialNumber);
writer.Write((byte)MeterSealed);
writer.Write(CalibrationLNA);
writer.Write(CheckSum);
}
public virtual void ReadBinary(BinaryReader reader)
{
Version = reader.ReadByte();
MeterType = (MeterType)reader.ReadByte();
Calibration = reader.ReadUInt16();
VolumeUnits = (VolumeUnits)reader.ReadByte();
FlowArrow = (FlowArrow)reader.ReadByte();
FWVersion = reader.ReadUInt16();
TargetField[0] = reader.ReadUInt16();
TargetField[1] = reader.ReadUInt16();
TargetField[2] = reader.ReadUInt16();
RecipMeanCurrent = reader.ReadUInt16();
ThresholdVolume = reader.ReadUInt16();
ThresholdTime = reader.ReadUInt16();
FlowActivationThr = reader.ReadUInt16();
VolumeArrowThr = reader.ReadUInt16();
CalibrationTime = reader.ReadUInt32();
SerialNumber = reader.ReadUInt64();
MeterSealed = (MeterSealed)reader.ReadByte();
CalibrationLNA = reader.ReadUInt16();
CheckSum = reader.ReadByte();
}
}
}
@@ -1,40 +0,0 @@
///
/// Copyright (c) 2015-2019 Sensus Metering Systems
/// Author: Milan Hanajík
///
using System;
using TBF.Rig.Uni.SharedDialogs.iPerlCommunication;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
public class CommCompletedEventArgs : EventArgs
{
public int ThreadId;
public int WMNr0; /// 0-based water meter position
public IPerlReader Ihead;
public Results.Entities.WaterMeter Wm;
public string CommMessage;
public CommErr CommErr;
public CommCompletedEventArgs(int threadId, int wmNr0, IPerlReader ihead, Results.Entities.WaterMeter wm, string commMessage, CommErr commErr)
{
this.ThreadId = threadId;
this.WMNr0 = wmNr0;
this.Ihead = ihead;
this.Wm = wm;
this.CommMessage = commMessage;
this.CommErr = commErr;
}
public override string ToString()
{
return string.Format("Thread={0} WMNr0={1} IHead={2} WM={3} CommMsg={4} CommErr={5}",
ThreadId,
WMNr0,
(Ihead != null) ? Ihead.Name : "null",
Wm.WMPosition,
(CommMessage != null) ? CommMessage : "null",
CommErr);
}
}
}
@@ -1,266 +0,0 @@
///
/// Copyright (c) 2015-2020 Sensus Metering Systems
///
using System;
using System.IO;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
public class ConfigStruct
{
public const int Length = 32;
public Byte Version; /// 0: 1 byte
public MeterState MeterState; /// 1: 1 byte
public UInt32 TargetTimeVeryLowBatt; /// 2: 4 bytes in seconds
public UInt32 TargetTimeLowBatt; /// 6: 4 bytes, in seconds
public UInt32 TestModeTime; /// 10: 4 bytes, Max. test mode time in seconds
public UInt16 EmptyPipeThreshold; /// 14: 2 bytes
public byte[] PCBNumber; /// 16: 5 bytes
public byte TestModeConfig; /// 21: 1 byte
public UInt32 RadioAddress; /// 22: 4 bytes
public UInt16 TempCalibration; /// 26: 2 bytes
public UInt16 AlarmMask; /// 28: 2 bytes, Default 0xA3F7
public UInt16 ConfigCheckSum; /// 30: 2 bytes
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>
/// Returns PCB number string (12 characters, 12 decimal digits)
/// </summary>
/// <returns>PCB number STRING</returns>
public string GetPcbNrString()
{
return PCBNumber2String(this.PCBNumber);
}
/// <summary>
/// Converts PCBNumber to string (12 characters, 12 decimal digits)
/// </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();
}
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,
GetPcbNrString(),
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,
GetPcbNrString(),
TestModeConfig.ToString("X2"),
RadioAddress,
TempCalibration,
AlarmMask.ToString("X4"),
ConfigCheckSum.ToString("X4"));
}
public virtual void WriteBinary(BinaryWriter writer)
{
writer.Write(Version);
writer.Write((byte)MeterState);
writer.Write(TargetTimeVeryLowBatt);
writer.Write(TargetTimeLowBatt);
writer.Write(TestModeTime);
writer.Write(EmptyPipeThreshold);
writer.Write(PCBNumber[0]);
writer.Write(PCBNumber[1]);
writer.Write(PCBNumber[2]);
writer.Write(PCBNumber[3]);
writer.Write(PCBNumber[4]);
writer.Write(TestModeConfig);
writer.Write(RadioAddress);
writer.Write(TempCalibration);
writer.Write(AlarmMask);
writer.Write(ConfigCheckSum);
}
public virtual void ReadBinary(BinaryReader reader)
{
Version = reader.ReadByte();
MeterState = (MeterState)reader.ReadByte();
TargetTimeVeryLowBatt = reader.ReadUInt32();
TargetTimeLowBatt = reader.ReadUInt32();
TestModeTime = reader.ReadUInt32();
EmptyPipeThreshold = reader.ReadUInt16();
PCBNumber[0] = reader.ReadByte();
PCBNumber[1] = reader.ReadByte();
PCBNumber[2] = reader.ReadByte();
PCBNumber[3] = reader.ReadByte();
PCBNumber[4] = reader.ReadByte();
TestModeConfig = reader.ReadByte();
RadioAddress = reader.ReadUInt32();
TempCalibration = reader.ReadUInt16();
AlarmMask = reader.ReadUInt16();
ConfigCheckSum = reader.ReadUInt16();
}
}
}
@@ -1,113 +0,0 @@
///
/// Copyright (c) 2015-2021 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
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, /// DN25 Q3 = 6.3 m3/h
DN25_Q3_10 = 4, /// DN25 Q3 = 10 m3/h
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 Command : byte
{
SetActiveMode = 6,
SetTestMode = 7,
}
public enum FlowState : byte
{
No = 0,
Reverse = 1,
Forward = 2,
EmptyPipe = 3,
Count /// Number of flow states
}
public enum DataStreamState
{
Flush = 0,
ProcessAndSave,
}
public enum CommunicationInterface
{
RFID,
NFC
}
}
@@ -1,316 +0,0 @@
using log4net;
using Sensus.iPerl.NfcHandler;
using Sensus.iPerl.RfidCom.Exceptions;
using System;
using System.Globalization;
using System.Text;
using System.Threading;
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
using static Sensus.iPerl.NfcHandler.MCI_Protocol;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
internal class NfcServices
{
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
internal static int ReadRequest(TestMethodCfg cfg, IPerlReader iperlHead, MCI_Protocol.StructName structName, int offset, int length, out byte[] buffer)
{
for (int i = 0; i < cfg.MaxCommRetries; i++)
{
NfcDataHandler _nfcDataHandler = new NfcDataHandler();
MessageEventHandlers(_nfcDataHandler);
CR95HF_MessageEventHandlers(_nfcDataHandler._CR95HF_Reader);
ST25DV_MessageEventHandlers(_nfcDataHandler._ST25DV_Device);
MCI_MessageEventHandlers(_nfcDataHandler._MCI_Protocol);
NFCHeadConfig_MessageEventHandlers(_nfcDataHandler._NFCHead_Config);
try
{
rfidDataLogger.Info($"NFC COM{iperlHead.RfidComPortNr} ReadRequest : {structName}, {offset}, {length}");
OpenConnection(_nfcDataHandler, cfg, iperlHead);
buffer = MciRead(_nfcDataHandler, cfg, structName, (ushort)offset, length);
_nfcDataHandler.RFProtocolOFF(); // turn off rf antenna due to possible interference
CloseComPort(_nfcDataHandler);
rfidDataLogger.Info($"NFC COM{iperlHead.RfidComPortNr} ReadRequest : {structName}, {offset}, {length} ; Response= {ByteArrayToHexString(buffer)} ; Error: {_nfcDataHandler.LastErrorMessage}");
if (_nfcDataHandler.LastErrorCode != 0)
{
throw new RfidValidationException(_nfcDataHandler.LastErrorMessage);
}
return Convert.ToInt32(_nfcDataHandler.LastErrorCode); //return 0;
}
catch (RfidValidationException)
{
Thread.Sleep(cfg.WaitTimeAfterFailure);
}
catch (Exception ex)
{
rfidDataLogger.Error($"NFC COM{iperlHead.RfidComPortNr} ReadRequest Error: {ex.Message}");
buffer = new byte[length];
return 3;
}
}
buffer = new byte[length];
return 3;
}
internal static int WriteRequest(TestMethodCfg cfg, IPerlReader iperlHead, MCI_Protocol.StructName structName, int offset, int length, byte[] buffer)
{
NfcDataHandler _nfcDataHandler = new NfcDataHandler();
MessageEventHandlers(_nfcDataHandler);
CR95HF_MessageEventHandlers(_nfcDataHandler._CR95HF_Reader);
ST25DV_MessageEventHandlers(_nfcDataHandler._ST25DV_Device);
MCI_MessageEventHandlers(_nfcDataHandler._MCI_Protocol);
NFCHeadConfig_MessageEventHandlers(_nfcDataHandler._NFCHead_Config);
try
{
rfidDataLogger.Info($"NFC COM{iperlHead.RfidComPortNr} WriteRequest : {structName}, {offset}, {length}, {ByteArrayToHexString(buffer)}");
OpenConnection(_nfcDataHandler, cfg, iperlHead);
MciWrite(_nfcDataHandler, cfg, structName, (ushort)offset, length, buffer);
_nfcDataHandler.RFProtocolOFF(); // turn off rf antenna due to possible interference
CloseComPort(_nfcDataHandler);
return 0;
}
catch (Exception ex)
{
rfidDataLogger.Error($"NFC COM{iperlHead.RfidComPortNr} WriteRequest Error: {ex.Message}");
return 3;
}
}
private static void OpenConnection(NfcDataHandler nfcDataHandler, TestMethodCfg cfg, IPerlReader iperlHead)
{
string comPort = $"COM{iperlHead.RfidComPortNr}";
int retryCount = 0 ;
Open:
nfcDataHandler.Close();
Thread.Sleep(100);
if (nfcDataHandler.OpenConnection(comPort, cfg.BaudRate, cfg.DataBits, cfg.ParityBit, cfg.StopBits))
{
rfidDataLogger.Info($"NFC COM{iperlHead.RfidComPortNr} Port Open");
if (nfcDataHandler.ConnectReader())
{
rfidDataLogger.Info($"NFC COM{iperlHead.RfidComPortNr} Reader connected");
if (!nfcDataHandler.ConnectDevice())
{
rfidDataLogger.Error($"NFC COM{iperlHead.RfidComPortNr} Error connect device.");
for (int i = 0; i < cfg.MaxCommRetries; i++)
{
if (nfcDataHandler.Echo()) break;
}
}
}
else
{
retryCount++;
rfidDataLogger.Error($"NFC COM{iperlHead.RfidComPortNr} Error connect reader. Reconnect comport {retryCount}");
if (retryCount < cfg.MaxCommRetries)
{
nfcDataHandler.Close();
iperlHead.ResetNfcInterface(); // reset NFC head via optoport - switch to RFID and back to NFC interface
goto Open;
}
}
}
else
rfidDataLogger.Error($"Open NFC COM{iperlHead.RfidComPortNr} Port Failed");
}
private static void CloseComPort(NfcDataHandler nfcDataHandler)
{
nfcDataHandler.Close();
}
private static byte[] MciRead(NfcDataHandler nfcDataHandler, TestMethodCfg cfg, StructName structName, ushort offset, int length)
{
bool isReadValues = false;
int retryCount = 0;
Read:
try
{
isReadValues = false;
long num1 = (long)length;
int timeoutMs = 4000;
byte payloadlength = Convert.ToByte(num1.ToString("X2"), 16);
if (nfcDataHandler.MCI_Read(structName, offset, payloadlength, timeoutMs))
{
byte[] lastData = nfcDataHandler.LastData;
if ((long)lastData.Length >= num1)
{
rfidDataLogger.Info($"COM: MciRead ({structName},{offset},{length}) = {ByteArrayToHexString(lastData)}");
return lastData;
}
else
rfidDataLogger.Info($"COM: MciRead ({structName},{offset},{length}) = {ByteArrayToHexString(lastData)}");
}
else if (nfcDataHandler.LastErrorCode == (byte)0)
{
rfidDataLogger.Info($"MCI Error: Unidentified");
retryCount++;
if (retryCount < cfg.MaxCommRetries)
goto Read;
}
else
{
rfidDataLogger.Info("Last error message: " + nfcDataHandler.LastErrorMessage);
retryCount++;
if (retryCount < cfg.MaxCommRetries)
goto Read;
}
}
catch (Exception ex)
{
rfidDataLogger.Error("MciRead Last error message: " + ex.Message);
retryCount++;
if (retryCount < cfg.MaxCommRetries)
goto Read;
}
return new byte[length];
}
private static void MciWrite(NfcDataHandler nfcDataHandler, TestMethodCfg cfg, MCI_Protocol.StructName structName, ushort offset, int length, byte[] payload)
{
int retryCount = 0;
Write:
try
{
long num1 = (long)length;
int timeoutMs = 4000;
byte payloadlength = Convert.ToByte(num1);
if ((int)payloadlength != payload.Length)
rfidDataLogger.Error("Insufficient Payload -- Payload lenth : " + (object)payload.Length);
else if (nfcDataHandler.MCI_Write(structName, offset, payloadlength, payload, timeoutMs))
{
// OK
}
else if (nfcDataHandler.LastErrorCode > (byte)0)
{
rfidDataLogger.Error("Last error message: " + nfcDataHandler.LastErrorMessage);
//int num2 = (int)MessageBox.Show(this._nfcDataHandler.LastErrorMessage);
}
}
catch (Exception ex)
{
rfidDataLogger.Error("MciWrite error message: " + ex.Message);
retryCount++;
if (retryCount < cfg.MaxCommRetries)
goto Write;
}
}
private static void MciWriteCommand(NfcDataHandler nfcDataHandler, byte commandcode)
{
try
{
ushort offset = 0;
int timeoutMs = 4000;
byte payloadlength = 1;
byte[] payload = new byte[1] { commandcode };
if (nfcDataHandler.MCI_Write(MCI_Protocol.StructName.Command, offset, payloadlength, payload, timeoutMs) || nfcDataHandler.LastErrorCode <= (byte)0)
return;
rfidDataLogger.Error("MciWriteCommand Last error message: " + nfcDataHandler.LastErrorMessage);
}
catch (Exception ex)
{
rfidDataLogger.Error("MciWriteCommand Last error message: " + ex.Message);
}
}
public static string ByteArrayToHexString(byte[] data)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (byte num in data)
stringBuilder.Append(num.ToString("X2"));
return stringBuilder.ToString();
}
private static byte[] BuildPayLoad(string strPayLoad, int length)
{
byte[] collection;
if (strPayLoad.Split(':').Length > 1)
{
uint timestamp = ConvertDateTimeToTimestamp(Convert.ToDateTime(DateTime.ParseExact(strPayLoad, "HH:mm:ss dd/MM/yyyy", (IFormatProvider)CultureInfo.InvariantCulture)));
byte[] bytes = BitConverter.GetBytes(timestamp);
return bytes;
}
else if (strPayLoad.Split(',').Length > 1)
{
string[] strArray = strPayLoad.Split(',');
collection = new byte[strArray.Length];
for (int index3 = 0; index3 < strArray.Length; ++index3)
collection[index3] = Convert.ToByte(strArray[index3], 16);
return collection;
}
else
{
//int num = strPayLoad.Split(',').Length;
collection = HexStringToByteArray(strPayLoad.Substring(strPayLoad.Length - length * 2).ToUpper());
Array.Reverse((Array)collection);
return collection;
}
}
public static byte[] HexStringToByteArray(string hexString)
{
int length = hexString.Length;
byte[] byteArray = new byte[length / 2];
for (int startIndex = 0; startIndex < length; startIndex += 2)
byteArray[startIndex / 2] = Convert.ToByte(hexString.Substring(startIndex, 2), 16);
return byteArray;
}
private static uint ConvertDateTimeToTimestamp(DateTime datetime)
{
TimeSpan utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
return (uint)((datetime - new DateTime(2000, 1, 1, 0, 0, 0).ToLocalTime()).TotalSeconds + utcOffset.TotalSeconds);
}
#region EventHandlers
public static void MCI_MessageEventHandlers(MCI_Protocol e)
{
DelNfc_MCI_MessageHandler mciMessageHandler = new DelNfc_MCI_MessageHandler(OnHandler);
e.MessageEvent += mciMessageHandler;
}
public static void ST25DV_MessageEventHandlers(ST25DV_Device e)
{
DelNfc_ST25DV_MessageHandler dvMessageHandler = new DelNfc_ST25DV_MessageHandler(OnHandler);
e.MessageEvent += dvMessageHandler;
}
public static void CR95HF_MessageEventHandlers(CR95HF_Reader e)
{
DelNfc_CR95HF_MessageHandler hfMessageHandler = new DelNfc_CR95HF_MessageHandler(OnHandler);
e.MessageEvent += hfMessageHandler;
}
public static void NFCHeadConfig_MessageEventHandlers(NFCHeadConfig e)
{
DelNfc_NFCHeadConfig_MessageHandler configMessageHandler = new DelNfc_NFCHeadConfig_MessageHandler(OnHandler);
e.MessageEvent += configMessageHandler;
}
public static void MessageEventHandlers(NfcDataHandler e)
{
DelNfcMessageHandler nfcMessageHandler = new DelNfcMessageHandler(OnHandler);
e.MessageEvent += nfcMessageHandler;
}
public static void OnHandler(object sender, NfcMessageEventArgs e)
{
if (e.Message == null)
return;
string message = e.Message.Replace("\n", " ").Replace("\r", "");
rfidDataLogger.Debug(message);
}
#endregion
}
}
@@ -1,20 +0,0 @@
///
/// Copyright (c) 2015-2017 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
public class OptoReceivedEventArgs : EventArgs
{
public string Data;
public OptoReceivedEventArgs(string data)
{
this.Data = data;
}
}
}
@@ -1,126 +0,0 @@
using Sensus.iPerl.RfidCom.Exceptions;
using Sensus.iPerl.RfidCom.Helper;
using Sensus.iPerl.RfidCom;
using System;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using TBF.Rig.Uni.SharedDialogs.iPerlCommunication;
using static TBF.Rig.Uni.SharedDialogs.iPerlCommunication.iPerlCommunicationForm;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
internal class RfidServices
{
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
private static readonly ILog log = LogManager.GetLogger(typeof(iPerlCommunicationForm));
internal static int ReadRequest(TestMethodCfg cfg, IPerlReader iperlHead, MessageID messageID, int offset, int length, out byte[] buffer)
{
for (int i = 0; i < cfg.MaxCommRetries; i++)
{
rfidDataLogger.Error($"{iperlHead.CommInterface} Start {i} reading: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},{offset}, {length}... timeout {cfg.CommTimeout})");
using (RfidLogic writer = new RfidLogic($"COM{iperlHead.RfidComPortNr}"))
{
try
{
byte[] response = writer.ReadRequest((byte)messageID, offset, length, cfg.CommTimeout);
string hexString = RfidHelper.ConvertByteArrayToHexString(response);
string swapHexString = RfidHelper.SwapHexcode(hexString);
string decString = RfidHelper.HexLiteral2Unsigned(RfidHelper.SwapHexcode(hexString)).ToString();
if (length > 10)
{
//if the result only contains "00"s we are working on the wrong COM port
// or the module just isn't connected
if (Regex.IsMatch(hexString, @"^(00)\1+$"))
{
rfidDataLogger.Error($"COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...) <- Error: No RFID signal.");
throw new RfidValidationException("Error_Rfid_NoSignal");
}
//if the result only contains "03"s the meter did not answer.
// Might be due to the module being positioned incorrectly.
if (Regex.IsMatch(hexString, @"^(03)\1+$"))
{
rfidDataLogger.Error($"COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...) <- Error: No meter signal.");
throw new RfidValidationException("Error_Rfid_NoAnswerFromMeter");
}
}
writer.ClosePort();
buffer = response;
rfidDataLogger.Info($"{iperlHead.Name} ({iperlHead.SerialNr}): ReadRequestPort(COM{iperlHead.RfidComPortNr},...) returned HEX: {hexString}; SwapHexCodeToDecimal: {decString}");
return 0;
}
catch (RfidDataNotAvailableException)
{
if (/*RfidHelper.IsPassThrough(messageID)*/ messageID == MessageID.ASICRegisterReadTest || messageID == MessageID.RadioPassthrough)
{
rfidDataLogger.Info($"COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...) {(i > 0 ? "<- Error: Invalid Pass-Through data." : "<- Info: Wait for Pass-Through data.")}");
Thread.Sleep(cfg.PassThroughWaitTime);
}
else
{
Thread.Sleep(cfg.WaitTimeAfterFailure);
}
}
catch (RfidValidationException)
{
Thread.Sleep(cfg.WaitTimeAfterFailure);
}
catch (Exception ex)
{
rfidDataLogger.Error($"COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...) {ex.Message}");
Thread.Sleep(cfg.WaitTimeAfterFailure);
}
}
}
rfidDataLogger.Error($"{iperlHead.CommInterface} reading failed after {cfg.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...)");
log.Error($"{iperlHead.CommInterface} reading failed after {cfg.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: ReadRequestPort ({messageID},...)");
buffer = new byte[length];
return 3;
}
internal static int WriteRequest(TestMethodCfg cfg, IPerlReader iperlHead, MessageID messageID, int offset, int length, byte[] buffer)
{
RfidLogic writer = new RfidLogic($"COM{iperlHead.RfidComPortNr}");
string payload = RfidHelper.ConvertByteArrayToHexString(buffer);
for (var i = 0; i < cfg.MaxCommRetries; i++)
{
rfidDataLogger.Error($"{iperlHead.CommInterface} Start {i} writting: COM{iperlHead.RfidComPortNr}: WriteRequest ({messageID},{offset}, {length}, {payload}... timeout {cfg.CommTimeout})");
try
{
if (writer.ClosePort()) writer.OpenPort();
writer.WriteRequest((byte)messageID, offset, length, buffer, cfg.CommTimeout, false);
writer.ClosePort();
rfidDataLogger.InfoFormat($"{iperlHead.Name}({iperlHead.SerialNr},COM{iperlHead.RfidComPortNr}): WriteRequestPort({messageID}, {offset}, {length}, {payload})");
return 0;
}
catch (Exception ex)
{
if (messageID == MessageID.RadioPassthrough || messageID == MessageID.ASICRegisterReadTest)
{
Thread.Sleep(1500);
}
else
{
rfidDataLogger.Error($"COM{iperlHead.RfidComPortNr}: Error: {ex.Message}");
Thread.Sleep(cfg.WaitTimeAfterFailure);
if (i > 1)
{
rfidDataLogger.Error($"COM{iperlHead.RfidComPortNr}: Reopen the com port.");
writer.ClosePort();
}
}
}
}
writer.ClosePort();
rfidDataLogger.Error($"RFID writing failed after {cfg.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: WriteRequestPort ({messageID},...) {System.Text.Encoding.UTF8.GetString(buffer)}");
log.Error($"RFID writing failed after {cfg.MaxCommRetries} retries: COM{iperlHead.RfidComPortNr}: WriteRequestPort ({messageID},...) {System.Text.Encoding.UTF8.GetString(buffer)}");
return 2;
}
}
}
@@ -1,62 +0,0 @@
using System;
using System.Linq;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication
{
internal class SimulationServices
{
const int Q2CorrFactorsAddr = Uni.SharedDialogs.iPerlCommunication.iPerlCommunicationConstants.Q2CorrFactorsAddr;
internal static int ReadRequest(IPerlReader iperlHead, MessageID messageID, int offset, int length, out byte[] buffer)
{
byte[] configurationBuffer = new byte[ConfigStruct.Length] { 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 160, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] calibrationBuffer = new byte[CalibrationStructV4.Length] { 3, 0, 150, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 150, 10 };
buffer = new byte[length];
if (messageID == MessageID.Configuration)
{
Array.Copy(GetPCB(iperlHead), 0, configurationBuffer, 16, 5); // set PCB Number according to iPerlHead configuration
Array.Copy(configurationBuffer,offset,buffer,0,length);
}
else if (messageID == MessageID.Calibration)
{
Array.Copy(calibrationBuffer, offset, buffer, 0, length);
}
else if ((messageID == MessageID.MetrologyMemory) && (offset == Q2CorrFactorsAddr) && (length == 2))
{
buffer = new byte[2] { 0, 0 };
}
else
{
buffer = new byte[length];
}
return iperlHead.Name.Equals("iPerl13") ? 2 : 0; /// Simulates an error on position 13
}
internal static int WriteRequest(TestMethodCfg cfg, IPerlReader iperlHead, MessageID messageID, int offset,
int length, byte[] buffer)
{
return 0;
}
private static Array GetPCB(IPerlReader iperlHead)
{
string pcbStr = iperlHead.RfidComPortNr.ToString().PadRight(10,'0') + iperlHead.Position.ToString("D2");
long decVal = Convert.ToInt64(pcbStr);
string nHexStr = decVal.ToString("X4");
string hexStr = "";
for (int a = nHexStr.Length; a >= 1; a = a - 2)
{
hexStr = hexStr + nHexStr.Substring(a - 2, 2);
}
return Enumerable.Range(0, hexStr.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hexStr.Substring(x, 2), 16))
.ToArray();
}
}
}
@@ -1,129 +0,0 @@
using Config.Resources;
using log4net;
using Sensus.iPerl.RfidCom.Helper;
using System;
using TBF.Rig.Uni.SharedDialogs.iPerlCommunication;
using static Sensus.iPerl.NfcHandler.MCI_Protocol;
using TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication;
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.test
{
internal class OpticalHeadTest
{
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
internal static string OpenSealing(IPerlReader iHead)
{
if (RfidCommands.OpenSealing($"COM{iHead.RfidComPortNr}")) return "OK";
return "Error Open Sealing";
}
internal static string ReadRequest_PCB(IPerlReader iHead)
{
try
{
byte[] pcb = null;
int readRetVal = iPerlCommunicationForm.ReadRequestPort(iHead, MessageID.Configuration, Sensus.iPerl.NfcHandler.MCI_Protocol.StructName.Configuration, 16, 5, out pcb);
if (readRetVal == 0)
{
return RfidHelper.HexLiteral2Unsigned(RfidHelper.SwapHexcode(BitConverter.ToString(pcb).Replace("-", string.Empty))).ToString();
}
rfidDataLogger.Error($"COM{iHead.RfidComPortNr}: ReadRequest_PCB ({MessageID.Configuration},16,5...) <- Error: {readRetVal}");
return "Error";
}
catch (Exception ex)
{
return (ex.Message.ToString());
}
}
internal static string SetActiveMode(IPerlReader iHead)
{
byte[] cmd = new byte[1] { (byte)Command.SetActiveMode };
if (0 == iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.Command, StructName.Command, 0, 1, cmd))
{
return "OK";
}
else
{
return "Error Set Active Mode";
}
}
internal static string SetTestMode(IPerlReader iHead)
{
byte[] cmd = new byte[1] { (byte)Command.SetTestMode };
if (0 == iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.Command, StructName.Command, 0, 1, cmd))
{
return "OK";
}
else
{
return "Error Set Test Mode";
}
}
#if IPERL
internal static string TurnOffRadio(IPerlReader iHead)
{
try
{
int retValue = iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.RadioPassthrough, StructName.RadioParams, 0x1898, 1, new byte[] { (byte)3 }); // WakeUpInterval
return 0 == retValue ? "OK" : "Error";
}
catch (Exception ex)
{
return (ex.Message.ToString());
}
}
internal static string SetProductionMode(IPerlReader iHead)
{
try
{
int retValue = iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, 1, new byte[] { (byte)1 }); // System Status
return 0 == retValue ? "OK" : "Error";
}
catch (Exception ex)
{
return (ex.Message.ToString());
}
}
internal static string WriteRequestPort_u8_Customer_Text(IPerlReader iHead)
{
string custText = "FF0123456789ABCDEF"; // Sample text to test write function
/*try
{
byte[] cmd = RfidHelper.HexStringToByteArray(custText);
if (0 == iPerlCommunicationForm.WriteRequestPort(iHead, MessageID.RadioPassthrough, Sensus.iPerl.NfcHandler.MCI_Protocol.StructName.RadioParams, 0x1899, 9, cmd))
{
RfidCommunicationService rfidCommunicationService = new RfidCommunicationService { ComPort = $"COM{iHead.RfidComPortNr}", WaitTimeAfterFailure = 2200, PassThroughWaitTime = 1500, MaxRetries = 3, TimeOut = 5000 };
//rfidCommunicationService.RfidWrite(Params.u8_Customer_Text, custText);
return rfidCommunicationService.RfidRead<string>(Params.u8_Customer_Text).ToString();
}
}
catch (Exception ex)
{
return (ex.Message.ToString());
}*/
return $"Error COM{iHead.RfidComPortNr}";
}
internal static string SetRfidMode(IPerlReader iHead)
{
iHead.SetRfidInterface();
iHead.SetCommunicationInterface(CommunicationInterface.RFID);
return ($"OK - {Strings.Program_restart_is_required_to_apply_some_settings}");
}
internal static string SetNfcMode(IPerlReader iHead)
{
iHead.SetNfcInterface();
iHead.SetCommunicationInterface(CommunicationInterface.NFC);
return ($"OK - {Strings.Program_restart_is_required_to_apply_some_settings}");
}
#endif /// IPERL
}
}
-28
View File
@@ -110,7 +110,6 @@ namespace TBF.Rig.Sequences
/// iPERL related state variables to be saved after each completed test
///
public static IList<TestMethods.iPerlCommunication.iPerlHead.IperlHead> IperlHeads;
public static IList<RegisterReaders.iPerlReaderUNI.IPerlReader> IperlHeadsUni;
public static bool IsQ2PreCorrectionCalculated;
public static int CalculatedQ2PreCorrectionLR;
public static int CalculatedQ2PreCorrectionRL;
@@ -155,7 +154,6 @@ namespace TBF.Rig.Sequences
{
IperlHeads[i].WriteBinary(writer);
}
writer.Write(IsQ2PreCorrectionCalculated);
writer.Write(CalculatedQ2PreCorrectionLR);
@@ -175,12 +173,6 @@ namespace TBF.Rig.Sequences
for (int i = 0; i < CompleteTestInfos.Length; i++) CompleteTestInfos[i].WriteBinary(writer);
}
#endif
/////// IperlHeadsUni - added for support of smart meters
writer.Write(IperlHeadsUni.Count);
for (int i = 0; i < IperlHeadsUni.Count; i++)
{
IperlHeadsUni[i].WriteBinary(writer);
}
log.WarnFormat("Process data succesfully saved to file {0}", PDataFileName);
}
}
@@ -254,26 +246,6 @@ namespace TBF.Rig.Sequences
CompleteTestInfos[i] = ti;
}
#endif
try
{
int iPerlHeadsCountUni = reader.ReadInt32();
for (int i = 0; i < iPerlHeadsCountUni; i++)
{
if (IperlHeadsUni != null && i < IperlHeadsUni.Count)
{
IperlHeadsUni[i].ReadBinary(reader);
}
else
{
new TestMethods.iPerlCommunication.iPerlHead.IperlHead().ReadBinary(reader);
}
}
}
catch (Exception exc)
{
}
log.WarnFormat("Process data succesfully loaded from file {0}", PDataFileName);
return true;
}
-948
View File
@@ -1,948 +0,0 @@
///
/// Copyright (c) 2015-2023 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using System.Drawing; /// Point definition
using log4net;
using Common;
using Config.Entities;
using RestClient;
using TBF.Rig.Sequences;
using TBF.Resources;
using TBF.UiBridge;
using Results;
using Results.Entities;
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
using TBF.Rig.Uni.SharedDialogs.iPerlCommunication;
namespace TBF.Rig.Sequences
{
public class iPerlCommunicationSeq : SequenceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(iPerlCommunicationSeq));
System.Windows.Forms.Form modelessDlg;
///
delegate void iPerlCommFormDlgt(iPerlCommunicationSeq myRef, SmartComponentBase smartComponentBase, Test test, iPerlCommunicationParams testParams);
///
void OpenIPerlCommForm(iPerlCommunicationSeq myRef, SmartComponentBase method, Test test, iPerlCommunicationParams testParams)
{
myRef.modelessDlg = new iPerlCommunicationForm(method, test, testParams);
myRef.modelessDlg.Show();
}
void CloseIPerlCommForm()
{
UiBridge.Bridge.OnCloseModelessForm(this, null);
modelessDlg = null;
}
/// <summary>
/// Flying start mass collection method sequence
/// </summary>
/// <param name="test">Test entity</param>
/// <returns>
/// Event.Done . . . . . . . OK
/// Event.UiCmdStop . . . . Stopped by the user using the on-screen button STOP
/// Event.OpArgumentError . Target flow is out of range
/// Event.Error . . . . . . Unspecified error
/// </returns>
public IList<Event> Execute(Test test, int repetitionNr, SmartComponentBase method, iPerlCommunicationParams testParams)
{
TestMethodCfg cfg = method.Cfg as TestMethodCfg;
IList<Event> e; /// Events from currently running operations
checkUiOp = new Operations.CheckUIOp(true); /// Runs in more then one state
modelessDlg = null;
processDataLoggingOp = new TBF.Rig.Operations.ProcessDataLoggingOp(processDataLogger, this, false);
string cmd;
if (testParams.Activity.ToLower().Equals(cmd = iPerlCommunicationConstants.GetDefaultQ2CorrectionsStr.ToLower()))
{
TestProgressEventArgs.SetEstimatedTimes(new int[] { 0, 0, 0, 30, 0, 30, 0, 0 });
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.JustStarted));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.FlowSetting));
/// Get 'wmType' from IperlHead procedure parameters
int wmType = 0;
#if IPERL
/*foreach (var wm in ProcessData.BatchRslts.Batch.WaterMeters)
{
if (wm != null && !wm.Disabled && wm.WMTypeId() > 0)
{
wmType = wm.WMTypeId();
break;
}
}*/
#endif
if (cfg.UseWebService)
{
IsQ2PreCorrectionCalculated = GetQ2PreCorrectionsOrBackups(cfg, wmType, out CalculatedQ2PreCorrectionLR, out CalculatedQ2PreCorrectionRL);
}
/// Generate test results
Results.Entities.TestRslt tstRslt = BatchRslts.GetTestRslt(test.Name, 0);
if (tstRslt != null)
{
tstRslt.StartTime = DateTime.Now;
tstRslt.TestDone = true;
foreach (var wm in BatchRslts.Batch.WaterMeters)
{
if (!wm.Disabled)
{
foreach(var mtr in wm.MeterTestRslts)
{
if (mtr.TestRslt == tstRslt)
{
mtr.Passed = !cfg.UseWebService || IsQ2PreCorrectionCalculated;
mtr.TestDone = true;
break;
}
}
}
}
}
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.Completed));
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, ProcessData.BatchRslts.GetTestRslt(test.Name, 0)));
allResults.Info(TestResult2CsvLine(test.Name, 0)); /// Append the results to the CSV-file
return new List<Event> { Event.Done };
}
else if (testParams.Activity.ToLower().Contains(cmd = iPerlCommunicationConstants.Q2correctedFromCmd.ToLower()))
{
TestProgressEventArgs.SetEstimatedTimes(new int[] { 0, 0, 0, 30, 0, 30, 0, 0 });
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.JustStarted));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.FlowSetting));
string[] args = testParams.Activity.Substring(cmd.Length).Split(new char[] { ' ' });
string fromTestName = (args.Length >= 1) ? args[0] : string.Empty;
bool isPlus = (args.Length >= 2) ? args[1].ToLower().Contains("plus") : false;
MakeQ2CorrectedFrom(test.Name, fromTestName, isPlus);
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.Completed));
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, ProcessData.BatchRslts.GetTestRslt(test.Name, 0)));
allResults.Info(TestResult2CsvLine(test.Name, 0)); /// Append the results to the CSV-file
return new List<Event> { Event.Done };
}
else if (testParams.Activity.ToLower().Contains(cmd = iPerlCommunicationConstants.StrictQ2ErrorCheckStr.ToLower()))
{
TestProgressEventArgs.SetEstimatedTimes(new int[] { 0, 0, 0, 30, 0, 30, 0, 0 });
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.JustStarted));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.FlowSetting));
string fromTestName = testParams.Activity.Substring(cmd.Length);
StrictQ2ErrorCheck(test.Name, fromTestName);
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.Completed));
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, ProcessData.BatchRslts.GetTestRslt(test.Name, 0)));
allResults.Info(TestResult2CsvLine(test.Name, 0)); /// Append the results to the CSV-file
return new List<Event> { Event.Done };
}
else if (testParams.Activity.ToLower().Contains(cmd = iPerlCommunicationConstants.Q2correctionCheckCmd.ToLower()))
{
TestProgressEventArgs.SetEstimatedTimes(new int[] { 0, 0, 0, 30, 0, 30, 0, 0 });
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.JustStarted));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.FlowSetting));
string[] testNames = testParams.Activity.Substring(cmd.Length).Split(new char[] { ' ' });
if (testNames.Length >= 2)
{
CheckQ2Correction(test.Name, testNames[0], testNames[1]);
}
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.Completed));
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, ProcessData.BatchRslts.GetTestRslt(test.Name, 0)));
allResults.Info(TestResult2CsvLine(test.Name, 0)); /// Append the results to the CSV-file
return new List<Event> { Event.Done };
}
else if (testParams.Activity.ToLower().Contains(cmd = iPerlCommunicationConstants.IperlCheckCmd.ToLower()))
{
TestProgressEventArgs.SetEstimatedTimes(new int[] { 0, 0, 0, 30, 0, 30, 0, 0 });
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.JustStarted));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.FlowSetting));
string[] args = testParams.Activity.Substring(cmd.Length).Split(new char[] { ' ' });
//int maxTestIndex = (ProcessData.BenchInfo is TBF.Rig.DataContainer.BenchInfo.Component)
// ? (ProcessData.BenchInfo as TBF.Rig.DataContainer.BenchInfo.Component).MaxTestIndex
// : int.MaxValue;
Results.Entities.TestRslt tstRslt = ProcessData.BatchRslts.GetTestRslt(test.Name, 0);
if (tstRslt != null)
{
tstRslt.StartTime = DateTime.Now;
int wrongMetersCount = 0;
string message = string.Empty;
for (int i = 0; i < BatchRslts.WMPositionsCount; i++)
{
Results.Entities.WaterMeter wm = BatchRslts.Batch.WaterMeters[i];
Results.Entities.MeterTestRslt mtr = ProcessData.BatchRslts.GetMeterTestRslt(test.Name, i, CompoundMeterId.Single);
///// Reference to iPerl water meter or null:
//TestMethods.iPerlCommunication.iPerlHead.IperlHead iPerlHead = ((sensPath.RegisterReaders != null) && (i < sensPath.RegisterReaders.Length))
// ? (sensPath.RegisterReaders[i] as TestMethods.iPerlCommunication.iPerlHead.IperlHead)
// : null;
if ((wm != null) && (mtr != null))
{
int errorIndicators = 0;
bool anyErrorOfThisMeter = false;
foreach (var arg in args)
{
#if TURA_SPECIAL
if (arg.ToLower() == "q2factors")
{
if ((wm.ProdQ2CorrRL != wm.Q2CorrRL) || (wm.ProdQ2CorrLR != wm.Q2CorrLR))
{
anyErrorOfThisMeter = true;
message += string.Format("Q2 korekčné faktory vodomera {0} nesedia{1}", wm.WMPosition, Environment.NewLine);
errorIndicators |= (int)ErrorFlagMask.E26; /// Q2 correction factors not valid
}
}
#endif
if (arg.ToLower() == "direction")
{
//if (wm.Pruefindex > maxTestIndex)
//{
// anyErrorOfThisMeter = true;
// message += string.Format("Príliš veľa opakovaní testu vodomera {0}{1}", wm.WMPosition, Environment.NewLine);
// errorIndicators |= (int)ErrorFlagMask.E27; /// Wrong direction (positive/negative counting)
//}
}
if (arg.ToLower() == "prevworkstep")
{
if (wm.LastRecordIsNok)
{
wm.ErrorFlags |= (int)ErrorFlagMask.E28; /// Set E28
}
if ((wm.ErrorFlags & (int)ErrorFlagMask.E28) != 0)
{
anyErrorOfThisMeter = true;
message += string.Format("iPerl{0} : Predchádzajúci krok nebol zaznamenaný{1}", wm.WMPosition, Environment.NewLine);
errorIndicators |= (int)ErrorFlagMask.E28; /// Previous workstep missing or NOK (production tracing)
}
}
}
mtr.TestDone = true;
mtr.ErrorIndicators = errorIndicators;
///
if (anyErrorOfThisMeter)
{
/// This iPerl check did not pass
mtr.Passed = false;
wrongMetersCount++;
}
else
{
/// Check passed OK
mtr.Passed = true;
}
}
}
tstRslt.EndTime = DateTime.Now;
tstRslt.TestDone = true;
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.Completed));
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, tstRslt));
allResults.Info(TestResult2CsvLine(test.Name, 0)); /// Append the results to the CSV-file
if (wrongMetersCount >= cfg.IperlCheckErrorsToStop)
{
State.Create("iPerlCommunicationSeq : Show check result")
.AddOperation(new Operations.LargeMessageBoxOp(message))
.EnterState();
do
{
e = StateMachine.WaitRunDevsRunOps();
}
while (!e.Contains(Event.Continue) && !e.Contains(Event.Abort));
if (e.Contains(Event.Abort))
{
Bridge.OnError(this, string.Format("Niečo nie je v poriadku !"));
return new List<Event> { Event.UiCmdStop };
}
}
}
return new List<Event> { Event.Done };
}
else if (testParams.Activity.ToLower().Contains(cmd = iPerlCommunicationConstants.SimulateCmd))
{
TestProgressEventArgs.SetEstimatedTimes(new int[] { 0, 0, 0, 30, 0, 30, 0, 0 });
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.JustStarted));
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.FlowSetting));
if (testParams.Activity.ToLower().Contains("q3")) MakeSimulated(test, 1, 0, -0.5f);
else if (testParams.Activity.Substring(cmd.Length).ToLower() == "q2") MakeSimulated(test, 1, 0, 0.5f);
else if (testParams.Activity.Substring(cmd.Length).ToLower() == "q1") MakeSimulated(test, 1, 0, -5.1f);
else if (testParams.Activity.Substring(cmd.Length).ToLower() == "compound ok") MakeSimulatedCompound(test, 1, 0, 0.7f, 1.0f);
else if (testParams.Activity.Substring(cmd.Length).ToLower() == "compound nok") MakeSimulatedCompound(test, 1, 0, 4.7f, 0.9f);
else if (testParams.Activity.Substring(cmd.Length).ToLower() == "compound rise") MakeSimulatedCompound(test, 1, 0, 0.7f, 0.0f);
else if (testParams.Activity.Substring(cmd.Length).ToLower() == "compound fall") MakeSimulatedCompound(test, 1, 0, 0.7f, 0.9f);
else if (testParams.Activity.Substring(cmd.Length).ToLower() == "iperls")
{
string[] pcbNrs = new string[] { "831232435539", "831232435562", "831232435587",
"831232432141", "831232432497", "831232763641" };
TestRslt tstRslt = BatchRslts.GetTestRslt(test.Name, test.Part);
if (tstRslt != null)
{
Results.Utils.GetCounterStates(tstRslt, Program.LocalSettings.Counters);
/// Auxiliary results ... not required
/// Main results
tstRslt.MethodClass = TbfComponents.FindComponent(test.Method).ClassName;
tstRslt.TestDone = true;
tstRslt.StartTime = tstRslt.Batch.StartTime;
tstRslt.EndTime = DateTime.Now;
tstRslt.FlowSetTime = 0;
tstRslt.MassOfEvapWater = 0;
tstRslt.TestTime = 1;
for (int i = 0; i < BatchRslts.Batch.WaterMeters.Count; i++)
{
MeterTestRslt meterRslt =
BatchRslts.GetMeterTestRslt(test.Name, i, CompoundMeterId.Single);
if (meterRslt != null)
{
meterRslt.WaterMeter.SerialNr = pcbNrs[i % pcbNrs.Length];
meterRslt.Passed = true;
meterRslt.TestDone = true;
}
//if (iperlHeads[i] != null)
//{
// iperlHeads[i].CommFailed = iperlHeads[i].Disabled = false;
// iperlHeads[i].SerialNr = pcbNrs[i % pcbNrs.Length];
//}
}
}
}
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, Progress.Completed));
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, ProcessData.BatchRslts.GetTestRslt(Common.Utils.GetTestName(test.Name, 1, 1), 0)));
allResults.Info(TestResult2CsvLine(test.Name, 0)); /// Append the results to the CSV-file
//------------------------------------------------
Bridge.OnActivity(this, testParams.Activity);
//------------------------------------------------
State.Create(string.Format("iPerlCommunicationSeq : {0}", testParams.Activity))
.AddOperation(checkUiOp)
.EnterState();
e = StateMachine.WaitRunDevsRunOps();
if (TestAndLogUiCmdStop(test, e))
{
return new List<Event> { Event.UiCmdStop };
}
}
else
{
///
/// Show the modeless dialog with error indication
///
Program.MainWnd.Invoke(new iPerlCommFormDlgt(OpenIPerlCommForm), new object[] { this, method, test, testParams });
//------------------------------------------------
Bridge.OnActivity(this, Strings.iPerl_Communication_in_progress);
//------------------------------------------------
bool stopPressed = false; /// true when STOP button pressed
bool completed = false;
State.Create("iPerlCommunicationSeq : Wait until the entry form is closed")
.AddOperation(checkUiOp)
.EnterState();
do {
e = StateMachine.WaitRunDevsRunOps();
stopPressed = TestAndLogUiCmdStop(test, e);
completed = (modelessDlg is GenericDevices.IHasCompleted)
&& (modelessDlg as GenericDevices.IHasCompleted).Completed;
}
while (!stopPressed && !completed);
if (stopPressed)
{
CloseIPerlCommForm();
return new List<Event> { Event.UiCmdStop };
}
else
{
TBF.UiBridge.Bridge.OnTestProgress(null, new TBF.UiBridge.TestProgressEventArgs(test.Name, Progress.Completed));
}
/// Test 'Quit'
modelessDlg = null; /// Modeless dialog is closed now
}
return new List<Event> { Event.Done };
}
/// <summary>
/// Read default Q2 correction factors from a REST service (= Web service).
/// </summary>
/// <param name="cfg">iPerlCommunication component configuration</param>
/// <param name="wmType">Water meter type (WZ Typ)</param>
/// <param name="q2PreCorrectionLR">Default Q2 correction LR</param>
/// <param name="q2PreCorrectionRL">Default Q2 correction RL</param>
/// <returns>true when successful</returns>
static bool ReadCorrectionsFromWebService(TestMethodCfg cfg, int wmType, out int q2PreCorrectionLR, out int q2PreCorrectionRL)
{
if (wmType == 0)
{
/// No REST service call when wmType == 0, factors are 0
q2PreCorrectionLR = 0;
q2PreCorrectionRL = 0;
return true;
}
try
{
GetQ2PreCorrectionClient client = new GetQ2PreCorrectionClient(cfg.BaseUrl);
client.GetToken("ReadUser", "sensus", "https://deluh1web03.world.fluidtechnology.net/SensusCore/api/v1/Locations/1/Login2").Wait();
Q2PreCorrection response = client.GetQ2Correction(string.Format(cfg.RelativeUrl, wmType)).Result;
if (response != null && response.AreDataCalculated)
{
q2PreCorrectionLR = response.CorrLR;
q2PreCorrectionRL = response.CorrRL;
log.WarnFormat("Q2 corrections from a REST client for WM Type = {0} are: LR = {1}, RL = {2}", wmType, q2PreCorrectionLR, q2PreCorrectionRL);
return true;
}
else
{
log.ErrorFormat("Failed to obtain Q2 corrections from a REST client for WM Type = {0}", wmType);
q2PreCorrectionLR = 0;
q2PreCorrectionRL = 0;
return false;
}
}
catch (Exception exc)
{
log.ErrorFormat("Failed to obtain Q2 corrections from a REST client for WM Type = {0}: {1}", wmType, exc.Message);
q2PreCorrectionLR = 0;
q2PreCorrectionRL = 0;
return false;
}
}
/// <summary>
/// Obtain Q2 correction factors from a REST service or from local settings (stored backup values)
/// </summary>
/// <param name="cfg">iPerlCommunication component configuration</param>
/// <param name="wmType">Water meter type (WZ Typ)</param>
/// <param name="q2PreCorrectionLR">Default Q2 correction LR</param>
/// <param name="q2PreCorrectionRL">Default Q2 correction RL</param>
/// <returns>true when successful</returns>
public static bool GetQ2PreCorrectionsOrBackups(TestMethodCfg cfg, int wmType, out int q2PreCorrectionLR, out int q2PreCorrectionRL)
{
/// Get Q2 pre-correction values from REST service
bool restOK = ReadCorrectionsFromWebService(cfg, wmType, out q2PreCorrectionLR, out q2PreCorrectionRL);
/// Store / load Q2 pre-correction values
Point storedValue;
if (restOK)
{
/// Q2 pre-correction values were successfully obtained from a REST service for the specified wmType
if (!Program.LocalSettings.Q2PreCorrections.TryGetValue(wmType, out storedValue))
{
/// No Q2 pre-correction values in the dictionary for the specified wmType => save them
Program.LocalSettings.Q2PreCorrections.Add(wmType, new Point(q2PreCorrectionLR, q2PreCorrectionRL));
log.WarnFormat("Q2 corrections added to dictionary for WM Type = {0}: LR = {1}, RL = {2}", wmType, q2PreCorrectionLR, q2PreCorrectionRL);
}
else if (storedValue.X != q2PreCorrectionLR || storedValue.Y != q2PreCorrectionRL)
{
/// Different Q2 pre-correction values in the dictionary for the specified wmType => overwrite them with ones from the REST service
Program.LocalSettings.Q2PreCorrections[wmType] = new Point(q2PreCorrectionLR, q2PreCorrectionRL);
log.WarnFormat("Q2 corrections modified in dictionary for WM Type = {0}: LR = {1}, RL = {2}", wmType, q2PreCorrectionLR, q2PreCorrectionRL);
}
else
{
/// Q2 pre-correction values in the dictionary are the same and were not changed
log.WarnFormat("Q2 corrections in dictionary for WM Type = {0} are the same and were not changed", wmType, q2PreCorrectionLR, q2PreCorrectionRL);
}
}
else
{
/// No Q2 pre-correction values from a REST service => read the dictionary
if (Program.LocalSettings.Q2PreCorrections.TryGetValue(wmType, out storedValue))
{
/// Q2 pre-correction values successfully read from the dictionary
q2PreCorrectionLR = storedValue.X;
q2PreCorrectionRL = storedValue.Y;
log.WarnFormat("Q2 corrections loaded from dictionary for WM Type = {0}: LR = {1}, RL = {2}", wmType, q2PreCorrectionLR, q2PreCorrectionRL);
}
else
{
/// Q2 pre-correction values not found in the dictionary => use zeros
q2PreCorrectionLR = 0;
q2PreCorrectionRL = 0;
log.ErrorFormat("Q2 corrections not found in the dictionary for WM Type = {0}, using zeros", wmType, q2PreCorrectionLR, q2PreCorrectionRL);
/// Everything failed => using zero values
return false;
}
}
/// Q2 pre-corections were obtained from REST service or stored backup values were used
return true;
}
/// <summary>
/// Virtually apply Q2 correction to a test used for the correction calculation.
/// </summary>
/// <param name="testName">This test name</param>
/// <param name="oriTestRslt">Name of Q2 test done before Q2 correction (Q2adj)</param>
/// <remarks>Assuming this test does not have multiple parts (part = 0)</remarks>
void MakeQ2CorrectedFrom(string testName, string oriTestName, bool isPlus = false)
{
Results.Entities.TestRslt oriTestRslt = ProcessData.BatchRslts.GetTestRslt(oriTestName, 0);
Results.Entities.TestRslt tstRslt = ProcessData.BatchRslts.GetTestRslt(testName, 0);
if (oriTestRslt == null || tstRslt == null) return;
tstRslt.Components = oriTestRslt.Components;
/// Auxiliary results, as in SequenceBase.UpdateTemoPressDensAmb()
tstRslt.AmbTempMean = oriTestRslt.AmbTempMean;
tstRslt.AmbTempStart = oriTestRslt.AmbTempStart;
tstRslt.AmbTempEnd = oriTestRslt.AmbTempEnd;
tstRslt.AmbTempMin = oriTestRslt.AmbTempMin;
tstRslt.AmbTempMax = oriTestRslt.AmbTempMax;
tstRslt.AmbPressMean = oriTestRslt.AmbPressMean;
tstRslt.AmbPressStart = oriTestRslt.AmbPressStart;
tstRslt.AmbPressEnd = oriTestRslt.AmbPressEnd;
tstRslt.AmbPressMin = oriTestRslt.AmbPressMin;
tstRslt.AmbPressMax = oriTestRslt.AmbPressMax;
tstRslt.AmbHumiMean = oriTestRslt.AmbHumiMean;
tstRslt.AmbHumiStart = oriTestRslt.AmbHumiStart;
tstRslt.AmbHumiEnd = oriTestRslt.AmbHumiEnd;
tstRslt.AmbHumiMin = oriTestRslt.AmbHumiMin;
tstRslt.AmbHumiMax = oriTestRslt.AmbHumiMax;
tstRslt.PressUpMean = oriTestRslt.PressUpMean;
tstRslt.PressUpStart = oriTestRslt.PressUpStart;
tstRslt.PressUpEnd = oriTestRslt.PressUpEnd;
tstRslt.PressUpMin = oriTestRslt.PressUpMin;
tstRslt.PressUpMax = oriTestRslt.PressUpMax;
tstRslt.PressDownMean = oriTestRslt.PressDownMean;
tstRslt.PressDownStart = oriTestRslt.PressDownStart;
tstRslt.PressDownEnd = oriTestRslt.PressDownEnd;
tstRslt.PressDownMin = oriTestRslt.PressDownMin;
tstRslt.PressDownMax = oriTestRslt.PressDownMax;
tstRslt.PressDeltaMean = oriTestRslt.PressDeltaMean;
tstRslt.PressDeltaStart = oriTestRslt.PressDeltaStart;
tstRslt.PressDeltaEnd = oriTestRslt.PressDeltaEnd;
tstRslt.PressDeltaMin = oriTestRslt.PressDeltaMin;
tstRslt.PressDeltaMax = oriTestRslt.PressDeltaMax;
tstRslt.ConductMean = oriTestRslt.ConductMean;
tstRslt.ConductStart = oriTestRslt.ConductStart;
tstRslt.ConductEnd = oriTestRslt.ConductEnd;
tstRslt.ConductMin = oriTestRslt.ConductMin;
tstRslt.ConductMax = oriTestRslt.ConductMax;
tstRslt.TempUpMean = oriTestRslt.TempUpMean;
tstRslt.TempUpStart = oriTestRslt.TempUpStart;
tstRslt.TempUpEnd = oriTestRslt.TempUpEnd;
tstRslt.TempUpMin = oriTestRslt.TempUpMin;
tstRslt.TempUpMax = oriTestRslt.TempUpMax;
tstRslt.TempDownMean = oriTestRslt.TempDownMean;
tstRslt.TempDownStart = oriTestRslt.TempDownStart;
tstRslt.TempDownEnd = oriTestRslt.TempDownEnd;
tstRslt.TempDownMin = oriTestRslt.TempDownMin;
tstRslt.TempDownMax = oriTestRslt.TempDownMax;
tstRslt.TempDivMean = oriTestRslt.TempDivMean;
tstRslt.TempDivStart = oriTestRslt.TempDivStart;
tstRslt.TempDivEnd = oriTestRslt.TempDivEnd;
tstRslt.TempDivMin = oriTestRslt.TempDivMin;
tstRslt.TempDivMax = oriTestRslt.TempDivMax;
tstRslt.DensityIn = oriTestRslt.DensityIn;
tstRslt.DensityLine = oriTestRslt.DensityLine;
tstRslt.DensityDiv = oriTestRslt.DensityDiv;
tstRslt.StartTime = oriTestRslt.StartTime;
tstRslt.EndTime = oriTestRslt.EndTime;
tstRslt.FlowSetTime = oriTestRslt.FlowSetTime;
tstRslt.TestTime = oriTestRslt.TestTime;
tstRslt.PulsesMaster = oriTestRslt.PulsesMaster;
tstRslt.ConstMasterRaw = oriTestRslt.ConstMasterRaw;
tstRslt.ConstMaster = oriTestRslt.ConstMaster;
tstRslt.MassStartRaw = oriTestRslt.MassStartRaw;
tstRslt.MassStart = oriTestRslt.MassStart;
tstRslt.MassEndRaw = oriTestRslt.MassEndRaw;
tstRslt.MassEnd = oriTestRslt.MassEnd;
tstRslt.MassOfEvapWater = oriTestRslt.MassOfEvapWater;
//tstRslt.FlowMass = oriTestRslt.FlowMass;
//tstRslt.FlowVolume = oriTestRslt.FlowVolume;
tstRslt.VolumeCTV = oriTestRslt.VolumeCTV;
tstRslt.VolumeMaster = oriTestRslt.VolumeMaster;
tstRslt.ErrorMaster = oriTestRslt.ErrorMaster;
tstRslt.FlowMean = oriTestRslt.FlowMean;
tstRslt.FlowMin = oriTestRslt.FlowMin;
tstRslt.FlowMax = oriTestRslt.FlowMax;
tstRslt.Custom1 = oriTestRslt.Custom1;
tstRslt.Custom2 = oriTestRslt.Custom2;
tstRslt.Custom3 = oriTestRslt.Custom3;
tstRslt.Custom4 = oriTestRslt.Custom4;
tstRslt.Custom5 = oriTestRslt.Custom5;
tstRslt.Custom6 = oriTestRslt.Custom6;
tstRslt.Custom7 = oriTestRslt.Custom7;
tstRslt.Custom8 = oriTestRslt.Custom8;
for (int i = 0; i < ProcessData.BatchRslts.WMPositionsCount; i++)
{
// Fix for CS7036: Added the missing 'meterId' argument to the GetMeterTestRslt method call.
var q3mtr = ProcessData.BatchRslts.GetMeterTestRslt("Q3", i, CompoundMeterId.SingleOrCompound);
double q3error = (q3mtr != null) ? q3mtr.Error : 0;
Results.Entities.MeterTestRslt oriMeterRslt = ProcessData.BatchRslts.GetMeterTestRslt(oriTestName, i, CompoundMeterId.SingleOrCompound);
Results.Entities.MeterTestRslt meterRslt = ProcessData.BatchRslts.GetMeterTestRslt(testName, i, CompoundMeterId.SingleOrCompound);
/// Reference to iPerl water meter or null:
TestMethods.iPerlCommunication.iPerlHead.IperlHead iPerl = ((sensPath != null) && (sensPath.RegisterReaders != null) && (i < sensPath.RegisterReaders.Length))
? (sensPath.RegisterReaders[i] as TestMethods.iPerlCommunication.iPerlHead.IperlHead)
: null;
if (iPerl != null && meterRslt != null && oriMeterRslt != null)
{
#if ORACLE_DB
meterRslt.ErrorBC = oriMeterRslt.Error;
#endif
meterRslt.PulsesMeter = oriMeterRslt.PulsesMeter;
meterRslt.PulsesMaster = oriMeterRslt.PulsesMaster;
meterRslt.PulsesPerLiter = oriMeterRslt.PulsesPerLiter;
meterRslt.VolumeRef = oriMeterRslt.VolumeRef;
meterRslt.TestTime = oriMeterRslt.TestTime;
if (q3error * oriMeterRslt.Error < 0)
{
/// iPerl with Q2 correction => generate an artificial error equal to +1/10 of the original one (relative to Q2 target error)
meterRslt.Error = 0.1 * oriMeterRslt.Error;
}
else
{
/// iPerl with Q2 correction => generate an artificial error equal to -1/10 of the original one (relative to Q2 target error)
meterRslt.Error = - 0.1 * oriMeterRslt.Error;
}
meterRslt.VolumeMeter = meterRslt.VolumeRef * (100.0 + meterRslt.Error) / 100.0;
double signature = (oriMeterRslt.VolumeEnd > oriMeterRslt.VolumeStart) ? (+1) : (-1);
meterRslt.VolumeStart = oriMeterRslt.VolumeStart;
meterRslt.VolumeEnd = meterRslt.VolumeStart + signature * meterRslt.VolumeMeter;
meterRslt.Passed = (meterRslt.Error >= tstRslt.ErrLimLo() + tstRslt.ErrLimMargin()
&& meterRslt.Error <= tstRslt.ErrLimHi() - tstRslt.ErrLimMargin());
meterRslt.TestDone = true;
tstRslt.TestDone = true;
}
}
}
/// <summary>
/// Evaluate a given Q2 test result agains stricter error limits when Oruefindex == 1.
/// </summary>
/// <param name="testName">This test name</param>
/// <param name="oriTestRslt">Name of Q2 test done before Q2 correction (Q2adj)</param>
/// <remarks>Assuming this test does not have multiple parts (part = 0)</remarks>
void StrictQ2ErrorCheck(string testName, string oriTestName)
{
Results.Entities.TestRslt oriTestRslt = ProcessData.BatchRslts.GetTestRslt(oriTestName, 0);
Results.Entities.TestRslt tstRslt = ProcessData.BatchRslts.GetTestRslt(testName, 0);
if (oriTestRslt == null || tstRslt == null) return;
tstRslt.Components = oriTestRslt.Components;
/// Auxiliary results, as in SequenceBase.UpdateTemoPressDensAmb()
tstRslt.AmbTempMean = oriTestRslt.AmbTempMean;
tstRslt.AmbTempStart = oriTestRslt.AmbTempStart;
tstRslt.AmbTempEnd = oriTestRslt.AmbTempEnd;
tstRslt.AmbTempMin = oriTestRslt.AmbTempMin;
tstRslt.AmbTempMax = oriTestRslt.AmbTempMax;
tstRslt.AmbPressMean = oriTestRslt.AmbPressMean;
tstRslt.AmbPressStart = oriTestRslt.AmbPressStart;
tstRslt.AmbPressEnd = oriTestRslt.AmbPressEnd;
tstRslt.AmbPressMin = oriTestRslt.AmbPressMin;
tstRslt.AmbPressMax = oriTestRslt.AmbPressMax;
tstRslt.AmbHumiMean = oriTestRslt.AmbHumiMean;
tstRslt.AmbHumiStart = oriTestRslt.AmbHumiStart;
tstRslt.AmbHumiEnd = oriTestRslt.AmbHumiEnd;
tstRslt.AmbHumiMin = oriTestRslt.AmbHumiMin;
tstRslt.AmbHumiMax = oriTestRslt.AmbHumiMax;
tstRslt.PressUpMean = oriTestRslt.PressUpMean;
tstRslt.PressUpStart = oriTestRslt.PressUpStart;
tstRslt.PressUpEnd = oriTestRslt.PressUpEnd;
tstRslt.PressUpMin = oriTestRslt.PressUpMin;
tstRslt.PressUpMax = oriTestRslt.PressUpMax;
tstRslt.PressDownMean = oriTestRslt.PressDownMean;
tstRslt.PressDownStart = oriTestRslt.PressDownStart;
tstRslt.PressDownEnd = oriTestRslt.PressDownEnd;
tstRslt.PressDownMin = oriTestRslt.PressDownMin;
tstRslt.PressDownMax = oriTestRslt.PressDownMax;
tstRslt.PressDeltaMean = oriTestRslt.PressDeltaMean;
tstRslt.PressDeltaStart = oriTestRslt.PressDeltaStart;
tstRslt.PressDeltaEnd = oriTestRslt.PressDeltaEnd;
tstRslt.PressDeltaMin = oriTestRslt.PressDeltaMin;
tstRslt.PressDeltaMax = oriTestRslt.PressDeltaMax;
tstRslt.ConductMean = oriTestRslt.ConductMean;
tstRslt.ConductStart = oriTestRslt.ConductStart;
tstRslt.ConductEnd = oriTestRslt.ConductEnd;
tstRslt.ConductMin = oriTestRslt.ConductMin;
tstRslt.ConductMax = oriTestRslt.ConductMax;
tstRslt.TempUpMean = oriTestRslt.TempUpMean;
tstRslt.TempUpStart = oriTestRslt.TempUpStart;
tstRslt.TempUpEnd = oriTestRslt.TempUpEnd;
tstRslt.TempUpMin = oriTestRslt.TempUpMin;
tstRslt.TempUpMax = oriTestRslt.TempUpMax;
tstRslt.TempDownMean = oriTestRslt.TempDownMean;
tstRslt.TempDownStart = oriTestRslt.TempDownStart;
tstRslt.TempDownEnd = oriTestRslt.TempDownEnd;
tstRslt.TempDownMin = oriTestRslt.TempDownMin;
tstRslt.TempDownMax = oriTestRslt.TempDownMax;
tstRslt.TempDivMean = oriTestRslt.TempDivMean;
tstRslt.TempDivStart = oriTestRslt.TempDivStart;
tstRslt.TempDivEnd = oriTestRslt.TempDivEnd;
tstRslt.TempDivMin = oriTestRslt.TempDivMin;
tstRslt.TempDivMax = oriTestRslt.TempDivMax;
tstRslt.DensityIn = oriTestRslt.DensityIn;
tstRslt.DensityLine = oriTestRslt.DensityLine;
tstRslt.DensityDiv = oriTestRslt.DensityDiv;
tstRslt.StartTime = oriTestRslt.StartTime;
tstRslt.EndTime = oriTestRslt.EndTime;
tstRslt.FlowSetTime = oriTestRslt.FlowSetTime;
tstRslt.TestTime = oriTestRslt.TestTime;
tstRslt.PulsesMaster = oriTestRslt.PulsesMaster;
tstRslt.ConstMasterRaw = oriTestRslt.ConstMasterRaw;
tstRslt.ConstMaster = oriTestRslt.ConstMaster;
tstRslt.MassStartRaw = oriTestRslt.MassStartRaw;
tstRslt.MassStart = oriTestRslt.MassStart;
tstRslt.MassEndRaw = oriTestRslt.MassEndRaw;
tstRslt.MassEnd = oriTestRslt.MassEnd;
tstRslt.MassOfEvapWater = oriTestRslt.MassOfEvapWater;
//tstRslt.FlowMass = oriTestRslt.FlowMass;
//tstRslt.FlowVolume = oriTestRslt.FlowVolume;
tstRslt.VolumeCTV = oriTestRslt.VolumeCTV;
tstRslt.VolumeMaster = oriTestRslt.VolumeMaster;
tstRslt.ErrorMaster = oriTestRslt.ErrorMaster;
tstRslt.FlowMean = oriTestRslt.FlowMean;
tstRslt.FlowMin = oriTestRslt.FlowMin;
tstRslt.FlowMax = oriTestRslt.FlowMax;
tstRslt.Custom1 = oriTestRslt.Custom1;
tstRslt.Custom2 = oriTestRslt.Custom2;
tstRslt.Custom3 = oriTestRslt.Custom3;
tstRslt.Custom4 = oriTestRslt.Custom4;
tstRslt.Custom5 = oriTestRslt.Custom5;
tstRslt.Custom6 = oriTestRslt.Custom6;
tstRslt.Custom7 = oriTestRslt.Custom7;
tstRslt.Custom8 = oriTestRslt.Custom8;
for (int i = 0; i < ProcessData.BatchRslts.WMPositionsCount; i++)
{
Results.Entities.MeterTestRslt oriMeterRslt = ProcessData.BatchRslts.GetMeterTestRslt(oriTestName, i, CompoundMeterId.Single);
Results.Entities.MeterTestRslt meterRslt = ProcessData.BatchRslts.GetMeterTestRslt(testName, i, CompoundMeterId.Single);
/// Reference to iPerl water meter or null:
TestMethods.iPerlCommunication.iPerlHead.IperlHead iPerl = ((sensPath != null) && (sensPath.RegisterReaders != null) && (i < sensPath.RegisterReaders.Length))
? (sensPath.RegisterReaders[i] as TestMethods.iPerlCommunication.iPerlHead.IperlHead)
: null;
if (meterRslt != null && oriMeterRslt != null)
{
#if ORACLE_DB
meterRslt.ErrorBC = oriMeterRslt.Error;
#endif
meterRslt.PulsesMeter = oriMeterRslt.PulsesMeter;
meterRslt.PulsesMaster = oriMeterRslt.PulsesMaster;
meterRslt.PulsesPerLiter = oriMeterRslt.PulsesPerLiter;
meterRslt.VolumeRef = oriMeterRslt.VolumeRef;
meterRslt.TestTime = oriMeterRslt.TestTime;
if (iPerl != null && ProcessData.BatchRslts.Batch.WaterMeters[i] != null &&
!ProcessData.BatchRslts.Batch.WaterMeters[i].Disabled)
{
/// Either no iPerl head or no Q2 correction
meterRslt.Error = oriMeterRslt.Error;
meterRslt.VolumeMeter = oriMeterRslt.VolumeMeter;
meterRslt.VolumeStart = oriMeterRslt.VolumeStart;
meterRslt.VolumeEnd = oriMeterRslt.VolumeEnd;
#if ORACLE_DB
if ((ProcessData.BatchRslts.Batch.WaterMeters[i].Pruefindex % 100) == 1)
{
meterRslt.Passed = (oriMeterRslt.Error >= tstRslt.ErrLimLo() + tstRslt.ErrLimMargin()
&& oriMeterRslt.Error <= tstRslt.ErrLimHi() - tstRslt.ErrLimMargin());
}
else
#endif
{
meterRslt.Passed = oriMeterRslt.Passed;
}
meterRslt.TestDone = true;
tstRslt.TestDone = true;
}
}
}
}
/// <summary>
/// Check results of 2 tests: before Q2 correction and after Q2 correction.
/// Evaluate whether Q2 correction works OK.
/// </summary>
/// <param name="testName">This test name</param>
/// <param name="testNameQ2bc">Name of Q2 test done before correction</param>
/// <param name="testNameQ2ac">Name of Q2 test done after correction</param>
/// <remarks>Assuming these tests do not have multiple parts (part = 0)</remarks>
void CheckQ2Correction(string testName, string testNameQ2bc, string testNameQ2ac)
{
Results.Entities.TestRslt tstRslt = ProcessData.BatchRslts.GetTestRslt(testName, 0);
Results.Entities.TestRslt testRsltQ2bc = ProcessData.BatchRslts.GetTestRslt(testNameQ2bc, 0);
Results.Entities.TestRslt testRsltQ2ac = ProcessData.BatchRslts.GetTestRslt(testNameQ2ac, 0);
if ((tstRslt == null) || (testRsltQ2bc == null) || (testRsltQ2ac == null)) return;
tstRslt.Components = testRsltQ2ac.Components;
/// Auxiliary results, as in SequenceBase.UpdateTemoPressDensAmb()
tstRslt.AmbTempMean = testRsltQ2ac.AmbTempMean;
tstRslt.AmbTempStart = testRsltQ2ac.AmbTempStart;
tstRslt.AmbTempEnd = testRsltQ2ac.AmbTempEnd;
tstRslt.AmbTempMin = testRsltQ2ac.AmbTempMin;
tstRslt.AmbTempMax = testRsltQ2ac.AmbTempMax;
tstRslt.AmbPressMean = testRsltQ2ac.AmbPressMean;
tstRslt.AmbPressStart = testRsltQ2ac.AmbPressStart;
tstRslt.AmbPressEnd = testRsltQ2ac.AmbPressEnd;
tstRslt.AmbPressMin = testRsltQ2ac.AmbPressMin;
tstRslt.AmbPressMax = testRsltQ2ac.AmbPressMax;
tstRslt.AmbHumiMean = testRsltQ2ac.AmbHumiMean;
tstRslt.AmbHumiStart = testRsltQ2ac.AmbHumiStart;
tstRslt.AmbHumiEnd = testRsltQ2ac.AmbHumiEnd;
tstRslt.AmbHumiMin = testRsltQ2ac.AmbHumiMin;
tstRslt.AmbHumiMax = testRsltQ2ac.AmbHumiMax;
tstRslt.PressUpMean = testRsltQ2ac.PressUpMean;
tstRslt.PressUpStart = testRsltQ2ac.PressUpStart;
tstRslt.PressUpEnd = testRsltQ2ac.PressUpEnd;
tstRslt.PressUpMin = testRsltQ2ac.PressUpMin;
tstRslt.PressUpMax = testRsltQ2ac.PressUpMax;
tstRslt.PressDownMean = testRsltQ2ac.PressDownMean;
tstRslt.PressDownStart = testRsltQ2ac.PressDownStart;
tstRslt.PressDownEnd = testRsltQ2ac.PressDownEnd;
tstRslt.PressDownMin = testRsltQ2ac.PressDownMin;
tstRslt.PressDownMax = testRsltQ2ac.PressDownMax;
tstRslt.PressDeltaMean = testRsltQ2ac.PressDeltaMean;
tstRslt.PressDeltaStart = testRsltQ2ac.PressDeltaStart;
tstRslt.PressDeltaEnd = testRsltQ2ac.PressDeltaEnd;
tstRslt.PressDeltaMin = testRsltQ2ac.PressDeltaMin;
tstRslt.PressDeltaMax = testRsltQ2ac.PressDeltaMax;
tstRslt.ConductMean = testRsltQ2ac.ConductMean;
tstRslt.ConductStart = testRsltQ2ac.ConductStart;
tstRslt.ConductEnd = testRsltQ2ac.ConductEnd;
tstRslt.ConductMin = testRsltQ2ac.ConductMin;
tstRslt.ConductMax = testRsltQ2ac.ConductMax;
tstRslt.TempUpMean = testRsltQ2ac.TempUpMean;
tstRslt.TempUpStart = testRsltQ2ac.TempUpStart;
tstRslt.TempUpEnd = testRsltQ2ac.TempUpEnd;
tstRslt.TempUpMin = testRsltQ2ac.TempUpMin;
tstRslt.TempUpMax = testRsltQ2ac.TempUpMax;
tstRslt.TempDownMean = testRsltQ2ac.TempDownMean;
tstRslt.TempDownStart = testRsltQ2ac.TempDownStart;
tstRslt.TempDownEnd = testRsltQ2ac.TempDownEnd;
tstRslt.TempDownMin = testRsltQ2ac.TempDownMin;
tstRslt.TempDownMax = testRsltQ2ac.TempDownMax;
tstRslt.TempDivMean = testRsltQ2ac.TempDivMean;
tstRslt.TempDivStart = testRsltQ2ac.TempDivStart;
tstRslt.TempDivEnd = testRsltQ2ac.TempDivEnd;
tstRslt.TempDivMin = testRsltQ2ac.TempDivMin;
tstRslt.TempDivMax = testRsltQ2ac.TempDivMax;
tstRslt.DensityIn = testRsltQ2ac.DensityIn;
tstRslt.DensityLine = testRsltQ2ac.DensityLine;
tstRslt.DensityDiv = testRsltQ2ac.DensityDiv;
tstRslt.StartTime = testRsltQ2ac.StartTime;
tstRslt.EndTime = testRsltQ2ac.EndTime;
tstRslt.FlowSetTime = testRsltQ2ac.FlowSetTime;
tstRslt.TestTime = testRsltQ2ac.TestTime;
tstRslt.PulsesMaster = testRsltQ2ac.PulsesMaster;
tstRslt.ConstMasterRaw = testRsltQ2ac.ConstMasterRaw;
tstRslt.ConstMaster = testRsltQ2ac.ConstMaster;
tstRslt.MassStartRaw = testRsltQ2ac.MassStartRaw;
tstRslt.MassStart = testRsltQ2ac.MassStart;
tstRslt.MassEndRaw = testRsltQ2ac.MassEndRaw;
tstRslt.MassEnd = testRsltQ2ac.MassEnd;
tstRslt.MassOfEvapWater = testRsltQ2ac.MassOfEvapWater;
//tstRslt.FlowMass = testRsltQ2ac.FlowMass;
//tstRslt.FlowVolume = testRsltQ2ac.FlowVolume;
tstRslt.VolumeCTV = testRsltQ2ac.VolumeCTV;
tstRslt.VolumeMaster = testRsltQ2ac.VolumeMaster;
tstRslt.ErrorMaster = testRsltQ2ac.ErrorMaster;
tstRslt.FlowMean = testRsltQ2ac.FlowMean;
tstRslt.FlowMin = testRsltQ2ac.FlowMin;
tstRslt.FlowMax = testRsltQ2ac.FlowMax;
tstRslt.Custom1 = testRsltQ2ac.Custom1;
tstRslt.Custom2 = testRsltQ2ac.Custom2;
tstRslt.Custom3 = testRsltQ2ac.Custom3;
tstRslt.Custom4 = testRsltQ2ac.Custom4;
tstRslt.Custom5 = testRsltQ2ac.Custom5;
tstRslt.Custom6 = testRsltQ2ac.Custom6;
tstRslt.Custom7 = testRsltQ2ac.Custom7;
tstRslt.Custom8 = testRsltQ2ac.Custom8;
for (int i = 0; i < ProcessData.BatchRslts.WMPositionsCount; i++)
{
Results.Entities.MeterTestRslt meterRslt = ProcessData.BatchRslts.GetMeterTestRslt(testName, i, CompoundMeterId.Single);
Results.Entities.MeterTestRslt meterRsltQ2bc = ProcessData.BatchRslts.GetMeterTestRslt(testNameQ2bc, i, CompoundMeterId.Single);
Results.Entities.MeterTestRslt meterRsltQ2ac = ProcessData.BatchRslts.GetMeterTestRslt(testNameQ2ac, i, CompoundMeterId.Single);
if ((meterRslt != null) && (meterRsltQ2bc != null) && (meterRsltQ2ac != null))
{
meterRslt.PulsesMeter = meterRsltQ2ac.PulsesMeter;
meterRslt.PulsesMaster = meterRsltQ2ac.PulsesMaster;
meterRslt.PulsesPerLiter = meterRsltQ2ac.PulsesPerLiter;
meterRslt.VolumeRef = meterRsltQ2ac.VolumeRef;
meterRslt.TestTime = meterRsltQ2ac.TestTime;
meterRslt.VolumeStart = meterRsltQ2ac.VolumeStart;
meterRslt.VolumeEnd = meterRsltQ2ac.VolumeEnd;
meterRslt.VolumeMeter = meterRsltQ2ac.VolumeMeter;
meterRslt.Error = meterRsltQ2ac.Error;
meterRslt.TestDone = meterRsltQ2ac.TestDone;
tstRslt.TestDone = true;
if (((meterRsltQ2bc.Error < -0.51) && (meterRsltQ2ac.Error < meterRsltQ2bc.Error)) ||
((meterRsltQ2bc.Error > +0.51) && (meterRsltQ2ac.Error > meterRsltQ2bc.Error)))
{
meterRslt.Passed = false; /// Q2 correction check failed
}
else
{
meterRslt.Passed = true; /// Q2 correction check passed
}
}
}
}
}
}
-2
View File
@@ -14,7 +14,6 @@ using TBF.Rig.GenericDevices;
using TBF.Rig.Sequences;
using Dirichlet.Numerics;
using TBF.Resources;
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
namespace TBF.Rig
{
@@ -155,7 +154,6 @@ namespace TBF.Rig
TestMethod2Class = new Dictionary<string, string>();
ProcessData.IperlHeads = new List<TestMethods.iPerlCommunication.iPerlHead.IperlHead>();
ProcessData.IperlHeadsUni = new List<IPerlReader>();
SequenceBase.FlowMeters = new List<IFlowMeter>();
SequenceBase.RegVPositions = new List<RegValvePosition>();
SequenceBase.PumpsWithFM = new List<IPumpFM>();
+1 -2
View File
@@ -128,8 +128,7 @@ namespace TBF.Rig
new BuiltIn.PumpTandem.PumpFactory(),
new RegisterReaders.DataStream.MefImport.Factory(), /// 'Interface for data stream stream via MEF'
new RegisterReaders.DataStream.Reader.Factory(), /// 'RegisterReader for data stream stream via MEF'
new RegisterReaders.FrequencyMeterFromUniCB.Factory(), ///
new RegisterReaders.iPerlReaderUNI.Factory(), /// 'RegisterReader for Smart Meters'
new RegisterReaders.FrequencyMeterFromUniCB.Factory(), ///
new RegisterReaders.PulsesFromUniCB.Factory(), /// 'RegisterReader'
new RegisterReaders.StandingStartStop.Factory(), /// 'RegisterReader for standing start/stop'
new TestMethods.iPerlCommunication.iPerlHead.Factory(), /// 'RegisterReader for iPerl'
@@ -607,6 +607,11 @@ namespace TBF.Rig.TestMethods.FlyingStart
meterRslt.VolumeRef = tstRslt.VolumeCTV * meterRslt.TestTime / tstRslt.TestTime;
meterRslt.PulsesMaster = tstRslt.PulsesMaster * meterRslt.TestTime / tstRslt.TestTime;
log.Debug($"TEST TIME meterRslt.TimestampStart:{meterRslt.TimestampStart}, meterRslt.TimestampEnd:{meterRslt.TimestampEnd}, meterRslt.TestTime:{meterRslt.TestTime}");
log.Debug($"TEST VOLUME meterRslt.VolumeStart:{meterRslt.VolumeStart}, meterRslt.VolumeEnd:{meterRslt.VolumeEnd}, meterRslt.VolumeMeter:{meterRslt.VolumeMeter}");
log.Debug($"TEST modified by time: meterRslt.VolumeRef:{meterRslt.VolumeRef}, meterRslt.PulsesMaster:{meterRslt.PulsesMaster}");
if (iPerl != null)
{
if (iPerl.ResultCode != 0 && (meterRslt.WaterMeter.ResultCode & (int)Results.Entities.ResultCode.OptoErrorCodeMask) == 0)
@@ -635,7 +635,18 @@ namespace TBF.Rig.TestMethods.FlyingStartMassCollection
while (!e.Contains(Event.ScaleDone) && !e.Contains(Event.Next));
///
tMass2 = StateMachine.Time;
log.WarnFormat("End mass = {0}kg", EndMass);
try
{
if (EndMass != null)
{
log.WarnFormat("End mass = {0}kg", EndMass.Val);
}
}
catch (Exception ex)
{
log.ErrorFormat("Error while logging end mass: {0}", ex.Message);
}
TestEndTime = DateTime.Now;
if (test.DoDrainingAfter)
@@ -1,32 +0,0 @@
///
/// Copyright (c) 2022 Sensus Slovensko a.s.
///
using TBF.Resources;
using TBF.Rig.Uni.SharedDialogs.iPerlCommunication;
namespace TBF.Rig.TestMethods.SmartTest
{
public class SequenceConditionOp : ISequenceConditionOp, IOperation
{
public SequenceConditionOp(TestMethod testMethodComponent, ConditionID id)
: base(testMethodComponent, id)
{
}
public void Start() { }
public Event Run()
{
bool conditionMet = testMethodComponent.IsMeterCommMilestone((int)id);// IperlCommMilestone[(int)id];
return conditionMet ? Event.ConditionMet : Event.ConditionNotMet;
}
public void Stop() { }
public override string ToString()
{
return GetConditionNameFmt(id);
}
}
}
-181
View File
@@ -1,181 +0,0 @@
///
/// Copyright (c) 2015-2022 Sensus Slovensko a.s.
///
using System;
using System.Collections.Generic;
using log4net;
using Common;
using Config.Entities;
using TBF.Rig.GenericDevices;
using TBF.Rig.Sequences;
using TBF.Rig.Uni.SharedDialogs.iPerlCommunication;
using TBF.UiBridge;
using ConditionID = TBF.Rig.Uni.SharedDialogs.iPerlCommunication.ConditionID;
using iPerlCommunicationSeq = TBF.Rig.Sequences.iPerlCommunicationSeq;
using TestMethodCfg = TBF.Rig.RegisterReaders.iPerlReaderUNI.TestMethodCfg;
namespace TBF.Rig.TestMethods.SmartTest
{
public class TestMethod : SmartComponentBase, ISimultTestMethod, ISequenceCondition, ISessionDataMngmnt, ISmartTestMethod
{
private static readonly ILog log = LogManager.GetLogger(typeof(TestMethod));
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
public override string ToString() { return string.Format("{0}({1})", ClassName, Cfg.ToString(-1)); }
public bool CanTest(MetersKind meters) { return meters == MetersKind.Single; }
public bool DoTransitions() { return false; }
public bool SimultWithPrevious { get { return testMethodCfg.TestParams.SimultWithPrevious; } }
public bool SimultWithNext { get { return testMethodCfg.TestParams.SimultWithNext; } }
#region Configuration Change Handling
public static void OnCfgChange(object sender, CfgChangeArgs args)
{
if (CfgChangeHandler == null) return;
try { CfgChangeHandler(sender, args); }
catch (Exception e) { log.Error("CfgChangeHandler(...) failed", e); }
}
public static event EventHandler<CfgChangeArgs> CfgChangeHandler;
public override void StartChangeHandler()
{
CfgChangeHandler += delegate(object sender, CfgChangeArgs args)
{
TestMethodCfg tmpCfg = args.Cfg as TestMethodCfg;
if (tmpCfg != null && tmpCfg.Name.Equals(Name))
{
if (args.Command == CfgChangeCmd.CfgChange)
{
testMethodCfg.CommTimeout = tmpCfg.CommTimeout;
testMethodCfg.DelayBetweenRetries = tmpCfg.DelayBetweenRetries;
testMethodCfg.MaxCommRetries = tmpCfg.MaxCommRetries;
testMethodCfg.IperlCheckErrorsToStop = tmpCfg.IperlCheckErrorsToStop;
testMethodCfg.UseWebService = tmpCfg.UseWebService;
testMethodCfg.BaseUrl = tmpCfg.BaseUrl;
testMethodCfg.RelativeUrl = tmpCfg.RelativeUrl;
}
}
};
}
public override void MeterCommMilestone(int iItem, bool bValue)
{
IperlCommMilestone[iItem] = bValue;
}
public override bool IsMeterCommMilestone(int iItem)
{
return IperlCommMilestone[iItem];
}
#endregion Configuration Change Handling
readonly TestMethodCfg testMethodCfg;
public bool[] IperlCommMilestone;
IList<IOperation> sequenceConditionOps;
public TestMethod()
{
CreateMilestonesAndConditions();
}
public TestMethod(Generic.IComponentCfg cfg)
: base(cfg)
{
testMethodCfg = cfg as TestMethodCfg;
CreateMilestonesAndConditions();
}
void CreateMilestonesAndConditions()
{
IperlCommMilestone = new bool[(int)ConditionID.Count];
sequenceConditionOps = new List<IOperation>();
for (ConditionID id = ConditionID.A; id < ConditionID.Count; id++)
{
sequenceConditionOps.Add(new SequenceConditionOp(this, id));
}
}
/// IDevice interface - only Initialize() is used
public override void Initialize()
{
if (DebugLevel == DebugMode.Normal)
{
rfidDataLogger.Fatal("------------------------------------------------------------------------");
rfidDataLogger.FatalFormat("Test Bench Framework ver. {0}", Program.Version);
log.FatalFormat("{0} initialized: {1}", Name, this);
}
else
{
log.FatalFormat("{0} simulated: {1}", Name, this);
}
}
public IList<Event> Execute(Test test, int repetNr, bool isLastRepetition)
{
if (DebugLevel == DebugMode.Normal)
{
return (new iPerlCommunicationSeq()).Execute(test, repetNr, this, testMethodCfg.TestParams);
}
else
{
/// DebugLevel == DebugMode.Simulate
(new iPerlCommunicationSeq()).MakeSimulatedTrivial(test, repetNr, test.Part);
Bridge.OnTestProgress(this, new TestProgressEventArgs(test, 1, Progress.Completed));
Bridge.OnTestCompleted(this, new TestCompletedEventArgs(test.Name, ProcessData.BatchRslts.GetTestRslt(Common.Utils.GetTestName(test.Name, 1, 1), 0)));
return new List<Event> { Event.Done };
}
}
public int ConditionsCount { get { return (int)ConditionID.Count; } }
public string ConditionName(int i)
{
return (i >= 0 && i < (int)ConditionID.Count) ? ConditionOp(i).ToString() : string.Empty;
}
public IOperation ConditionOp(int i)
{
return (i >= 0 && i < (int)ConditionID.Count) ? sequenceConditionOps[i] : null;
}
public void StartSession()
{
/// Clear milestones
if (IperlCommMilestone != null)
{
for (int i = 0; i < IperlCommMilestone.Length; i++)
{
IperlCommMilestone[i] = false;
}
}
}
public void SaveMark(object o)
{
/// No marks
}
public void EndSession()
{
/// Nothing at the end of session
}
public bool CheckDeviceCaps(Test test, OutputPath devices, out string message)
{
// Implement the method to satisfy the ITestMethod interface.
// For now, provide a basic implementation.
message = "Device capabilities check not implemented.";
return true;
}
}
}
@@ -1,257 +0,0 @@
///
/// Copyright (c) 2015-2020 Sensus Slovensko a.s.
///
using System;
using System.Windows.Forms;
using Common;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Resources;
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
namespace TBF.Rig.TestMethods.SmartTest
{
public partial class TestMethodCfgCtrl : Configs.ConfigCtrlUtils, IComponentCfgCtrl
{
public bool ShowMore { get { return false; } }
TestMethodCfg config;
public IComponentCfg Config
{
get { return config as IComponentCfg; }
set
{
config = value as TestMethodCfg;
Redraw();
}
}
public TestMethodCfgCtrl()
{
InitializeComponent();
}
private void EntryFormCfgCtrl_Load(object sender, EventArgs e)
{
Redraw();
}
public void Closing()
{
}
void Redraw()
{
if (config == null) return; /// Control was not loaded, settings were not changed
classNameLabel.Text = config.Factory.ClassName;
nameTextBox.Text = config.Name;
commTimeoutTextBox.Text = config.CommTimeout.ToString();
maxCommRetriesTextBox.Text = config.MaxCommRetries.ToString();
delayBetweenRetriesTextBox.Text = config.DelayBetweenRetries.ToString();
nrThreadsTextBox.Text = config.NrThreads.ToString();
iperlCheckErrorsToStopTextBox.Text = config.IperlCheckErrorsToStop.ToString();
textBox15rl.Text = config.DfltQ2c_15_rl.ToString();
textBox15lr.Text = config.DfltQ2c_15_lr.ToString();
textBox20rl.Text = config.DfltQ2c_20_rl.ToString();
textBox20lr.Text = config.DfltQ2c_20_lr.ToString();
textBox25_63rl.Text = config.DfltQ2c_25_63_rl.ToString();
textBox25_63lr.Text = config.DfltQ2c_25_63_lr.ToString();
textBox25_10rl.Text = config.DfltQ2c_25_10_rl.ToString();
textBox25_10lr.Text = config.DfltQ2c_25_10_lr.ToString();
textBox32rl.Text = config.DfltQ2c_32_rl.ToString();
textBox32lr.Text = config.DfltQ2c_32_lr.ToString();
textBox40rl.Text = config.DfltQ2c_40_rl.ToString();
textBox40lr.Text = config.DfltQ2c_40_lr.ToString();
useWebServiceCheckBox.Checked = config.UseWebService;
baseUrlTextBox.Text = config.BaseUrl;
relativeUrlTextBox.Text = config.RelativeUrl;
}
public void Unlock()
{
nameTextBox.Enabled = true;
commTimeoutTextBox.Enabled = true;
maxCommRetriesTextBox.Enabled = true;
delayBetweenRetriesTextBox.Enabled = true;
nrThreadsTextBox.Enabled = true;
iperlCheckErrorsToStopTextBox.Enabled = true;
textBox15rl.Enabled = true;
textBox15lr.Enabled = true;
textBox20rl.Enabled = true;
textBox20lr.Enabled = true;
textBox25_63rl.Enabled = true;
textBox25_63lr.Enabled = true;
textBox25_10rl.Enabled = true;
textBox25_10lr.Enabled = true;
textBox32rl.Enabled = true;
textBox32lr.Enabled = true;
textBox40rl.Enabled = true;
textBox40lr.Enabled = true;
useWebServiceCheckBox.Enabled = true;
ManageCheckGroupBox(useWebServiceCheckBox, useWebServiceGroupBox);
baseUrlTextBox.Enabled = useWebServiceCheckBox.Enabled;
relativeUrlTextBox.Enabled = useWebServiceCheckBox.Enabled;
}
public CfgUpdateFlags VerifyCfg(ref string message)
{
CfgUpdateFlags flags = CfgUpdateFlags.None;
int dummy;
if (!int.TryParse(commTimeoutTextBox.Text, out dummy) || dummy < 500 || dummy > 5000)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'Comm. timeout' should be in range 500 .. 5000";
}
if (!int.TryParse(maxCommRetriesTextBox.Text, out dummy) || dummy < 1 || dummy > 10)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'Max. retries' should be in range 1 .. 10";
}
if (!int.TryParse(delayBetweenRetriesTextBox.Text, out dummy) || dummy < 0 || dummy > 5000)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'Comm. timeout' should be in range 0 .. 5000";
}
if (!int.TryParse(nrThreadsTextBox.Text, out dummy) || (dummy != 1 && dummy != 2 && dummy != 4))
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "'Nr. threads' should be 1, 2 or 4";
}
if (!int.TryParse(iperlCheckErrorsToStopTextBox.Text, out dummy) || ((dummy < 1) && (dummy > 40)))
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + string.Format(Strings.Invalid_0, iperlCheckErrorsToStopLabel.Text);
}
if (!int.TryParse(textBox15rl.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN15 RL should be in range -50 .. 50";
}
if (!int.TryParse(textBox15lr.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN15 LR should be in range -50 .. 50";
}
if (!int.TryParse(textBox20rl.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN20 RL should be in range -50 .. 50";
}
if (!int.TryParse(textBox20lr.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN20 LR should be in range -50 .. 50";
}
if (!int.TryParse(textBox25_63rl.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN25 Q3 6.3 RL should be in range -50 .. 50";
}
if (!int.TryParse(textBox25_63lr.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN25 Q3 6.3 LR should be in range -50 .. 50";
}
if (!int.TryParse(textBox25_10rl.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN25 Q3 10 RL should be in range -50 .. 50";
}
if (!int.TryParse(textBox25_10lr.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN25 Q3 10 LR should be in range -50 .. 50";
}
if (!int.TryParse(textBox32rl.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN32 RL should be in range -50 .. 50";
}
if (!int.TryParse(textBox32lr.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN32 LR should be in range -50 .. 50";
}
if (!int.TryParse(textBox40rl.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN40 RL should be in range -50 .. 50";
}
if (!int.TryParse(textBox40lr.Text, out dummy) || dummy < -50 || dummy > 50)
{
flags |= CfgUpdateFlags.Error;
message += Environment.NewLine + "Default Q2 correction factor DN40 LR should be in range -50 .. 50";
}
return flags;
}
public CfgUpdateFlags UpdateCfg()
{
CfgUpdateFlags flags = CfgUpdateFlags.None;
if (config == null) return CfgUpdateFlags.Error; /// Control was not loaded, settings were not changed
if (config.Name != nameTextBox.Text)
{
config.Name = nameTextBox.Text;
flags |= (CfgUpdateFlags.AnyChange | CfgUpdateFlags.RestartRqrd);
}
flags |= UpdateDifferent(ref config.CommTimeout, commTimeoutTextBox.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.MaxCommRetries, maxCommRetriesTextBox.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DelayBetweenRetries, delayBetweenRetriesTextBox.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.NrThreads, nrThreadsTextBox.Text, CfgUpdateFlags.RestartRqrd | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.IperlCheckErrorsToStop, iperlCheckErrorsToStopTextBox.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_15_rl, textBox15rl.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_15_lr, textBox15lr.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_20_rl, textBox20rl.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_20_lr, textBox20lr.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_25_63_rl, textBox25_63rl.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_25_63_lr, textBox25_63lr.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_25_10_rl, textBox25_10rl.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_25_10_lr, textBox25_10lr.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_32_rl, textBox32rl.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_32_lr, textBox32lr.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_40_rl, textBox40rl.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.DfltQ2c_40_lr, textBox40lr.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.UseWebService, useWebServiceCheckBox.Checked, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.BaseUrl, baseUrlTextBox.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
flags |= UpdateDifferent(ref config.RelativeUrl, relativeUrlTextBox.Text, CfgUpdateFlags.InvokeCfgChange | CfgUpdateFlags.AnyChange);
if ((flags & CfgUpdateFlags.InvokeCfgChange) != 0)
{
TestMethod.OnCfgChange(this, new CfgChangeArgs(CfgChangeCmd.CfgChange, config));
}
return flags;
}
private void ManageCheckGroupBox(CheckBox chk, GroupBox grp)
{
/// Make sure the CheckBox isn't in the GroupBox. This will only happen the first time.
if (chk.Parent == grp)
{
grp.Parent.Controls.Add(chk); /// Reparent the CheckBox so it's not in the GroupBox.
chk.Location = new System.Drawing.Point(chk.Left + grp.Left, chk.Top + grp.Top); /// Adjust the CheckBox's location.
chk.BringToFront(); /// Move the CheckBox to the top of the stacking order.
}
/// Enable or disable the GroupBox.
grp.Enabled = chk.Checked;
}
private void useWebServiceCheckBox_CheckedChanged(object sender, EventArgs e)
{
useWebServiceGroupBox.Enabled = useWebServiceCheckBox.Checked;
}
}
}
@@ -1,520 +0,0 @@
///
/// Copyright (c) 2015 Sensus Metering Systems
/// Author: Milan Hanajík
///
namespace TBF.Rig.TestMethods.SmartTest
{
partial class TestMethodCfgCtrl
{
/// <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.commTimeoutTextBox = new System.Windows.Forms.TextBox();
this.commTimeoutLabel = new System.Windows.Forms.Label();
this.maxCommRetriesTextBox = new System.Windows.Forms.TextBox();
this.maxNrRetriesLabel = new System.Windows.Forms.Label();
this.nrThreadsTextBox = new System.Windows.Forms.TextBox();
this.nrThreadsLabel = new System.Windows.Forms.Label();
this.iperlCheckErrorsToStopTextBox = new System.Windows.Forms.TextBox();
this.iperlCheckErrorsToStopLabel = new System.Windows.Forms.Label();
this.delayBetweenRetriesTextBox = new System.Windows.Forms.TextBox();
this.delayBetweenRetriesLabel = new System.Windows.Forms.Label();
this.relativeUrlTextBox = new System.Windows.Forms.TextBox();
this.relativeUrlLabel = new System.Windows.Forms.Label();
this.baseUrlTextBox = new System.Windows.Forms.TextBox();
this.baseUrlLabel = new System.Windows.Forms.Label();
this.useWebServiceCheckBox = new System.Windows.Forms.CheckBox();
this.useWebServiceGroupBox = new System.Windows.Forms.GroupBox();
this.dfltQ2corrFactorsGroupBox = new System.Windows.Forms.GroupBox();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.textBox40lr = new System.Windows.Forms.TextBox();
this.textBox32lr = new System.Windows.Forms.TextBox();
this.textBox25_10lr = new System.Windows.Forms.TextBox();
this.textBox25_63lr = new System.Windows.Forms.TextBox();
this.textBox20lr = new System.Windows.Forms.TextBox();
this.textBox15lr = new System.Windows.Forms.TextBox();
this.textBox40rl = new System.Windows.Forms.TextBox();
this.textBox32rl = new System.Windows.Forms.TextBox();
this.textBox25_10rl = new System.Windows.Forms.TextBox();
this.textBox25_63rl = new System.Windows.Forms.TextBox();
this.textBox20rl = new System.Windows.Forms.TextBox();
this.textBox15rl = new System.Windows.Forms.TextBox();
this.useWebServiceGroupBox.SuspendLayout();
this.dfltQ2corrFactorsGroupBox.SuspendLayout();
this.SuspendLayout();
//
// nameTextBox
//
this.nameTextBox.Enabled = false;
this.nameTextBox.Location = new System.Drawing.Point(237, 31);
this.nameTextBox.Name = "nameTextBox";
this.nameTextBox.Size = new System.Drawing.Size(130, 20);
this.nameTextBox.TabIndex = 2;
//
// nameLabel
//
this.nameLabel.AutoSize = true;
this.nameLabel.Location = new System.Drawing.Point(23, 34);
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(234, 11);
this.classNameLabel.Name = "classNameLabel";
this.classNameLabel.Size = new System.Drawing.Size(83, 13);
this.classNameLabel.TabIndex = 0;
this.classNameLabel.Text = "ComonentName";
//
// commTimeoutTextBox
//
this.commTimeoutTextBox.Enabled = false;
this.commTimeoutTextBox.Location = new System.Drawing.Point(237, 53);
this.commTimeoutTextBox.Name = "commTimeoutTextBox";
this.commTimeoutTextBox.Size = new System.Drawing.Size(45, 20);
this.commTimeoutTextBox.TabIndex = 4;
//
// commTimeoutLabel
//
this.commTimeoutLabel.AutoSize = true;
this.commTimeoutLabel.Location = new System.Drawing.Point(23, 56);
this.commTimeoutLabel.Name = "commTimeoutLabel";
this.commTimeoutLabel.Size = new System.Drawing.Size(98, 13);
this.commTimeoutLabel.TabIndex = 3;
this.commTimeoutLabel.Text = "Comm. timeout [ms]";
//
// maxCommRetriesTextBox
//
this.maxCommRetriesTextBox.Enabled = false;
this.maxCommRetriesTextBox.Location = new System.Drawing.Point(237, 75);
this.maxCommRetriesTextBox.Name = "maxCommRetriesTextBox";
this.maxCommRetriesTextBox.Size = new System.Drawing.Size(45, 20);
this.maxCommRetriesTextBox.TabIndex = 6;
//
// maxNrRetriesLabel
//
this.maxNrRetriesLabel.AutoSize = true;
this.maxNrRetriesLabel.Location = new System.Drawing.Point(23, 78);
this.maxNrRetriesLabel.Name = "maxNrRetriesLabel";
this.maxNrRetriesLabel.Size = new System.Drawing.Size(61, 13);
this.maxNrRetriesLabel.TabIndex = 5;
this.maxNrRetriesLabel.Text = "Max. retries";
//
// nrThreadsTextBox
//
this.nrThreadsTextBox.Enabled = false;
this.nrThreadsTextBox.Location = new System.Drawing.Point(237, 119);
this.nrThreadsTextBox.Name = "nrThreadsTextBox";
this.nrThreadsTextBox.Size = new System.Drawing.Size(45, 20);
this.nrThreadsTextBox.TabIndex = 10;
//
// nrThreadsLabel
//
this.nrThreadsLabel.AutoSize = true;
this.nrThreadsLabel.Location = new System.Drawing.Point(23, 122);
this.nrThreadsLabel.Name = "nrThreadsLabel";
this.nrThreadsLabel.Size = new System.Drawing.Size(59, 13);
this.nrThreadsLabel.TabIndex = 9;
this.nrThreadsLabel.Text = "Nr. threads";
//
// iperlCheckErrorsToStopTextBox
//
this.iperlCheckErrorsToStopTextBox.Enabled = false;
this.iperlCheckErrorsToStopTextBox.Location = new System.Drawing.Point(237, 141);
this.iperlCheckErrorsToStopTextBox.Name = "iperlCheckErrorsToStopTextBox";
this.iperlCheckErrorsToStopTextBox.Size = new System.Drawing.Size(45, 20);
this.iperlCheckErrorsToStopTextBox.TabIndex = 13;
//
// iperlCheckErrorsToStopLabel
//
this.iperlCheckErrorsToStopLabel.AutoSize = true;
this.iperlCheckErrorsToStopLabel.Location = new System.Drawing.Point(23, 144);
this.iperlCheckErrorsToStopLabel.Name = "iperlCheckErrorsToStopLabel";
this.iperlCheckErrorsToStopLabel.Size = new System.Drawing.Size(202, 13);
this.iperlCheckErrorsToStopLabel.TabIndex = 12;
this.iperlCheckErrorsToStopLabel.Text = "iperl_check errors count to stop the cycle";
//
// delayBetweenRetriesTextBox
//
this.delayBetweenRetriesTextBox.Enabled = false;
this.delayBetweenRetriesTextBox.Location = new System.Drawing.Point(237, 97);
this.delayBetweenRetriesTextBox.Name = "delayBetweenRetriesTextBox";
this.delayBetweenRetriesTextBox.Size = new System.Drawing.Size(45, 20);
this.delayBetweenRetriesTextBox.TabIndex = 8;
//
// delayBetweenRetriesLabel
//
this.delayBetweenRetriesLabel.AutoSize = true;
this.delayBetweenRetriesLabel.Location = new System.Drawing.Point(23, 100);
this.delayBetweenRetriesLabel.Name = "delayBetweenRetriesLabel";
this.delayBetweenRetriesLabel.Size = new System.Drawing.Size(131, 13);
this.delayBetweenRetriesLabel.TabIndex = 7;
this.delayBetweenRetriesLabel.Text = "Delay between retries [ms]";
//
// relativeUrlTextBox
//
this.relativeUrlTextBox.Enabled = false;
this.relativeUrlTextBox.Location = new System.Drawing.Point(89, 50);
this.relativeUrlTextBox.Name = "relativeUrlTextBox";
this.relativeUrlTextBox.Size = new System.Drawing.Size(298, 20);
this.relativeUrlTextBox.TabIndex = 18;
//
// relativeUrlLabel
//
this.relativeUrlLabel.AutoSize = true;
this.relativeUrlLabel.Location = new System.Drawing.Point(13, 53);
this.relativeUrlLabel.Name = "relativeUrlLabel";
this.relativeUrlLabel.Size = new System.Drawing.Size(71, 13);
this.relativeUrlLabel.TabIndex = 17;
this.relativeUrlLabel.Text = "Relative URL";
//
// baseUrlTextBox
//
this.baseUrlTextBox.Enabled = false;
this.baseUrlTextBox.Location = new System.Drawing.Point(89, 24);
this.baseUrlTextBox.Name = "baseUrlTextBox";
this.baseUrlTextBox.Size = new System.Drawing.Size(298, 20);
this.baseUrlTextBox.TabIndex = 16;
//
// baseUrlLabel
//
this.baseUrlLabel.AutoSize = true;
this.baseUrlLabel.Location = new System.Drawing.Point(13, 27);
this.baseUrlLabel.Name = "baseUrlLabel";
this.baseUrlLabel.Size = new System.Drawing.Size(56, 13);
this.baseUrlLabel.TabIndex = 15;
this.baseUrlLabel.Text = "Base URL";
//
// useWebServiceCheckBox
//
this.useWebServiceCheckBox.AutoSize = true;
this.useWebServiceCheckBox.Enabled = false;
this.useWebServiceCheckBox.Location = new System.Drawing.Point(15, 0);
this.useWebServiceCheckBox.Name = "useWebServiceCheckBox";
this.useWebServiceCheckBox.Size = new System.Drawing.Size(189, 17);
this.useWebServiceCheckBox.TabIndex = 14;
this.useWebServiceCheckBox.Text = "Use web service for default values";
this.useWebServiceCheckBox.UseVisualStyleBackColor = true;
this.useWebServiceCheckBox.CheckedChanged += new System.EventHandler(this.useWebServiceCheckBox_CheckedChanged);
//
// useWebServiceGroupBox
//
this.useWebServiceGroupBox.Controls.Add(this.baseUrlTextBox);
this.useWebServiceGroupBox.Controls.Add(this.useWebServiceCheckBox);
this.useWebServiceGroupBox.Controls.Add(this.relativeUrlTextBox);
this.useWebServiceGroupBox.Controls.Add(this.relativeUrlLabel);
this.useWebServiceGroupBox.Controls.Add(this.baseUrlLabel);
this.useWebServiceGroupBox.Location = new System.Drawing.Point(11, 266);
this.useWebServiceGroupBox.Name = "useWebServiceGroupBox";
this.useWebServiceGroupBox.Size = new System.Drawing.Size(404, 83);
this.useWebServiceGroupBox.TabIndex = 0;
this.useWebServiceGroupBox.TabStop = false;
//
// dfltQ2corrFactorsGroupBox
//
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.label8);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.label7);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.label6);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.label5);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.label4);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.label3);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.label2);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.label1);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox40lr);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox32lr);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox25_10lr);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox25_63lr);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox20lr);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox15lr);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox40rl);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox32rl);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox25_10rl);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox25_63rl);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox20rl);
this.dfltQ2corrFactorsGroupBox.Controls.Add(this.textBox15rl);
this.dfltQ2corrFactorsGroupBox.Location = new System.Drawing.Point(11, 175);
this.dfltQ2corrFactorsGroupBox.Name = "dfltQ2corrFactorsGroupBox";
this.dfltQ2corrFactorsGroupBox.Size = new System.Drawing.Size(404, 85);
this.dfltQ2corrFactorsGroupBox.TabIndex = 14;
this.dfltQ2corrFactorsGroupBox.TabStop = false;
this.dfltQ2corrFactorsGroupBox.Text = "Default Q2 correction factors";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(344, 17);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(35, 13);
this.label8.TabIndex = 19;
this.label8.Text = "DN40";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(289, 17);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(35, 13);
this.label7.TabIndex = 18;
this.label7.Text = "DN32";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(233, 17);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(45, 13);
this.label6.TabIndex = 17;
this.label6.Text = "...Q3 10";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(163, 17);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(70, 13);
this.label5.TabIndex = 16;
this.label5.Text = "DN25 Q3 6.3";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(121, 17);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(35, 13);
this.label4.TabIndex = 15;
this.label4.Text = "DN20";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(65, 17);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(35, 13);
this.label3.TabIndex = 14;
this.label3.Text = "DN15";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(22, 57);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(24, 13);
this.label2.TabIndex = 13;
this.label2.Text = "L-R";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(22, 34);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(24, 13);
this.label1.TabIndex = 12;
this.label1.Text = "R-L";
//
// textBox40lr
//
this.textBox40lr.Enabled = false;
this.textBox40lr.Location = new System.Drawing.Point(337, 54);
this.textBox40lr.Name = "textBox40lr";
this.textBox40lr.Size = new System.Drawing.Size(50, 20);
this.textBox40lr.TabIndex = 11;
//
// textBox32lr
//
this.textBox32lr.Enabled = false;
this.textBox32lr.Location = new System.Drawing.Point(281, 54);
this.textBox32lr.Name = "textBox32lr";
this.textBox32lr.Size = new System.Drawing.Size(50, 20);
this.textBox32lr.TabIndex = 10;
//
// textBox25_10lr
//
this.textBox25_10lr.Enabled = false;
this.textBox25_10lr.Location = new System.Drawing.Point(225, 54);
this.textBox25_10lr.Name = "textBox25_10lr";
this.textBox25_10lr.Size = new System.Drawing.Size(50, 20);
this.textBox25_10lr.TabIndex = 9;
//
// textBox25_63lr
//
this.textBox25_63lr.Enabled = false;
this.textBox25_63lr.Location = new System.Drawing.Point(169, 54);
this.textBox25_63lr.Name = "textBox25_63lr";
this.textBox25_63lr.Size = new System.Drawing.Size(50, 20);
this.textBox25_63lr.TabIndex = 8;
//
// textBox20lr
//
this.textBox20lr.Enabled = false;
this.textBox20lr.Location = new System.Drawing.Point(113, 54);
this.textBox20lr.Name = "textBox20lr";
this.textBox20lr.Size = new System.Drawing.Size(50, 20);
this.textBox20lr.TabIndex = 7;
//
// textBox15lr
//
this.textBox15lr.Enabled = false;
this.textBox15lr.Location = new System.Drawing.Point(57, 54);
this.textBox15lr.Name = "textBox15lr";
this.textBox15lr.Size = new System.Drawing.Size(50, 20);
this.textBox15lr.TabIndex = 6;
//
// textBox40rl
//
this.textBox40rl.Enabled = false;
this.textBox40rl.Location = new System.Drawing.Point(337, 31);
this.textBox40rl.Name = "textBox40rl";
this.textBox40rl.Size = new System.Drawing.Size(50, 20);
this.textBox40rl.TabIndex = 5;
//
// textBox32rl
//
this.textBox32rl.Enabled = false;
this.textBox32rl.Location = new System.Drawing.Point(281, 31);
this.textBox32rl.Name = "textBox32rl";
this.textBox32rl.Size = new System.Drawing.Size(50, 20);
this.textBox32rl.TabIndex = 4;
//
// textBox25_10rl
//
this.textBox25_10rl.Enabled = false;
this.textBox25_10rl.Location = new System.Drawing.Point(225, 31);
this.textBox25_10rl.Name = "textBox25_10rl";
this.textBox25_10rl.Size = new System.Drawing.Size(50, 20);
this.textBox25_10rl.TabIndex = 3;
//
// textBox25_63rl
//
this.textBox25_63rl.Enabled = false;
this.textBox25_63rl.Location = new System.Drawing.Point(169, 31);
this.textBox25_63rl.Name = "textBox25_63rl";
this.textBox25_63rl.Size = new System.Drawing.Size(50, 20);
this.textBox25_63rl.TabIndex = 2;
//
// textBox20rl
//
this.textBox20rl.Enabled = false;
this.textBox20rl.Location = new System.Drawing.Point(113, 31);
this.textBox20rl.Name = "textBox20rl";
this.textBox20rl.Size = new System.Drawing.Size(50, 20);
this.textBox20rl.TabIndex = 1;
//
// textBox15rl
//
this.textBox15rl.Enabled = false;
this.textBox15rl.Location = new System.Drawing.Point(57, 31);
this.textBox15rl.Name = "textBox15rl";
this.textBox15rl.Size = new System.Drawing.Size(50, 20);
this.textBox15rl.TabIndex = 0;
//
// TestMethodCfgCtrl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.dfltQ2corrFactorsGroupBox);
this.Controls.Add(this.useWebServiceGroupBox);
this.Controls.Add(this.delayBetweenRetriesTextBox);
this.Controls.Add(this.delayBetweenRetriesLabel);
this.Controls.Add(this.iperlCheckErrorsToStopTextBox);
this.Controls.Add(this.iperlCheckErrorsToStopLabel);
this.Controls.Add(this.nrThreadsTextBox);
this.Controls.Add(this.nrThreadsLabel);
this.Controls.Add(this.maxCommRetriesTextBox);
this.Controls.Add(this.maxNrRetriesLabel);
this.Controls.Add(this.commTimeoutTextBox);
this.Controls.Add(this.commTimeoutLabel);
this.Controls.Add(this.nameTextBox);
this.Controls.Add(this.nameLabel);
this.Controls.Add(this.classNameLabel);
this.Name = "TestMethodCfgCtrl";
this.Size = new System.Drawing.Size(427, 363);
this.Load += new System.EventHandler(this.EntryFormCfgCtrl_Load);
this.useWebServiceGroupBox.ResumeLayout(false);
this.useWebServiceGroupBox.PerformLayout();
this.dfltQ2corrFactorsGroupBox.ResumeLayout(false);
this.dfltQ2corrFactorsGroupBox.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 commTimeoutTextBox;
private System.Windows.Forms.Label commTimeoutLabel;
private System.Windows.Forms.TextBox maxCommRetriesTextBox;
private System.Windows.Forms.Label maxNrRetriesLabel;
private System.Windows.Forms.TextBox nrThreadsTextBox;
private System.Windows.Forms.Label nrThreadsLabel;
private System.Windows.Forms.TextBox iperlCheckErrorsToStopTextBox;
private System.Windows.Forms.Label iperlCheckErrorsToStopLabel;
private System.Windows.Forms.TextBox delayBetweenRetriesTextBox;
private System.Windows.Forms.Label delayBetweenRetriesLabel;
private System.Windows.Forms.TextBox relativeUrlTextBox;
private System.Windows.Forms.Label relativeUrlLabel;
private System.Windows.Forms.TextBox baseUrlTextBox;
private System.Windows.Forms.Label baseUrlLabel;
private System.Windows.Forms.CheckBox useWebServiceCheckBox;
private System.Windows.Forms.GroupBox useWebServiceGroupBox;
private System.Windows.Forms.GroupBox dfltQ2corrFactorsGroupBox;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox40lr;
private System.Windows.Forms.TextBox textBox32lr;
private System.Windows.Forms.TextBox textBox25_10lr;
private System.Windows.Forms.TextBox textBox25_63lr;
private System.Windows.Forms.TextBox textBox20lr;
private System.Windows.Forms.TextBox textBox15lr;
private System.Windows.Forms.TextBox textBox40rl;
private System.Windows.Forms.TextBox textBox32rl;
private System.Windows.Forms.TextBox textBox25_10rl;
private System.Windows.Forms.TextBox textBox25_63rl;
private System.Windows.Forms.TextBox textBox20rl;
private System.Windows.Forms.TextBox textBox15rl;
}
}
@@ -1,120 +0,0 @@
<?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>
@@ -1,25 +0,0 @@
///
/// Copyright (c) 2015-2016 Sensus Metering Systems
///
using System.Collections.Generic;
using TBF.Rig.Generic;
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
namespace TBF.Rig.TestMethods.SmartTest
{
public class TestMethodFactory : IComponentFactory
{
public string ClassName { get { return GetType().Namespace.Substring(8); } }
public IComponent DummyComponent() { return new TestMethod(); }
public IComponent GetComponent(IComponentCfg cfg, IList<IComponent> components) { return new TestMethod(cfg); }
public IComponentCfg DefaultConfig() { return new TestMethodCfg(this); }
public IComponentCfg CmpntCfgFromCmpntEntity(Config.Entities.Component component)
{
return ComponentCfgBase.CreateFromDbEntity(TestMethodCfg.Serializer, component, this);
}
}
}
@@ -31,7 +31,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
ThreadId,
WMNr0,
(Ihead != null) ? Ihead.Name : "null",
Wm.WMPosition,
(Wm != null) ? Wm.WMPosition : -1,
(CommMessage != null) ? CommMessage : "null",
CommErr);
}
@@ -0,0 +1,329 @@
///
/// Copyright (c) 2015-2021 Sensus Metering Systems
///
using System;
using System.Globalization;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
namespace TBF.Rig.TestMethods.iPerlCommunication.common
{
public enum OptoTelegramFlags : byte
{
OK = 0,
OK_TestStart,
OK_TestEnd,
InvalidTelegram, /// Wrong telegram format of checksum error
SyncError,
}
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 Int32 EmfRaw; /// Signed EMF from iPerl opto data
public Int16 MagneticFieldRaw;
public Int16 FlowRaw;
public double VolumeRaw;
public double VolumeRawExt;
public Int16 Impedance;
public double Timestamp;
public double TimestampExt;
public byte CheckSum;
///
/// Calculated values
///
public double EMF()
{
return 0.000000333 * (double)EmfRaw;
}
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, float refFlow, ref Int64 volumeRawExtLast, ref Int64 timestampExtLast, bool isLog = false)
// {
// DateTime = DateTime.Now;
// Counter = counter;
// RefFlow = refFlow;
//
// if ((telegram == null) || (telegram.Length < Length) ||
// (telegram[6] != '\t') || (telegram[11] != '\t') || (telegram[16] != '\t') ||
// (telegram[23] != '\t') || (telegram[28] != '\t') || (telegram[37] != '\t') ||
// (!isLog && (telegram[40] != '\r' || telegram[41] != '\n')))
// {
// Flags = OptoTelegramFlags.InvalidTelegram;
// return false;
// }
//
// UInt32 uEmfRaw;
// bool f1 = UInt32.TryParse(telegram.Substring(0, 6), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out uEmfRaw);
// EmfRaw = (uEmfRaw > 0x7FFFFF) ? ((int)uEmfRaw - 0x1000000) : (int)uEmfRaw;
//
// 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);
//
// byte calculatedCheckSum = 0;
// for (int i = 0; i < Length - 4; i++)
// {
// calculatedCheckSum += (byte)telegram[i];
// }
//
// bool allOk = f1 && f2 && f3 && f4 && f5 && f6 && f7 && (calculatedCheckSum == CheckSum);
//
// if (allOk)
// {
// ///
// /// 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;
// }
// }
//
// Flags = allOk ? OptoTelegramFlags.OK : OptoTelegramFlags.InvalidTelegram;
//
// return allOk;
// }
// -------- TIMESTAMP (seconds) --------
const double TS_TICKS_PER_SEC = 4096.0;
const double TS_RANGE = (1UL << 32) / TS_TICKS_PER_SEC;
//const double TS_HALF = TS_RANGE / 2.0;
// -------- VOLUME (liters) --------
const double GAL_TO_LITER = 3.785411784;
const double VOL_LITERS_PER_TICK =
(4.0 / 1000.0) / GAL_TO_LITER / 2.0;
const double VOL_RANGE = (1 << 24) * VOL_LITERS_PER_TICK;
//const double VOL_HALF = VOL_RANGE / 2.0;
//New IPERL ASIC
public void UpdateFromSmart(
DiagnosticLedState4Data data,
int counter,
float refFlow,
ref double volumeRawExtLast,
ref double timestampExtLast)
{
DateTime = DateTime.Now;
Counter = counter;
RefFlow = refFlow;
FlowRaw = data.RawFlow;
VolumeRaw = data.RawVolume;
Timestamp = data.AsicTimestamp;
// ---------- VOLUME UNWRAP ----------
double uncorrected = VolumeRaw;
if (double.IsNaN(volumeRawExtLast))
{
VolumeRawExt = volumeRawExtLast = uncorrected;
}
else
{
double k = Math.Round((volumeRawExtLast - uncorrected) / VOL_RANGE);
VolumeRawExt = volumeRawExtLast = uncorrected + k * VOL_RANGE;
}
// ---------- TIMESTAMP UNWRAP ----------
uncorrected = Timestamp;
if (double.IsNaN(timestampExtLast))
{
TimestampExt = timestampExtLast = uncorrected;
}
else
{
double k = Math.Round((timestampExtLast - uncorrected) / TS_RANGE);
TimestampExt = timestampExtLast = uncorrected + k * TS_RANGE;
}
}
/// <summary>
/// Alternative to UpdateFromString(...) when data are flushed
/// </summary>
public bool UpdateFromStringDummy(string telegram)
{
DateTime = DateTime.Now;
RefFlow = 0;
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 f7 = byte.TryParse(telegram.Substring(38, 2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out CheckSum);
byte calculatedCheckSum = 0;
for (int i = 0; i < Length - 4; i++)
{
calculatedCheckSum += (byte)telegram[i];
}
bool allOk = f7 && (calculatedCheckSum == CheckSum);
Flags = allOk ? OptoTelegramFlags.OK : OptoTelegramFlags.InvalidTelegram;
return allOk;
}
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 & 0x00FFFFFF).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());
}
}
}
}
@@ -0,0 +1,25 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public sealed class IperlHatFrame
{
public byte Start { get; }
public byte Direction { get; }
public byte End { get; }
public byte Length { get; }
public byte[] CommandInformation { get; }
public byte[] Payload { get; }
public IperlHatFrame(byte start, byte direction, byte length, byte[] commandBytes, byte[] payload, byte end)
{
Start = start;
Direction = direction;
Length = length;
CommandInformation = commandBytes ?? Array.Empty<byte>();
Payload = payload ?? Array.Empty<byte>();
End = end;
}
}
}
@@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public sealed class IperlHatFrameBuilder
{
private byte _direction;
private readonly List<byte> _commandBytes = new List<byte>();
private readonly List<byte> _payload = new List<byte>();
public IperlHatFrameBuilder RequestResponse(bool enabled)
{
_direction = enabled ? TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Write : TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Read;
return this;
}
public IperlHatFrameBuilder AddCommand(ProtocolCommand command)
{
_commandBytes.Add((byte)command);
return this;
}
public IperlHatFrameBuilder AddSubCommand(ProtocolCommand subCommand)
{
if (_commandBytes.Count == 0 ||
_commandBytes[0] != (byte)ProtocolCommand.DeviceSpecific)
throw new InvalidOperationException(
"Sub-command is only valid for DeviceSpecific (0xFD) commands.");
_commandBytes.Add((byte)subCommand);
return this;
}
public IperlHatFrameBuilder AddSubCommand(ProtocolStatuses subCommand)
{
if (_commandBytes.Count == 0 ||
_commandBytes[0] != (byte)ProtocolCommand.SetState)
throw new InvalidOperationException(
"Sub-command is only valid for SetState (0xA1) commands.");
_commandBytes.Add((byte)subCommand);
return this;
}
public IperlHatFrameBuilder AddDeviceCommand(
ProtocolDeviceSubCommand subCommand)
{
_commandBytes.Add((byte)ProtocolCommand.DeviceSpecific);
_commandBytes.Add((byte)subCommand);
return this;
}
public IperlHatFrameBuilder SetVersionCommand()
{
_commandBytes.Add((byte)ProtocolCommand.Question);
_payload.AddRange(TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Version);
return this;
}
public IperlHatFrameBuilder AddPayload(byte[] payload)
{
if (payload != null)
_payload.AddRange(payload);
return this;
}
public IperlHatFrameBuilder AddPayload(DiagnosticLedState state)
{
_payload.Add((byte)state);
return this;
}
public IperlHatFrameBuilder AddPayload(byte payload)
{
_payload.Add(payload);
return this;
}
public IperlHatFrameBuilder AddDiagnosticLedState(DiagnosticLedState state)
{
RequestResponse(true);
AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState);
AddPayload((byte)state);
return this;
}
public IperlHatFrameBuilder AddNullTerminatedAscii(string text)
{
if (!string.IsNullOrEmpty(text))
_commandBytes.AddRange(
System.Text.Encoding.ASCII.GetBytes(text));
_commandBytes.Add(0x00);
return this;
}
public IperlHatFrame BuildFrame()
{
if (_commandBytes.Count == 0)
throw new InvalidOperationException("No command specified.");
byte length = (byte)(4 + _commandBytes.Count + _payload.Count); // 4 = START + dirrection + LEN + END
return new IperlHatFrame(
TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start,
_direction,
length,
_commandBytes.ToArray(),
_payload.ToArray(),
TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End);
}
public byte[] BuildBytes()
{
IperlHatFrame frame = BuildFrame();
if (frame.CommandInformation.Length > 0 && frame.CommandInformation[0] == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question)
{
var bytes = new List<byte>
{
frame.Start,
frame.Direction,
};
bytes.AddRange(frame.CommandInformation);
bytes.AddRange(frame.Payload);
bytes.Add(frame.End);
return bytes.ToArray();
}
else
{
var bytes = new List<byte>
{
frame.Start,
frame.Direction,
frame.Length,
};
bytes.AddRange(frame.CommandInformation);
bytes.AddRange(frame.Payload);
bytes.Add(frame.End);
return bytes.ToArray();
}
}
}
}
@@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public sealed class IperlHatFrameParser
{
public IperlHatResponse Parse(byte[] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (data.Length < 5)
throw new FormatException("Frame too short.");
if (data[0] != TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start)
{
//if version parse version
if (data[0] == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question)
{
//Define Question answer
var prefix = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question };
var end = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End };
if (IsPrefixValid(data, prefix, end))
{
//whole payload may be like "vers: Harry T:B800, V:06.06.01, FW:190215, 7ECE, B1.6.01, HW:4, Serial:0"
prefix = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question };
byte[] payloadVersion = ExtractPayloadUsePrefix(data, prefix, end);
return new IperlHatResponse(TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question, payloadVersion.Length > 0 ? TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusOk : TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusNok, payloadVersion);
}
}
throw new FormatException("Invalid START byte.");
}
if (data[1] != TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Read)
throw new FormatException("Frame is no Response.");
byte length = data[2];
if (length != data.Length)
throw new FormatException("Length mismatch.");
byte direction = data[1];
byte status = data[3];
var prefixCommand = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start,direction,length,status };
var endCommand = new List<byte>{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End };
byte[] payload = ExtractPayloadUsePrefix(data,prefixCommand,endCommand);
return new IperlHatResponse(0x00, status, payload);
}
private static byte[] ExtractPayloadUsePrefix(byte[] data, List<byte> prefix, List<byte> end)
{
// payload exists only if frame longer than:
// START + DIRECTION + LEN + CTRL + END = 5 bytes
// OR VERSION_START + VERSION = 5 bytes
if (data.Length <= 5)
return Array.Empty<byte>();
//check prefix is equal
int prefixLength = prefix.Count;
byte[] commandPrefix = new byte[prefixLength];
Buffer.BlockCopy(data, 0, commandPrefix, 0, prefixLength);
if (StartsWithPrefix(end, commandPrefix))
{
return Array.Empty<byte>();
}
int payloadLength = data.Length - (prefix.Count + end.Count);
byte[] payload = new byte[payloadLength];
Buffer.BlockCopy(data, prefix.Count, payload, 0, payloadLength);
return payload;
}
private static bool IsPrefixValid(byte[] data, List<byte> prefix, List<byte> end)
{
int prefixLength = prefix.Count;
// payload exists only if frame longer than:
// OR VERSION_START + VERSION = 5 bytes - "?VERS" version implemented
if (data.Length <= prefixLength) // need be and on END
return false;
//check prefix is equal
byte[] commandPrefix = new byte[prefixLength];
Buffer.BlockCopy(data, 0, commandPrefix, 0, prefixLength);
if (StartsWithPrefix(end, commandPrefix))
{
return false;
}
return true;
}
private static bool StartsWithPrefix(List<byte> data, byte[] prefix)
{
if (data.Count < prefix.Length)
return false;
for (int i = 0; i < prefix.Length; i++)
{
if (data[i] != prefix[i])
return false;
}
return true;
}
private static byte[] ExtractVersionPayload(byte[] data)
{
// payload exists only if frame longer than:
// START + LEN + CTRL + STATUS + CHK_HI + CHK_LO = 6 bytes
if (data.Length <= 5)
return Array.Empty<byte>();
int payloadLength = data.Length - 4;
byte[] payload = new byte[payloadLength];
Buffer.BlockCopy(data, 5, payload, 0, payloadLength);
return payload;
}
}
}
@@ -0,0 +1,10 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public static class IperlHatProtocol
{
public const byte START = 0x0D;
// Control bits (CNTRL1)
public const byte RESPONSE_FLAG = 0x08; // RF
}
}
@@ -0,0 +1,15 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public static class IperlHatProtocolConstants
{
public const byte Start = 0x53; //'S'
public const byte Write = 0x57; // 'W'
public const byte Read = 0x52; // 'R'
public const byte End = 0x0D; //'.'
public const byte Question = (byte)0x3F; // '?'
public static readonly byte[] Version = {0x76, 0x65, 0x72, 0x73 }; // 'v' 'e' 'r' 's'
public const byte StatusOk = 0x01;
public const byte StatusNok = 0x00;
}
}
@@ -0,0 +1,94 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol
{
public sealed class IperlHatResponse
{
public byte Control { get; } //classic control byte - valid for question now
private byte Status { get; }
public byte[] Payload { get; }
public bool IsOk => Status == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusOk;
public IperlHatResponse(byte control, byte status, byte[] payload)
{
Control = control;
Status = status;
Payload = payload ?? Array.Empty<byte>();
}
public int GetResponse(ref bool isInt)
{
if (Payload.Length > 0 && Payload.Length <= 1)
{
isInt = true;
return Payload[0];
}
isInt = false;
return 0xFD;
}
public T GetResponse<T>(out bool ok) where T : struct
{
ok = false;
// we expect exactly 1 byte payload
if (Payload == null || Payload.Length != 1)
return default;
byte raw = Payload[0];
Type t = typeof(T);
// ----- BYTE -----
if (t == typeof(byte))
{
ok = true;
return (T)(object)raw;
}
// ----- INT -----
if (t == typeof(int))
{
ok = true;
return (T)(object)(int)raw;
}
// ----- USHORT -----
if (t == typeof(ushort))
{
ok = true;
return (T)(object)(ushort)raw;
}
// ----- ENUM -----
if (t.IsEnum)
{
// check if value exists in enum
if (!Enum.IsDefined(t, raw))
return default;
ok = true;
return (T)Enum.ToObject(t, raw);
}
// unsupported type
return default;
}
public string GetAsciiPayload()
{
if (Payload.Length == 0)
return null;
int length = Array.IndexOf(Payload, (byte)0x00);
if (length < 0)
length = Payload.Length;
return System.Text.Encoding.ASCII.GetString(Payload, 0, length);
}
}
}
@@ -0,0 +1,75 @@
using System;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed
{
public sealed class DiagnosticLedParser
{
private readonly DiagnosticLedState _state;
public DiagnosticLedParser(DiagnosticLedState state)
{
_state = state;
}
public DiagnosticLedData ParseLine(string line, bool checkLineTermination = true)
{
if (string.IsNullOrEmpty(line))
throw new ArgumentNullException(nameof(line));
if (checkLineTermination && !line.EndsWith("\r\n"))
throw new FormatException("Invalid diagnostic LED line termination");
string trimmed = line.TrimEnd('\r', '\n');
string[] parts = trimmed.Split('\t');
if (parts.Length < 2)
throw new FormatException("Too few diagnostic LED fields");
// ---- Checksum ----
string checksumHex = parts[parts.Length - 1];
int lastTab = trimmed.LastIndexOf('\t');
if (lastTab < 0)
throw new FormatException("Checksum separator not found");
string beforeChecksum = trimmed.Substring(0, lastTab + 1);
byte expected = DiagnosticChecksum.Compute(beforeChecksum);
byte actual = DiagnosticHex.ParseByte(checksumHex);
if (expected != actual)
throw new FormatException("Diagnostic LED checksum mismatch");
// ---- Dispatch ----
switch (_state)
{
case DiagnosticLedState.State1:
return new DiagnosticLedState1Data(line, parts);
case DiagnosticLedState.State2:
return new DiagnosticLedState2Data(line, parts);
case DiagnosticLedState.State3:
return new DiagnosticLedState3Data(line, parts);
case DiagnosticLedState.State4:
return new DiagnosticLedState4Data(line, parts);
case DiagnosticLedState.State5:
return new DiagnosticLedState5Data(line, parts);
case DiagnosticLedState.State6:
return new DiagnosticLedState6Data(line, parts);
case DiagnosticLedState.State7:
return new DiagnosticLedState7Data(line, parts);
default:
throw new NotSupportedException("Unknown diagnostic LED state");
}
}
}
}
@@ -0,0 +1,100 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed
{
/// <summary>
/// Diagnostic LED output mode.
/// <para>
/// Determines the format and content of high-speed serial diagnostic data
/// emitted by the meter when the diagnostic LED is enabled.
/// </para>
/// <para>
/// Each state corresponds to a specific TAB-separated ASCII HEX frame layout
/// as defined in the iPERL TouchRead protocol documentation.
/// </para>
/// <para>
/// See <see cref="ProtocolDeviceSubCommand.SetDiagnosticLEDState"/>
/// diagnostic LED States.
/// </para>
/// </summary>
public enum DiagnosticLedState : byte
{
/// <summary>
/// Diagnostic LED OFF - State #0.
/// <para>
/// Basic diagnostic output containing raw ADC, field strength,
/// flow rate, volume accumulator, and capacitor voltage.
/// </para>
/// </summary>
StateOFF = 0x00,
/// <summary>
/// Diagnostic LED State #1.
/// <para>
/// Basic diagnostic output containing raw ADC, field strength,
/// flow rate, volume accumulator, and capacitor voltage.
/// </para>
/// </summary>
State1 = 0x01,
/// <summary>
/// Diagnostic LED State #2.
/// <para>
/// Extends State #1 with LCD volume, meter state,
/// and low-flow cutoff indication.
/// </para>
/// </summary>
State2 = 0x02,
/// <summary>
/// Diagnostic LED State #3.
/// <para>
/// Extends State #1 with field calibration value,
/// ASIC timestamp, and field drive time.
/// </para>
/// </summary>
State3 = 0x03,
/// <summary>
/// Diagnostic LED State #4.
/// <para>
/// Extended diagnostic output including mean flow rate,
/// field measurements, integrator calibration values,
/// and ASIC state.
/// </para>
/// </summary>
State4 = 0x04,
/// <summary>
/// Diagnostic LED State #5.
/// <para>
/// Extends State #4 with water impedance measurement.
/// </para>
/// </summary>
State5 = 0x05,
/// <summary>
/// Diagnostic LED State #6.
/// <para>
/// Extends State #5 with electrode delta, spike detection data,
/// pipe status, LCD volume, and additional ASIC state.
/// </para>
/// </summary>
State6 = 0x06,
/// <summary>
/// Diagnostic LED State #7.
/// <para>
/// Extends State #6 with raw ADC before offset correction,
/// detrended ADC value, imaginary water impedance,
/// electrode voltage noise, and ADC offset learning status.
/// </para>
/// </summary>
State7 = 0x07,
/// <summary>
/// Unknown state.
/// </summary>
StatusUnknown = 0xFF,
}
}
@@ -0,0 +1,114 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Base class for all Diagnostic LED data frames.
///
/// <para>
/// The iPERL meter emits diagnostic LED frames when the
/// Diagnostic LED is enabled using the
/// <c>Set Diagnostic LED State (0xFD 0x60)</c> command.
/// </para>
///
/// <para>
/// All diagnostic LED states (State #1 State #7) share a common
/// set of leading fields, followed by state-specific extensions.
/// This class represents those common fields.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>Pos</term>
/// <description>Common field description</description>
/// </listheader>
/// <item><term>0 xxxxxx</term><description>Signed 24-bit ADC value (twos complement)</description></item>
/// <item><term>1 aaaa</term><description>Unsigned 16-bit field strength (internal units)</description></item>
/// <item><term>2 yyyy</term><description>Signed 16-bit raw flow rate (¼ ml per bit)</description></item>
/// <item><term>3 vvvvvv</term><description>Unsigned 24-bit raw volume accumulation (¼ ml per bit)</description></item>
/// <item><term>4 cccc</term><description>Unsigned 16-bit millivolt delta on the field drive capacitor</description></item>
/// </list>
///
/// <para>
/// Each derived state class parses additional fields starting at
/// position 5, according to the selected diagnostic LED state.
/// </para>
///
/// <para>
/// The raw ASCII line (including checksum and CRLF) is preserved
/// for logging, debugging, and offline analysis.
/// </para>
/// </summary>
public abstract class DiagnosticLedData
{
const double GalToLiterConversion = 3.785411784D;
public abstract int GetByteCount();
/// <summary>
/// Raw diagnostic LED line exactly as received from the meter,
/// including checksum and CRLF.
/// </summary>
public string RawLine { get; }
// ----- Common fields (present in all LED states) -----
/// <summary>
/// Signed 24-bit ADC value (twos complement).
/// </summary>
public int Adc24 { get; protected set; }
/// <summary>
/// Unsigned 16-bit field strength in internal (non-legacy) units.
/// </summary>
public ushort FieldStrength { get; protected set; }
/// <summary>
/// Signed 16-bit raw flow rate in units of ¼ milliliter per bit.
/// </summary>
public short RawFlow { get; protected set; }
/// <summary>
/// Unsigned 24-bit raw volume accumulation in units of ¼ milliliter per bit. it is in Gal * 2
/// </summary>
public uint RawVolume1to4 { get; protected set; } // in 1/4 ml Gal * 2
/// <summary>
/// Raw volume in liters
/// </summary>
public double RawVolume // in liter
{
get
{
double volume = (RawVolume1to4 * 0.00025) ; // convert to liters
return volume;
}
}
/// <summary>
/// Raw volume in Gal
/// </summary>
public double RawVolumeInGal // in Gal
{
get
{
double volume = (RawVolume1to4 * 4.0) / 1000.0F; // convert to Gal
//volume = (volume / GalToLiterConversion) / 2; // convert to liter
return volume;
}
}
/// <summary>
/// Unsigned 16-bit millivolt delta measured on the field drive capacitor.
/// </summary>
public ushort CapacitorMv { get; protected set; }
/// <summary>
/// Initializes the base diagnostic LED data with the raw input line.
/// </summary>
/// <param name="raw">
/// Raw ASCII line received from the diagnostic LED output.
/// </param>
protected DiagnosticLedData(string raw)
{
RawLine = raw;
}
}
}
@@ -0,0 +1,37 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
public static class DiagnosticLedFrameSpec
{
public static int GetExpectedAsciiLength(DiagnosticLedState state)
{
switch (state)
{
case DiagnosticLedState.State1: return 33;
case DiagnosticLedState.State2: return 48;
case DiagnosticLedState.State3: return 50;
case DiagnosticLedState.State4: return 84;
case DiagnosticLedState.State5: return 89;
case DiagnosticLedState.State6: return 112;
case DiagnosticLedState.State7: return 139;
default: throw new ArgumentOutOfRangeException(nameof(state));
}
}
public static int GetExpectedFieldCount(DiagnosticLedState state)
{
switch (state)
{
case DiagnosticLedState.State1: return 6;
case DiagnosticLedState.State2: return 9;
case DiagnosticLedState.State3: return 9;
case DiagnosticLedState.State4: return 15;
case DiagnosticLedState.State5: return 16;
case DiagnosticLedState.State6: return 21;
case DiagnosticLedState.State7: return 26;
default: throw new ArgumentOutOfRangeException(nameof(state));
}
}
}
}
@@ -0,0 +1,58 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #1 data frame.
///
/// <para>
/// Frame format: TAB-separated ASCII hexadecimal fields, terminated by CRLF.
/// The checksum is an 8-bit sum of all previous ASCII bytes including
/// the TAB character before the checksum field.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>Pos</term>
/// <description>Field description</description>
/// </listheader>
/// <item><term>0 xxxxxx</term><description>Signed 24-bit ADC value (twos complement)</description></item>
/// <item><term>1 aaaa</term><description>Unsigned 16-bit field strength (internal units)</description></item>
/// <item><term>2 yyyy</term><description>Signed 16-bit raw flow rate (¼ ml per bit)</description></item>
/// <item><term>3 vvvvvv</term><description>Unsigned 24-bit raw volume accumulation (¼ ml per bit)</description></item>
/// <item><term>4 cccc</term><description>Unsigned 16-bit millivolt delta on the field drive capacitor</description></item>
/// <item><term>5 ss</term><description>Unsigned 8-bit checksum (sum of all previous ASCII bytes
/// including the TAB before the checksum field)</description></item>
/// </list>
/// </summary>
public class DiagnosticLedState1Data : DiagnosticLedData
{
public DiagnosticLedState1Data(string raw, string[] f)
: base(raw)
{
Adc24 = DiagnosticHex.ParseInt24(f[0]);
FieldStrength = DiagnosticHex.ParseUInt16(f[1]);
RawFlow = DiagnosticHex.ParseInt16(f[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(f[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(f[4]);
}
public override string ToString()
{
return $"DiagnosticLedState1Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc ss
/// Chars total = 26
/// Tabs = 5
/// CRLF = 2
/// Total bytes = 33
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 33;
}
}
}
@@ -0,0 +1,90 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #2 data frame.
///
/// <para>
/// State #2 extends the common diagnostic LED fields with information
/// about the LCD-displayed volume, the current meter operating state,
/// and whether the meter is in low-flow cutoff mode.
/// </para>
///
/// <para>
/// Frame format: TAB-separated ASCII hexadecimal fields, terminated by CRLF.
/// The checksum is an 8-bit sum of all previous ASCII bytes including
/// the TAB character before the checksum field.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>Pos</term>
/// <description>Field description</description>
/// </listheader>
/// <item><term>0 xxxxxx</term><description>Signed 24-bit ADC value (twos complement)</description></item>
/// <item><term>1 aaaa</term><description>Unsigned 16-bit field strength (internal units)</description></item>
/// <item><term>2 yyyy</term><description>Signed 16-bit raw flow rate (¼ ml per bit)</description></item>
/// <item><term>3 vvvvvv</term><description>Unsigned 24-bit raw volume accumulation (¼ ml per bit)</description></item>
/// <item><term>4 cccc</term><description>Unsigned 16-bit millivolt delta on the field drive capacitor</description></item>
/// <item><term>5 gggggggg</term><description>Unsigned 32-bit volume displayed on the LCD</description></item>
/// <item><term>6 mm</term><description>Unsigned 8-bit meter state (see Table 17-23 in protocol documentation)</description></item>
/// <item><term>7 ff</term><description>Unsigned 8-bit boolean flag indicating low-flow cutoff
/// state (0 = false, 1 = true)</description></item>
/// <item><term>8 ss</term><description>Unsigned 8-bit checksum (sum of all previous ASCII bytes including
/// the TAB before the checksum field)</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState2Data : DiagnosticLedData
{
/// <summary>
/// Volume displayed on LCD (raw units).
/// </summary>
public uint LcdVolume { get; }
/// <summary>
/// Meter state (see Table 17-23).
/// </summary>
public byte MeterState { get; }
/// <summary>
/// True if meter is in low-flow cutoff.
/// </summary>
public bool IsLowFlowCutoff { get; }
public DiagnosticLedState2Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (04) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #2 specific ----
LcdVolume = DiagnosticHex.ParseUInt32(fields[5]);
MeterState = DiagnosticHex.ParseByte(fields[6]);
IsLowFlowCutoff = DiagnosticHex.ParseByte(fields[7]) != 0;
}
public override string ToString()
{
return $"DiagnosticLedState2Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, LcdVolume={LcdVolume}, MeterState={MeterState}, IsLowFlowCutoff={IsLowFlowCutoff}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc gggggggg mm ff ss
/// Chars total = 38
/// Tabs = 8
/// CRLF = 2
/// Total bytes = 48
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 48;
}
}
}
@@ -0,0 +1,89 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #3 data frame.
///
/// <para>
/// State #3 extends the common diagnostic LED fields with calibration
/// and timing information related to the field drive and ASIC operation.
/// </para>
///
/// <para>
/// Frame format: TAB-separated ASCII hexadecimal fields, terminated by CRLF.
/// The checksum is an 8-bit sum of all previous ASCII bytes including
/// the TAB character before the checksum field.
/// </para>
///
/// <list type="table">
/// <listheader>
/// <term>Pos</term>
/// <description>Field description</description>
/// </listheader>
/// <item><term>0 xxxxxx</term><description>Signed 24-bit ADC value (twos complement)</description></item>
/// <item><term>1 aaaa</term><description>Unsigned 16-bit field strength (internal units)</description></item>
/// <item><term>2 yyyy</term><description>Signed 16-bit raw flow rate (¼ ml per bit)</description></item>
/// <item><term>3 vvvvvv</term><description>Unsigned 24-bit raw volume accumulation (¼ ml per bit)</description></item>
/// <item><term>4 cccc</term><description>Unsigned 16-bit millivolt delta on the field drive capacitor</description></item>
/// <item><term>5 tttt</term><description>Unsigned 16-bit field calibration value</description></item>
/// <item><term>6 bbbbbbbb</term><description>Unsigned 32-bit ASIC timestamp (8192 ticks per second,
/// rolls over at 2^32)</description></item>
/// <item><term>7 ff</term><description>Unsigned 8-bit field drive time in microseconds</description></item>
/// <item><term>8 ss</term><description>Unsigned 8-bit checksum (sum of all previous ASCII bytes including
/// the TAB before the checksum field)</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState3Data : DiagnosticLedData
{
/// <summary>
/// Unsigned 16-bit field calibration value.
/// </summary>
public ushort FieldCalibration { get; }
/// <summary>
/// ASIC timestamp in units of 1 / 8192 seconds.
/// Rolls over at 2^32.
/// </summary>
public uint AsicTimestamp { get; }
/// <summary>
/// Field drive time in microseconds.
/// </summary>
public byte FieldDriveTimeUs { get; }
public DiagnosticLedState3Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (04) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #3 specific fields ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestamp = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
}
public override string ToString()
{
return $"DiagnosticLedState3Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc tttt bbbbbbbb ff ss
/// Chars total = 40
/// Tabs = 8
/// CRLF = 2
/// Total bytes = 50
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 50;
}
}
}
@@ -0,0 +1,104 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #4 data frame.
/// <para>Frame format (TAB-separated ASCII HEX fields, CRLF terminated).</para>
/// <list type="table">
/// <listheader>
/// <term># / Field</term>
/// <description>Description</description>
/// </listheader>
/// <item><term>0 xxxxxx</term><description>signed 24-bit ADC value</description></item>
/// <item><term>1 aaaa</term><description>unsigned 16-bit Field strength</description></item>
/// <item><term>2 yyyy</term><description>signed 16-bit Raw flow rate (1/4 ml per bit)</description></item>
/// <item><term>3 vvvvvv</term><description>unsigned 24 bit raw volume accumulation in ¼ ml per bit</description></item>
/// <item><term>4 cccc</term><description>unsigned 16-bit Capacitor mV delta</description></item>
/// <item><term>5 tttt</term><description>unsigned 16-bit Field calibration</description></item>
/// <item><term>6 bbbbbbbb</term><description>unsigned 32-bit ASIC timestamp</description></item>
/// <item><term>7 ff</term><description>unsigned 8-bit Field drive time (µs)</description></item>
/// <item><term>8 mmmmmmmm</term><description>signed 32-bit Mean flow rate</description></item>
/// <item><term>9 gggg</term><description>unsigned 16-bit Field 1 measurement</description></item>
/// <item><term>10 hhhh</term><description>unsigned 16-bit Field 2 measurement</description></item>
/// <item><term>11 cccc</term><description>unsigned 16-bit Integrator calibration positive</description></item>
/// <item><term>12 nnnn</term><description>unsigned 16-bit Integrator calibration negative</description></item>
/// <item><term>13 qq</term><description>unsigned 8-bit ASIC state</description></item>
/// <item><term>14 ss</term><description>unsigned 8-bit Checksum</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState4Data : DiagnosticLedData
{
public ushort FieldCalibration { get; }
/// <summary>
/// ASIC timestamp in seconds
/// </summary>
public double AsicTimestamp
{
get { return AsicTimestampTicks / 8192; } //4096.0; }
}
/// <summary>
/// ASIC timestamp in units of 1 / 4096 seconds.
/// </summary>
public uint AsicTimestampTicks { get; }
public byte FieldDriveTimeUs { get; }
public int MeanFlowRate { get; }
public ushort Field1Measurement { get; }
public ushort Field2Measurement { get; }
public ushort IntegratorCalibrationPositive { get; }
public ushort IntegratorCalibrationNegative { get; }
public byte AsicState { get; }
public DiagnosticLedState4Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (04) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]); //1/4 ml Gal double
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #4 specific ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestampTicks = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
MeanFlowRate = unchecked((int)DiagnosticHex.ParseUInt32(fields[8]));
Field1Measurement = DiagnosticHex.ParseUInt16(fields[9]);
Field2Measurement = DiagnosticHex.ParseUInt16(fields[10]);
IntegratorCalibrationPositive = DiagnosticHex.ParseUInt16(fields[11]);
IntegratorCalibrationNegative = DiagnosticHex.ParseUInt16(fields[12]);
AsicState = DiagnosticHex.ParseByte(fields[13]);
}
public override string ToString()
{
return $"DiagnosticLedState4Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, RawVolume1to4 = {RawVolume1to4}, RawVolumeGal={RawVolumeInGal}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}, MeanFlowRate={MeanFlowRate}, Field1Measurement={Field1Measurement}, Field2Measurement={Field2Measurement}, IntegratorCalibrationPositive={IntegratorCalibrationPositive}, IntegratorCalibrationNegative={IntegratorCalibrationNegative}, AsicState={AsicState}, RawLine={RawLine}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc tttt bbbbbbbb mmmmmmmm ff gggg hhhh cccc nnnn qq ss
/// Chars total = 68
/// Tabs = 14
/// CRLF = 2
/// Total bytes = 84
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 84;
}
}
}
@@ -0,0 +1,111 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #5 data frame.
/// <para>
/// Frame format: TAB-separated ASCII HEX fields, CRLF terminated.
/// </para>
/// <list type="table">
/// <listheader>
/// <term># / Field</term>
/// <description>Description</description>
/// </listheader>
/// <item><term>0 xxxxxx</term><description>signed 24-bit ADC value</description></item>
/// <item><term>1 aaaa</term><description>unsigned 16-bit Field strength (internal units)</description></item>
/// <item><term>2 yyyy</term><description>signed 16-bit Raw flow rate (1/4 ml per bit)</description></item>
/// <item><term>3 vvvvvv</term><description>unsigned 24-bit Raw volume accumulation (1/4 ml per bit)</description></item>
/// <item><term>4 cccc</term><description>unsigned 16-bit Millivolts delta on field drive capacitor</description></item>
/// <item><term>5 tttt</term><description>unsigned 16-bit Field calibration value</description></item>
/// <item><term>6 bbbbbbbb</term><description>unsigned 32-bit ASIC timestamp (8192 ticks/sec, rolls over at 2^32)</description></item>
/// <item><term>7 ff</term><description>unsigned 8-bit Field drive time in microseconds</description></item>
/// <item><term>8 mmmmmmmm</term><description>signed 32-bit Mean flow rate (rolls over at 2^32)</description></item>
/// <item><term>9 gggg</term><description>unsigned 16-bit Field 1 measurement</description></item>
/// <item><term>10 hhhh</term><description>unsigned 16-bit Field 2 measurement</description></item>
/// <item><term>11 cccc</term><description>unsigned 16-bit Integrator calibration positive</description></item>
/// <item><term>12 nnnn</term><description>unsigned 16-bit Integrator calibration negative</description></item>
/// <item><term>13 qq</term><description>unsigned 8-bit ASIC state</description></item>
/// <item><term>14 iiii</term><description>signed 16-bit Water impedance measurement</description></item>
/// <item><term>15 ss</term><description>unsigned 8-bit Checksum</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState5Data : DiagnosticLedData
{
/// <summary>Field calibration value (tttt).</summary>
public ushort FieldCalibration { get; }
/// <summary>ASIC timestamp (bbbbbbbb), 8192 ticks per second.</summary>
public uint AsicTimestamp { get; }
/// <summary>Field drive time in microseconds (ff).</summary>
public byte FieldDriveTimeUs { get; }
/// <summary>Mean flow rate (mmmmmmmm), signed 32-bit.</summary>
public int MeanFlowRate { get; }
/// <summary>Field 1 measurement (gggg).</summary>
public ushort Field1Measurement { get; }
/// <summary>Field 2 measurement (hhhh).</summary>
public ushort Field2Measurement { get; }
/// <summary>Integrator calibration positive (cccc).</summary>
public ushort IntegratorCalibrationPositive { get; }
/// <summary>Integrator calibration negative (nnnn).</summary>
public ushort IntegratorCalibrationNegative { get; }
/// <summary>ASIC state (qq).</summary>
public byte AsicState { get; }
/// <summary>Water impedance measurement (iiii), signed 16-bit.</summary>
public short WaterImpedance { get; }
public DiagnosticLedState5Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #5 specific ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestamp = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
MeanFlowRate = unchecked((int)DiagnosticHex.ParseUInt32(fields[8]));
Field1Measurement = DiagnosticHex.ParseUInt16(fields[9]);
Field2Measurement = DiagnosticHex.ParseUInt16(fields[10]);
IntegratorCalibrationPositive = DiagnosticHex.ParseUInt16(fields[11]);
IntegratorCalibrationNegative = DiagnosticHex.ParseUInt16(fields[12]);
AsicState = DiagnosticHex.ParseByte(fields[13]);
WaterImpedance = DiagnosticHex.ParseInt16(fields[14]);
}
public override string ToString()
{
return $"DiagnosticLedState5Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}, MeanFlowRate={MeanFlowRate}, Field1Measurement={Field1Measurement}, Field2Measurement={Field2Measurement}, IntegratorCalibrationPositive={IntegratorCalibrationPositive}, IntegratorCalibrationNegative={IntegratorCalibrationNegative}, AsicState={AsicState}, WaterImpedance={WaterImpedance}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc tttt bbbbbbbb mmmmmmmm ff iiii ss
/// Chars total = 72
/// Tabs = 15
/// CRLF = 2
/// Total bytes = 89
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 89;
}
}
}
@@ -0,0 +1,152 @@
using System;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #6 data frame.
/// <para>
/// Frame format: TAB-separated ASCII HEX fields, CRLF terminated.
/// </para>
/// <list type="table">
/// <listheader>
/// <term># / Field</term>
/// <description>Description</description>
/// </listheader>
/// <item><term>0 xxxxxx</term><description>signed 24-bit ADC value</description></item>
/// <item><term>1 aaaa</term><description>unsigned 16-bit Field strength (internal units)</description></item>
/// <item><term>2 yyyy</term><description>signed 16-bit Raw flow rate (1/4 ml per bit)</description></item>
/// <item><term>3 vvvvvv</term><description>unsigned 24-bit Raw volume accumulation (1/4 ml per bit)</description></item>
/// <item><term>4 cccc</term><description>unsigned 16-bit Millivolts delta on field drive capacitor</description></item>
/// <item><term>5 tttt</term><description>unsigned 16-bit Field calibration value</description></item>
/// <item><term>6 bbbbbbbb</term><description>unsigned 32-bit ASIC timestamp (8192 ticks/sec, rolls over at 2^32)</description></item>
/// <item><term>7 ff</term><description>unsigned 8-bit Field drive time in microseconds</description></item>
/// <item><term>8 mmmmmmmm</term><description>signed 32-bit Mean flow rate (rolls over at 2^32)</description></item>
/// <item><term>9 gggg</term><description>unsigned 16-bit Field 1 measurement</description></item>
/// <item><term>10 hhhh</term><description>unsigned 16-bit Field 2 measurement</description></item>
/// <item><term>11 cccc</term><description>unsigned 16-bit Integrator calibration positive</description></item>
/// <item><term>12 nnnn</term><description>unsigned 16-bit Integrator calibration negative</description></item>
/// <item><term>13 qq</term><description>unsigned 8-bit ASIC state 0</description></item>
/// <item><term>14 iiii</term><description>signed 16-bit Water impedance measurement</description></item>
/// <item><term>15 rrrr</term><description>signed 16-bit Electrode delta (mV)</description></item>
/// <item><term>16 pp</term><description>unsigned 8-bit Spike detection diagnostic</description></item>
/// <item><term>17 ll</term><description>unsigned 8-bit Pipe status</description></item>
/// <item><term>18 dddddddd</term><description>unsigned 32-bit LCD volume</description></item>
/// <item><term>19 oo</term><description>unsigned 8-bit ASIC state 1</description></item>
/// <item><term>20 ss</term><description>unsigned 8-bit Checksum</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState6Data : DiagnosticLedData
{
public ushort FieldCalibration { get; }
public uint AsicTimestamp { get; }
public byte FieldDriveTimeUs { get; }
public int MeanFlowRate { get; }
public ushort Field1Measurement { get; }
public ushort Field2Measurement { get; }
public ushort IntegratorCalibrationPositive { get; }
public ushort IntegratorCalibrationNegative { get; }
public byte AsicState0 { get; }
public short WaterImpedance { get; }
public short ElectrodeDeltaMv { get; }
public byte SpikeDetection { get; }
public byte PipeStatus { get; }
public uint LcdVolume { get; }
public byte AsicState1 { get; }
public DiagnosticLedState6Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (04) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #6 specific ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestamp = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
MeanFlowRate = unchecked((int)DiagnosticHex.ParseUInt32(fields[8]));
Field1Measurement = DiagnosticHex.ParseUInt16(fields[9]);
Field2Measurement = DiagnosticHex.ParseUInt16(fields[10]);
IntegratorCalibrationPositive = DiagnosticHex.ParseUInt16(fields[11]);
IntegratorCalibrationNegative = DiagnosticHex.ParseUInt16(fields[12]);
AsicState0 = DiagnosticHex.ParseByte(fields[13]);
WaterImpedance = DiagnosticHex.ParseInt16(fields[14]);
ElectrodeDeltaMv = DiagnosticHex.ParseInt16(fields[15]);
SpikeDetection = DiagnosticHex.ParseByte(fields[16]);
PipeStatus = DiagnosticHex.ParseByte(fields[17]);
LcdVolume = DiagnosticHex.ParseUInt32(fields[18]);
AsicState1 = DiagnosticHex.ParseByte(fields[19]);
}
/// <summary>
/// Pipe status interpreted as <see cref="PipeStatus"/>.
/// If the value is outside the defined range, returns null.
/// </summary>
public PipeStatus PipeStatusEnumValue
{
get
{
if (!Enum.IsDefined(typeof(PipeStatus), PipeStatus))
throw new InvalidOperationException(
"Unknown pipe status value: 0x" + PipeStatus.ToString("X2"));
return (PipeStatus)PipeStatus;
}
}
/// <summary>
/// Spike Detection interpreted as <see cref="SpikeDetectionStatus"/>.
/// If the value is outside the defined range, returns null.
/// </summary>
public SpikeDetectionStatus SpikeDetectionEnumValue
{
get
{
if (!Enum.IsDefined(typeof(SpikeDetectionStatus), SpikeDetection))
throw new InvalidOperationException(
"Unknown Spike Detection value: 0x" + SpikeDetection.ToString("X2"));
return (SpikeDetectionStatus)SpikeDetection;
}
}
public override string ToString()
{
return $"DiagnosticLedState6Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}, MeanFlowRate={MeanFlowRate}, Field1Measurement={Field1Measurement}, Field2Measurement={Field2Measurement}, IntegratorCalibrationPositive={IntegratorCalibrationPositive}, IntegratorCalibrationNegative={IntegratorCalibrationNegative}, AsicState0={AsicState0}, WaterImpedance={WaterImpedance}, SpikeDetection={SpikeDetection}, PipeStatus={PipeStatus}, LcdVolume={LcdVolume}, AsicState1={AsicState1}";
}
/// <summary>
/// Format: xxxxxx aaaa yyyy vvvvvv cccc tttt bbbbbbbb mmmmmmmm ff iiii rrrr pp ll dddddddd oo ss
/// Chars total = 90
/// Tabs = 20
/// CRLF = 2
/// Total bytes = 112
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 112;
}
}
}
@@ -0,0 +1,155 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
/// <summary>
/// Diagnostic LED State #7 data frame.
/// <para>
/// Frame format: TAB-separated ASCII HEX fields, CRLF terminated.
/// This state extends State #6 with additional ADC and learning diagnostics.
/// </para>
/// <list type="table">
/// <listheader>
/// <term># / Field</term>
/// <description>Description</description>
/// </listheader>
/// <item><term>0 xxxxxx</term><description>signed 24-bit ADC value</description></item>
/// <item><term>1 aaaa</term><description>unsigned 16-bit Field strength (internal units)</description></item>
/// <item><term>2 yyyy</term><description>signed 16-bit Raw flow rate (1/4 ml per bit)</description></item>
/// <item><term>3 vvvvvv</term><description>unsigned 24-bit Raw volume accumulation (1/4 ml per bit)</description></item>
/// <item><term>4 cccc</term><description>unsigned 16-bit Millivolts delta on field drive capacitor</description></item>
/// <item><term>5 tttt</term><description>unsigned 16-bit Field calibration value</description></item>
/// <item><term>6 bbbbbbbb</term><description>unsigned 32-bit ASIC timestamp (8192 ticks/sec)</description></item>
/// <item><term>7 ff</term><description>unsigned 8-bit Field drive time (µs)</description></item>
/// <item><term>8 mmmmmmmm</term><description>signed 32-bit Mean flow rate</description></item>
/// <item><term>9 gggg</term><description>unsigned 16-bit Field 1 measurement</description></item>
/// <item><term>10 hhhh</term><description>unsigned 16-bit Field 2 measurement</description></item>
/// <item><term>11 cccc</term><description>unsigned 16-bit Integrator calibration positive</description></item>
/// <item><term>12 nnnn</term><description>unsigned 16-bit Integrator calibration negative</description></item>
/// <item><term>13 qq</term><description>unsigned 8-bit ASIC state 0</description></item>
/// <item><term>14 iiii</term><description>signed 16-bit Water impedance measurement</description></item>
/// <item><term>15 rrrr</term><description>signed 16-bit Electrode delta (mV)</description></item>
/// <item><term>16 pp</term><description>unsigned 8-bit Spike detection diagnostic</description></item>
/// <item><term>17 ll</term><description>unsigned 8-bit Pipe status</description></item>
/// <item><term>18 dddddddd</term><description>unsigned 32-bit LCD volume</description></item>
/// <item><term>19 oo</term><description>unsigned 8-bit ASIC state 1</description></item>
/// <item><term>20 xxxxxx</term><description>signed 24-bit Raw ADC value (before offset correction)</description></item>
/// <item><term>21 yyyyyy</term><description>signed 24-bit Detrended ADC value</description></item>
/// <item><term>22 iiii</term><description>signed 16-bit Imaginary water impedance</description></item>
/// <item><term>23 nnnn</term><description>unsigned 16-bit Electrode voltage noise level</description></item>
/// <item><term>24 aa</term><description>unsigned 8-bit ADC offset learning status</description></item>
/// <item><term>25 ss</term><description>unsigned 8-bit Checksum</description></item>
/// </list>
/// </summary>
public sealed class DiagnosticLedState7Data : DiagnosticLedData
{
// ----- State #6 fields -----
public ushort FieldCalibration { get; }
public uint AsicTimestamp { get; }
public byte FieldDriveTimeUs { get; }
public int MeanFlowRate { get; }
public ushort Field1Measurement { get; }
public ushort Field2Measurement { get; }
public ushort IntegratorCalibrationPositive { get; }
public ushort IntegratorCalibrationNegative { get; }
public byte AsicState0 { get; }
public short WaterImpedance { get; }
public short ElectrodeDeltaMv { get; }
public byte SpikeDetection { get; }
public byte PipeStatus { get; }
public uint LcdVolume { get; }
public byte AsicState1 { get; }
// ----- State #7 extensions -----
/// <summary>Raw ADC value before offset correction (signed 24-bit).</summary>
public int RawAdcBeforeOffset { get; }
/// <summary>Detrended ADC value (signed 24-bit).</summary>
public int DetrendedAdc { get; }
/// <summary>Imaginary water impedance (signed 16-bit).</summary>
public short ImaginaryWaterImpedance { get; }
/// <summary>Electrode voltage noise level (unsigned 16-bit).</summary>
public ushort ElectrodeVoltageNoise { get; }
/// <summary>
/// ADC offset learning status bitfield.
/// Bit 0: currently learning
/// Bit 1: completed first learning cycle
/// Other bits reserved.
/// </summary>
public byte AdcOffsetLearningStatus { get; }
public DiagnosticLedState7Data(string rawLine, string[] fields)
: base(rawLine)
{
// ---- Common fields (04) ----
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
RawVolume1to4 = DiagnosticHex.ParseUInt24(fields[3]);
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
// ---- State #6 fields ----
FieldCalibration = DiagnosticHex.ParseUInt16(fields[5]);
AsicTimestamp = DiagnosticHex.ParseUInt32(fields[6]);
FieldDriveTimeUs = DiagnosticHex.ParseByte(fields[7]);
MeanFlowRate = unchecked((int)DiagnosticHex.ParseUInt32(fields[8]));
Field1Measurement = DiagnosticHex.ParseUInt16(fields[9]);
Field2Measurement = DiagnosticHex.ParseUInt16(fields[10]);
IntegratorCalibrationPositive = DiagnosticHex.ParseUInt16(fields[11]);
IntegratorCalibrationNegative = DiagnosticHex.ParseUInt16(fields[12]);
AsicState0 = DiagnosticHex.ParseByte(fields[13]);
WaterImpedance = DiagnosticHex.ParseInt16(fields[14]);
ElectrodeDeltaMv = DiagnosticHex.ParseInt16(fields[15]);
SpikeDetection = DiagnosticHex.ParseByte(fields[16]);
PipeStatus = DiagnosticHex.ParseByte(fields[17]);
LcdVolume = DiagnosticHex.ParseUInt32(fields[18]);
AsicState1 = DiagnosticHex.ParseByte(fields[19]);
// ---- State #7 extensions ----
RawAdcBeforeOffset = DiagnosticHex.ParseInt24(fields[20]);
DetrendedAdc = DiagnosticHex.ParseInt24(fields[21]);
ImaginaryWaterImpedance = DiagnosticHex.ParseInt16(fields[22]);
ElectrodeVoltageNoise = DiagnosticHex.ParseUInt16(fields[23]);
AdcOffsetLearningStatus = DiagnosticHex.ParseByte(fields[24]);
}
public override string ToString()
{
return $"DiagnosticLedState7Data: Adc24={Adc24}, FieldStrength={FieldStrength}, RawFlow={RawFlow}, RawVolume={RawVolume}, CapacitorMv={CapacitorMv}, FieldCalibration={FieldCalibration}, AsicTimestamp={AsicTimestamp}, FieldDriveTimeUs={FieldDriveTimeUs}, MeanFlowRate={MeanFlowRate}, Field1Measurement={Field1Measurement}, Field2Measurement={Field2Measurement}, IntegratorCalibrationPositive={IntegratorCalibrationPositive}, IntegratorCalibrationNegative={IntegratorCalibrationNegative}, AsicState0={AsicState0}, WaterImpedance={WaterImpedance}, ElectrodeDeltaMv={ElectrodeDeltaMv}, SpikeDetection={SpikeDetection}, PipeStatus={PipeStatus}, LcdVolume={LcdVolume}, AsicState1={AsicState1}, RawAdcBeforeOffset={RawAdcBeforeOffset}, DetrendedAdc={DetrendedAdc}, ImaginaryWaterImpedance={ImaginaryWaterImpedance}, ElectrodeVoltageNoise={ElectrodeVoltageNoise}, AdcOffsetLearningStatus={AdcOffsetLearningStatus}";
}
/// <summary>
/// Format:
/// Chars total = 112
/// Tabs = 25
/// CRLF = 2
/// Total bytes = 139
/// </summary>
/// <returns> Total bytes</returns>
public override int GetByteCount()
{
return 139;
}
}
}
@@ -0,0 +1,11 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
public enum PipeStatus : byte
{
MetroLowFlowCut = 0,
MetroFlowReverse = 1,
MetroFlowForward = 2,
MetroEmptyPipe = 3
}
}
@@ -0,0 +1,11 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer
{
public enum SpikeDetectionStatus : byte
{
NoSpike = 0,
AdcSpike = 1,
SpikeHoldOff = 2,
SpikeHighFlow = 5
}
}
@@ -0,0 +1,13 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils
{
internal static class DiagnosticChecksum
{
public static byte Compute(string lineWithoutChecksum)
{
byte sum = 0;
foreach (char c in lineWithoutChecksum)
sum += (byte)c;
return sum;
}
}
}
@@ -0,0 +1,40 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils
{
internal static class DiagnosticHex
{
public static int ParseInt24(string hex)
{
int value = Convert.ToInt32(hex, 16);
if ((value & 0x800000) != 0)
value |= unchecked((int)0xFF000000); // sign extend
return value;
}
public static uint ParseUInt24(string hex)
{
return Convert.ToUInt32(hex, 16);
}
public static short ParseInt16(string hex)
{
return unchecked((short)Convert.ToUInt16(hex, 16));
}
public static ushort ParseUInt16(string hex)
{
return Convert.ToUInt16(hex, 16);
}
public static uint ParseUInt32(string hex)
{
return Convert.ToUInt32(hex, 16);
}
public static byte ParseByte(string hex)
{
return Convert.ToByte(hex, 16);
}
}
}
@@ -0,0 +1,49 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils
{
public class DiagnostigLedDataByUnit
{
private readonly Common.Unit _unitFlow;
private readonly Common.Unit _unitVolume;
private readonly DiagnosticLedState4Data _data;
public DiagnostigLedDataByUnit(Common.Unit unitFlow, Common.Unit unitVolume, DiagnosticLedState4Data data)
{
this._unitFlow = unitFlow;
this._unitVolume = unitVolume;
this._data = data;
}
public Common.Unit Unit => _unitVolume;
public DiagnosticLedState4Data Data => _data;
public double RawFlow {
get { return UnitVolume(_unitFlow, _data.RawFlow); }
}
public double RawVolume
{
get { return Common.Units.ConvertFrom(_unitVolume, _data.RawVolume); }
}
public double AsicTimestamp
{
get { return _data.AsicTimestamp; }
}
public static double UnitVolume(Common.Unit unit, double volume)
{
return Common.Units.ConvertFrom(unit, volume); /// 1 liter
}
public static uint DeltaTicks(uint oldTicks, uint newTicks)
{
return newTicks >= oldTicks
? newTicks - oldTicks
: uint.MaxValue - oldTicks + newTicks + 1;
}
}
}
@@ -0,0 +1,175 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public static class HexFormatter
{
/// <summary>
/// Byte to hex string.
/// Formats a single byte as 0xNN.
/// Example: 0x0D
/// </summary>
public static string ToHex(byte value)
{
return "0x" + value.ToString("X2");
}
/// <summary>
/// int to byte - securely
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static byte ToHexByte(int value)
{
if (value < 0 || value > 255)
throw new ArgumentOutOfRangeException(nameof(value),
"Value must be between 0 and 255.");
return (byte)value;
}
/// <summary>
/// Formats a byte array as 0xNN 0xNN ...
/// </summary>
public static string ToHex(byte[] data)
{
if (data == null || data.Length == 0)
return "<empty>";
var sb = new System.Text.StringBuilder();
for (int i = 0; i < data.Length; i++)
{
if (i > 0)
sb.Append(' ');
sb.Append("0x");
sb.Append(data[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Formats a byte array exactly as shown in serial terminals.
/// Example: "0D 04 08 01 00 1A"
/// </summary>
public static string ToSerialHex(byte[] data)
{
if (data == null || data.Length == 0)
return string.Empty;
var sb = new System.Text.StringBuilder();
for (int i = 0; i < data.Length; i++)
{
if (i > 0)
sb.Append(' ');
sb.Append(data[i].ToString("X2"));
}
return sb.ToString();
}
public static string ToHexWithAscii(byte value)
{
char c = (value >= 32 && value <= 126) ? (char)value : '.';
return $"0x{value:X2} ('{c}')";
}
public static string ToSerialHexWithAscii(byte[] data)
{
if (data == null || data.Length == 0)
return string.Empty;
var hex = new StringBuilder(data.Length * 3);
var ascii = new StringBuilder(data.Length);
foreach (byte b in data)
{
hex.Append(b.ToString("X2")).Append(' ');
// Printable ASCII range
if (b >= 32 && b <= 126)
{
ascii.Append((char)b);
}
// Binary numbers 09 -> show digit
else if (b <= 9)
{
ascii.Append((char)('0' + b));
}
else
{
ascii.Append('.');
}
}
// remove last trailing space in hex
if (hex.Length > 0)
hex.Length--;
return $"{hex} | {ascii}";
}
public static string ToHex(int value)
{
return $"0x{(byte)value:X2}";
}
public static byte[] IntToBytesBE(int value, int byteCount)
{
var result = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
result[byteCount - 1 - i] = (byte)(value >> (8 * i));
return result;
}
public static byte[] IntToBytesLE(int value, int byteCount)
{
var result = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
result[i] = (byte)(value >> (8 * i));
return result;
}
public static byte[] AsciiToBytes(string text)
{
return string.IsNullOrEmpty(text)
? Array.Empty<byte>()
: System.Text.Encoding.ASCII.GetBytes(text);
}
/// <summary>
/// Converts a hex string to a byte array.
/// Like: string hex = "3F 76 65 72 73 3A 20 48 61 72 72 79 20 54 3A 42 38 30 30 2C 20";
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static byte[] HexStringToByteArray(string hex)
{
if (hex == null)
throw new ArgumentNullException(nameof(hex));
return hex
.Split(new[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(b => byte.Parse(b, NumberStyles.HexNumber, CultureInfo.InvariantCulture))
.ToArray();
}
}
}
@@ -0,0 +1,21 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public class IpelHatCommandDecoder
{
public static string DescribeCommand(byte command)
{
return "";
}
public static string DescribeDirection(byte direction)
{
if (direction == IperlHatProtocol.IperlHatProtocolConstants.Write)
return "(WRITE - OUTGOING)";
if (direction == IperlHatProtocol.IperlHatProtocolConstants.Read)
return "(READ - INCOMING)";
return "INVALID CONTROL BITS (unsupported pattern)";
}
}
}
@@ -0,0 +1,85 @@
using System;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public static class IperlHatLogger
{
public static string DescribeTx(byte[] frame)
{
if (frame == null || frame.Length < 5)
return "Invalid frame";
if (frame[2] == IperlHatProtocol.IperlHatProtocolConstants.Question)
{
return
"TX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" DIRECTION : {HexFormatter.ToHex(frame[1])} ({IpelHatCommandDecoder.DescribeDirection(frame[1])})\n" +
$" COMMAND : {HexFormatter.ToHexWithAscii(frame[2])}\n" +
$" INFO : {HexFormatter.ToSerialHexWithAscii(GetInformatioQuestion(frame))}\n" +
$" END : {HexFormatter.ToHex(frame[frame.Length - 1])}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
else
{
return
"TX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" DIRECTION : {HexFormatter.ToHex(frame[1])} ({HexFormatter.ToHexWithAscii(frame[1])}) {IpelHatCommandDecoder.DescribeDirection(frame[1])}\n" +
$" LEN : {HexFormatter.ToHex(frame[2])} - {(int)frame[2]}\n" +
$" COMMAND : {HexFormatter.ToHexWithAscii(frame[3])}\n" +
$" INFO : {HexFormatter.ToSerialHexWithAscii(GetInformation(frame))}\n" +
$" END : {HexFormatter.ToHex(frame[frame.Length - 1])}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
}
//payload
private static byte[] GetInformation(byte[] frame)
{
int infoLength = frame.Length - 5; // START + DIRECTION + LEN + COMMAND + END
if (infoLength <= 0)
return Array.Empty<byte>();
var info = new byte[infoLength];
Buffer.BlockCopy(frame, 4, info, 0, infoLength);
return info;
}
//payload for question
private static byte[] GetInformatioQuestion(byte[] frame)
{
int infoLength = frame.Length - 4; // START + DIRECTION + COMMAND + END
if (infoLength <= 0)
return Array.Empty<byte>();
var info = new byte[infoLength];
Buffer.BlockCopy(frame, 3, info, 0, infoLength);
return info;
}
public static string DescribeRx(byte[] frame, TouchReadResponse response)
{
return
"RX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" LEN : {HexFormatter.ToHex(frame[1])} ({frame[1]})\n" +
$" CONTROL : {HexFormatter.ToHex(response.Control)}\n" +
$" STATUS : {HexFormatter.ToHex(response.Status)} ({DescribeStatus(response.Status)})\n" +
$" PAYLOAD : {HexFormatter.ToHex(response.Payload)}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
private static string DescribeStatus(byte status)
{
switch (status)
{
case 0x01: return "Command complete, no errors";
case 0x02: return "Unable to execute";
case 0x04: return "Unsupported control bits";
default: return "Unknown status";
}
}
}
}
@@ -0,0 +1,16 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public static class TouchReadControlDecoder
{
public static string Describe(byte control)
{
if (control == 0x00)
return "RF=0 (No response expected)";
if (control == 0x08)
return "RF=1 (Response expected)";
return "INVALID CONTROL BITS (unsupported pattern)";
}
}
}
@@ -0,0 +1,57 @@
using System;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger
{
public static class TouchReadLogger
{
public static string DescribeTx(byte[] frame)
{
if (frame == null || frame.Length < 6)
return "Invalid frame";
return
"TX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" LEN : {HexFormatter.ToHex(frame[1])} ({frame[1]})\n" +
$" CONTROL : {HexFormatter.ToHex(frame[2])} - {TouchReadControlDecoder.Describe(frame[2])}\n" +
$" INFO : {HexFormatter.ToHex(GetInformation(frame))}\n" +
$" CHECKSUM: {HexFormatter.ToHex(frame[frame.Length - 2])} {HexFormatter.ToHex(frame[frame.Length - 1])}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
private static byte[] GetInformation(byte[] frame)
{
int infoLength = frame.Length - 5; // CTRL + INFO + CHK(2)
if (infoLength <= 0)
return Array.Empty<byte>();
var info = new byte[infoLength];
Buffer.BlockCopy(frame, 3, info, 0, infoLength);
return info;
}
public static string DescribeRx(byte[] frame, TouchReadResponse response)
{
return
"RX Frame\n" +
$" START : {HexFormatter.ToHex(frame[0])}\n" +
$" LEN : {HexFormatter.ToHex(frame[1])} ({frame[1]})\n" +
$" CONTROL : {HexFormatter.ToHex(response.Control)}\n" +
$" STATUS : {HexFormatter.ToHex(response.Status)} ({DescribeStatus(response.Status)})\n" +
$" PAYLOAD : {HexFormatter.ToHex(response.Payload)}\n" +
$" RAW : {HexFormatter.ToHex(frame)}";
}
private static string DescribeStatus(byte status)
{
switch (status)
{
case 0x01: return "Command complete, no errors";
case 0x02: return "Unable to execute";
case 0x04: return "Unsupported control bits";
default: return "Unknown status";
}
}
}
}
@@ -0,0 +1,7 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led
{
public interface ITouchReadLedParser
{
TouchReadLedData Parse(TouchReadLedMessage message);
}
}
@@ -0,0 +1,17 @@
using System.Globalization;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led
{
public class ShortVariableLedParser : ITouchReadLedParser
{
public TouchReadLedData Parse(TouchReadLedMessage msg)
{
return new TouchReadLedData(msg.Raw)
{
MeterId = msg.Fields[0],
Reading = decimal.Parse(msg.Fields[1],
CultureInfo.InvariantCulture)
};
}
}
}
@@ -0,0 +1,77 @@
using System;
using System.Globalization;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led
{
/// <summary>
/// Parsed data from a unidirectional TouchRead LED message.
/// The exact populated fields depend on the configured reading mode.
/// </summary>
public sealed class TouchReadLedData
{
/// <summary>
/// Raw LED message including delimiters.
/// Example: ";12345678,00012345.67,m3;"
/// </summary>
public string Raw { get; }
/// <summary>
/// Meter factory ID or serial number (if present).
/// </summary>
public string MeterId { get; set; }
/// <summary>
/// Customer programmable ID (if present).
/// </summary>
public string CustomerId { get; set; }
/// <summary>
/// Parsed meter reading value.
/// </summary>
public decimal? Reading { get; set; }
/// <summary>
/// Engineering units (e.g. "m3", "ft3", "gal").
/// </summary>
public string Units { get; set; }
/// <summary>
/// Optional alarm/status field (bitfield or text).
/// </summary>
public string AlarmStatus { get; set; }
/// <summary>
/// Timestamp when the LED data was received.
/// </summary>
public DateTime Timestamp { get; }
public TouchReadLedData(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
throw new ArgumentException("Raw LED data must not be null or empty.", nameof(raw));
Raw = raw;
Timestamp = DateTime.UtcNow;
}
/// <summary>
/// Helper to safely parse a decimal value using invariant culture.
/// </summary>
public static decimal? ParseDecimal(string value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
if (decimal.TryParse(
value,
NumberStyles.Number,
CultureInfo.InvariantCulture,
out var result))
{
return result;
}
return null;
}
}
}
@@ -0,0 +1,21 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.led
{
public class TouchReadLedMessage
{
public string Raw { get; }
public string[] Fields { get; }
public TouchReadLedMessage(string raw)
{
Raw = raw ?? throw new ArgumentNullException(nameof(raw));
if (!raw.StartsWith(";") || !raw.EndsWith(";"))
throw new FormatException("Invalid LED message framing");
string content = raw.Substring(1, raw.Length - 2);
Fields = content.Split(',');
}
}
}
@@ -0,0 +1,140 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons
{
/// <summary>
/// Common iPERL TouchRead bidirectional commands.
/// These commands consist of a single-byte command code
/// placed in the Information field.
/// </summary>
public enum ProtocolCommand : byte
{
/// <summary>
/// Simple (legacy) commands (e.g. View Factory ID = 0x01)
/// </summary>
Simple = 0x00,
/// <summary>
/// View Factory ID (ex-works serial number).
/// Returns a 012 byte ASCII string terminated by NULL.
/// Response only if RF flag is set.
/// </summary>
ViewFactoryId = 0x01,
/// <summary>
/// Set Factory ID (012 ASCII characters, NULL terminated).
/// Protected by meter seal.
/// </summary>
SetFactoryId = 0x02,
/// <summary>
/// View Customer Programmable ID (112 ASCII characters).
/// </summary>
ViewProgrammableId = 0x03,
/// <summary>
/// Set Customer Programmable ID (112 ASCII characters, NULL terminated).
/// </summary>
SetProgrammableId = 0x04,
/// <summary>
/// View Version and Type string.
/// Example: B1.22,SMW002,B0.02
/// </summary>
ViewVersionAndType = 0x05,
/// <summary>
/// View Customer Programmable Text (020 ASCII characters).
/// </summary>
ViewProgrammableText = 0x07,
/// <summary>
/// Set Customer Programmable Text (020 ASCII characters, NULL terminated).
/// </summary>
SetProgrammableText = 0x08,
/// <summary>
/// View number of reading digits and decimal shift.
/// Payload: uint8 digits, int8 decimal shift.
/// </summary>
ViewNumberOfReadingDigits = 0x09,
/// <summary>
/// Set number of reading digits and decimal shift.
/// Digits range: 48, Decimal shift: -5..0.
/// </summary>
SetNumberOfReadingDigits = 0x0A,
/// <summary>
/// View reading units.
/// Returns numeric unit code (m3, ft3, gallons).
/// </summary>
ViewReadingUnits = 0x0B,
/// <summary>
/// Set reading units.
/// Valid values: 0x00=m3, 0x01=ft3, 0x04=US gallons, 0xFF=off.
/// </summary>
SetReadingUnits = 0x0C,
/// <summary>
/// View reading multiplier (resolution).
/// Range: -7..+5 or 0x80 (disabled).
/// </summary>
ViewReadingMultiplier = 0x0F,
/// <summary>
/// Set reading multiplier (resolution).
/// </summary>
SetReadingMultiplier = 0x10,
/// <summary>
/// View preset total (volume accumulator).
/// Returns 8 ASCII digits + NULL.
/// </summary>
ViewPresetTotal = 0x13,
/// <summary>
/// Set preset total (08 ASCII digits, NULL terminated).
/// Protected by meter seal.
/// </summary>
SetPresetTotal = 0x14,
/// <summary>
/// View reading mode (unidirectional TouchRead format).
/// </summary>
ViewReadingMode = 0x15,
/// <summary>
/// Set reading mode.
/// Values: Short Variable, Extended, Fixed, Smart Meter.
/// </summary>
SetReadingMode = 0x16,
/// <summary>
/// View build information (firmware details).
/// </summary>
ViewBuildInformation = 0x17,
/// <summary>
/// View meter state.
/// </summary>
ViewState = 0x19,
/// <summary>
/// Set meter state (operating mode).
/// Protected by meter seal.
/// </summary>
SetState = 0x1A,
/// <summary>
/// Device-specific command prefix.
/// Must be followed by a device sub-command byte.
/// </summary>
DeviceSpecific = 0xFD,
/// <summary>
/// Question - specific switch to add additional payload request like "vers"
/// Mandatory add payload
/// </summary>
Question = 0x3F,
}
}
@@ -0,0 +1,203 @@
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons
{
/// <summary>
/// Device-specific TouchRead sub-commands.
/// These sub-commands are used together with the
/// <see cref="TouchReadCommand.DeviceSpecific"/> (0xFD) command.
/// </summary>
public enum ProtocolDeviceSubCommand : byte
{
// ==========================================================
// System / Time
// ==========================================================
/// <summary>
/// View system time.
/// Returns uint32 seconds since 2000-01-01 00:00:00.
/// </summary>
ViewSystemTime = 0x10,
/// <summary>
/// Set system time.
/// Payload: uint32 seconds since 2000-01-01.
/// If set to zero, the meter resets and erases data.
/// Protected by meter seal.
/// </summary>
SetSystemTime = 0x11,
// ==========================================================
// Alarm Mask / Alarm Configuration
// ==========================================================
/// <summary>View alarm mask (lower 16 bits).</summary>
ViewAlarmMask = 0x31,
/// <summary>Set alarm mask (lower 16 bits).</summary>
SetAlarmMask = 0x32,
/// <summary>View alarm persistence period (days).</summary>
ViewPersistence = 0x33,
/// <summary>Set alarm persistence period (days).</summary>
SetPersistence = 0x34,
/// <summary>View leak duration (hours).</summary>
ViewLeakDuration = 0x35,
/// <summary>Set leak duration (hours).</summary>
SetLeakDuration = 0x36,
/// <summary>View current alarm states.</summary>
ViewAlarms = 0x37,
/// <summary>Set alarm states (protected by meter seal).</summary>
SetAlarms = 0x38,
// ==========================================================
// Manufacture / Counters
// ==========================================================
/// <summary>View manufacture date.</summary>
ViewManufactureDate = 0x39,
/// <summary>Set manufacture date (protected by meter seal).</summary>
SetManufactureDate = 0x3A,
/// <summary>View seconds idle.</summary>
ViewSecondsIdle = 0x3B,
/// <summary>View seconds active.</summary>
ViewSecondsActive = 0x3D,
/// <summary>View seconds used.</summary>
ViewSecondsUsed = 0x3F,
// ==========================================================
// Snapshot / Datalog
// ==========================================================
/// <summary>View snapshot data.</summary>
ViewSnapshotData = 0x41,
/// <summary>View datalog duration.</summary>
ViewDatalogDuration = 0x43,
/// <summary>Set datalog duration.</summary>
SetDatalogDuration = 0x44,
/// <summary>Read datalog.</summary>
ReadDatalog = 0x45,
/// <summary>Clear datalog.</summary>
ClearDatalog = 0x46,
// ==========================================================
// History
// ==========================================================
/// <summary>View history mask.</summary>
ViewHistoryMask = 0x47,
/// <summary>Set history mask.</summary>
SetHistoryMask = 0x48,
/// <summary>Read history.</summary>
ReadHistory = 0x49,
/// <summary>Clear history.</summary>
ClearHistory = 0x4A,
// ==========================================================
// Diagnostics / Status
// ==========================================================
/// <summary>View diagnostics.</summary>
ViewDiagnostics = 0x4B,
/// <summary>Reset diagnostics.</summary>
ResetDiagnostics = 0x4C,
/// <summary>View status file.</summary>
ViewStatusFile = 0x4F,
/// <summary>Set status file (protected by meter seal).</summary>
SetStatusFile = 0x50,
// ==========================================================
// Calibration / Configuration
// ==========================================================
/// <summary>View calibration structure.</summary>
ViewCalibrationStructure = 0x51,
/// <summary>Set calibration structure (protected by meter seal).</summary>
SetCalibrationStructure = 0x52,
/// <summary>View calibration.</summary>
ViewCalibration = 0x53,
/// <summary>Set calibration (protected by meter seal).</summary>
SetCalibration = 0x54,
/// <summary>View reboot count.</summary>
ViewRebootCount = 0x55,
/// <summary>Set reboot count (protected by meter seal).</summary>
SetRebootCount = 0x56,
/// <summary>View temperature.</summary>
ViewTemperature = 0x57,
/// <summary>Set temperature (protected by meter seal).</summary>
SetTemperature = 0x58,
// ==========================================================
// Diagnostic LED / Hardware
// ==========================================================
/// <summary>
/// Set diagnostic LED state.
/// Enables or disables high-speed LED serial output.
/// <para>
/// See <see cref="DiagnosticLedState"/>
/// diagnostic LED output modes.
/// </para>
/// </summary>
SetDiagnosticLEDState = 0x60,
// ==========================================================
// Build / Firmware Info
// ==========================================================
/// <summary>View iPERL build information.</summary>
ViewIPerlBuild = 0x65,
/// <summary>Set iPERL build (protected by meter seal).</summary>
SetIPerlBuild = 0x66,
// ==========================================================
// Bootloader (DANGEROUS use with care)
// ==========================================================
/// <summary>Enter bootloader mode.</summary>
EnterBootloader = 0x81,
/// <summary>Read FLASH memory.</summary>
ReadFlash = 0x82,
/// <summary>Erase all FLASH memory.</summary>
EraseAll = 0x83,
/// <summary>Erase FLASH segment.</summary>
EraseSegment = 0x84,
/// <summary>Update firmware code.</summary>
UpdateCode = 0x85,
/// <summary>Exit bootloader mode.</summary>
ExitBootloader = 0x86
}
}
@@ -0,0 +1,13 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons
{
public enum ProtocolStatuses : byte
{
Idle = 0x01,
Active = 0x02,
EndOfLife = 0x03,
MeterTest = 0x04,
MeterTestEMF = 0x05,
Unknown = 0x00
}
}
@@ -0,0 +1,27 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public sealed class TouchReadFrame
{
public byte Start { get; }
public byte Length { get; }
public byte Control { get; }
public byte[] Information { get; }
public ushort Checksum { get; }
public TouchReadFrame(
byte start,
byte length,
byte control,
byte[] information,
ushort checksum)
{
Start = start;
Length = length;
Control = control;
Information = information ?? Array.Empty<byte>();
Checksum = checksum;
}
}
}
@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public sealed class TouchReadFrameBuilder
{
private const byte START = 0x0D;
private byte _control;
private readonly List<byte> _information = new List<byte>();
public TouchReadFrameBuilder RequestResponse(bool enabled)
{
_control = enabled ? (byte)0x08 : (byte)0x00;
return this;
}
public TouchReadFrameBuilder AddCommand(ProtocolCommand command)
{
_information.Add((byte)command);
return this;
}
public TouchReadFrameBuilder AddSubCommand(ProtocolDeviceSubCommand subCommand)
{
if (_information.Count == 0 ||
_information[0] != (byte)ProtocolCommand.DeviceSpecific)
throw new InvalidOperationException(
"Sub-command is only valid for DeviceSpecific (0xFD) commands.");
_information.Add((byte)subCommand);
return this;
}
public TouchReadFrameBuilder AddDeviceCommand(
ProtocolDeviceSubCommand subCommand)
{
_information.Add((byte)ProtocolCommand.DeviceSpecific);
_information.Add((byte)subCommand);
return this;
}
public TouchReadFrameBuilder AddPayload(byte[] payload)
{
if (payload != null)
_information.AddRange(payload);
return this;
}
public TouchReadFrameBuilder AddDiagnosticLedState(DiagnosticLedState state)
{
_information.Add((byte)ProtocolCommand.DeviceSpecific);
_information.Add((byte)ProtocolDeviceSubCommand.SetDiagnosticLEDState);
_information.Add((byte)state);
return this;
}
public TouchReadFrameBuilder AddNullTerminatedAscii(string text)
{
if (!string.IsNullOrEmpty(text))
_information.AddRange(
System.Text.Encoding.ASCII.GetBytes(text));
_information.Add(0x00);
return this;
}
public TouchReadFrame BuildFrame()
{
if (_information.Count == 0)
throw new InvalidOperationException("No command specified.");
byte length = (byte)(1 + _information.Count + 2);
var raw = new List<byte>
{
START,
length,
_control
};
raw.AddRange(_information);
ushort checksum = CalculateChecksum(raw);
raw.Add((byte)(checksum >> 8));
raw.Add((byte)(checksum & 0xFF));
return new TouchReadFrame(
START,
length,
_control,
_information.ToArray(),
checksum);
}
public byte[] BuildBytes()
{
TouchReadFrame frame = BuildFrame();
var bytes = new List<byte>
{
frame.Start,
frame.Length,
frame.Control
};
bytes.AddRange(frame.Information);
bytes.Add((byte)(frame.Checksum >> 8));
bytes.Add((byte)(frame.Checksum & 0xFF));
return bytes.ToArray();
}
public static ushort CalculateChecksum(IEnumerable<byte> data)
{
ushort sum = 0;
foreach (var b in data)
sum += b;
return sum;
}
}
}
@@ -0,0 +1,63 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public sealed class TouchReadFrameParser
{
private const byte START = 0x0D;
public TouchReadResponse Parse(byte[] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (data.Length < 6)
throw new FormatException("Frame too short.");
if (data[0] != START)
throw new FormatException("Invalid START byte.");
byte length = data[1];
if (length + 2 != data.Length)
throw new FormatException("Length mismatch.");
ushort receivedChecksum =
(ushort)((data[data.Length - 2] << 8) |
data[data.Length - 1]);
ushort calculatedChecksum = CalculateChecksum(data, data.Length - 2);
if (receivedChecksum != calculatedChecksum)
throw new FormatException("Checksum error.");
byte control = data[2];
byte status = data[3];
byte[] payload = ExtractPayload(data);
return new TouchReadResponse(control, status, payload);
}
private static ushort CalculateChecksum(byte[] data, int count)
{
ushort sum = 0;
for (int i = 0; i < count; i++)
sum += data[i];
return sum;
}
private static byte[] ExtractPayload(byte[] data)
{
// payload exists only if frame longer than:
// START + LEN + CTRL + STATUS + CHK_HI + CHK_LO = 6 bytes
if (data.Length <= 6)
return Array.Empty<byte>();
int payloadLength = data.Length - 6;
byte[] payload = new byte[payloadLength];
Buffer.BlockCopy(data, 4, payload, 0, payloadLength);
return payload;
}
}
}
@@ -0,0 +1,10 @@
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public static class TouchReadProtocol
{
public const byte START = 0x0D;
// Control bits (CNTRL1)
public const byte RESPONSE_FLAG = 0x08; // RF
}
}
@@ -0,0 +1,34 @@
using System;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol
{
public sealed class TouchReadResponse
{
public byte Control { get; }
public byte Status { get; }
public byte[] Payload { get; }
public bool IsOk => Status == 0x01;
public TouchReadResponse(byte control, byte status, byte[] payload)
{
Control = control;
Status = status;
Payload = payload ?? Array.Empty<byte>();
}
public string GetAsciiPayload()
{
if (Payload.Length == 0)
return null;
int length = Array.IndexOf(Payload, (byte)0x00);
if (length < 0)
length = Payload.Length;
return System.Text.Encoding.ASCII.GetString(Payload, 0, length);
}
}
}
@@ -0,0 +1,10 @@
using log4net;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication
{
public class OpthoHeadService
{
}
}
@@ -0,0 +1,328 @@
using System;
using System.IO.Ports;
using Common;
using log4net;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.Utils;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication
{
public class OptoHeadTest : IDisposable
{
//protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
private static readonly ILog log = LogManager.GetLogger(typeof(OptoHeadTest));
private IperlHead iperlHead;
private SerialDriver serialDriver;
public static SerialDriver BuildConnection(IperlHead iHead)
{
return new SerialDriverBuilder()
.WithPort($"COM{iHead.RfidComPortNr}")
.WithBaudRate(2400)
.WithDataBits(8)
.WithParity(Parity.None)
.WithStopBits(StopBits.One)
.WithTimeouts(4000, 2000)
.BuildAndConnect();
}
public OptoHeadTest(IperlHead iperlHead)
{
this.iperlHead = iperlHead;
}
private void CloseConnection()
{
if (serialDriver != null)
serialDriver.CloseConnection();
serialDriver = null;
}
public string ReadRequest_PCB()
{
if (iperlHead.DebugLevel == DebugMode.Simulate)
{
return "-OK Simulated response-";
}
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
RadioService headService = new RadioService(serialDriver);
string serialNo = headService.ReadRequest_PCB(ref iperlHead);
log.Info($"PCB Number: {serialNo} on COM{iperlHead.RfidComPortNr} serialDriver: {serialDriver}");
return serialNo;
}
}
catch (Exception ex)
{
return (ex.Message.ToString());
}
return "";
}
/// <summary>
/// Set Test mode
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
public bool SetTestMode()
{
log.Debug("SetTestMode called for iHead: " + iperlHead.ToString());
bool activityModeActive = SetActivityMode_Active();
bool optActiveMode = SetOptTestMode();
log.Debug("SetTestMode result: optoMod-> " + optActiveMode + " meterModeActive ->" + activityModeActive);
return (optActiveMode && activityModeActive);
}
/// <summary>
/// Set Active mode
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
public bool SetActiveMode()
{
log.Debug("SetActiveMode called for iHead: " + iperlHead.ToString());
bool optActiveMode = SetOptActiveMode(iperlHead);
bool activityModeIdle = SetActivityMode_Idle();
return (optActiveMode && activityModeIdle);
}
/// <summary>
/// Set Test mode - string response
/// </summary>
/// <param name="iHead"></param>
/// <param name="isTestModeSuccessful"></param>
/// <returns></returns>
public string SetTestMode(ref bool isTestModeSuccessful)
{
if (iperlHead.DebugLevel == DebugMode.Simulate)
{
isTestModeSuccessful = true;
return "-OK Simulated response-";
}
try
{
bool testMode = SetTestMode();
isTestModeSuccessful = testMode;
return testMode ? "Set Test Mode - OK" : "Set Test Mode - FAILED";
}catch (Exception ex)
{
log.Error("SetTestMode() - Exception:" + ex.StackTrace);
return "Set Test Mode - Exception";
}
}
/// <summary>
/// Set Optical -> Test mode
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private bool SetOptTestMode()
{
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
RadioService headService = new RadioService(serialDriver);
bool optTestMode = headService.SetOptTestMode(iperlHead);
if (iperlHead.ConfigStruct != null)
iperlHead.ConfigStruct.OpthoStatusMode = optTestMode ? DiagnosticLedState.State4 : DiagnosticLedState.StatusUnknown;
return optTestMode;
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
/// <summary>
/// Set Active mode - string response
/// </summary>
/// <param name="iHead"></param>
/// <param name="isTestModeSuccessful"></param>
/// <returns></returns>
public string SetActiveMode(ref bool isTestModeSuccessful)
{
if (iperlHead.DebugLevel == DebugMode.Simulate)
{
isTestModeSuccessful = true;
return "-OK Simulated response-";
}
try
{
bool activeMode = SetActiveMode();
isTestModeSuccessful = activeMode;
return activeMode ? "Set Active Mode - OK" : "Set Active Mode - FAILED";
}
catch (Exception ex)
{
return "Set Active Mode - Exception";
}
}
/// <summary>
/// Set Optical -> Active mode
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private bool SetOptActiveMode(IperlHead iHead)
{
try
{
if (iHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iHead);
RadioService headService = new RadioService(serialDriver);
return headService.SetOptActiveMode(iHead);
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
/// <summary>
/// Set activity mode to active
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private bool SetActivityMode_Active()
{
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
log.Debug("SetActivityMode_Active called for iHead: " + iperlHead.ToString() + " serialDriver: " + serialDriver);
RadioService headService = new RadioService(serialDriver);
return headService.SetActivityMode_Active(iperlHead);
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
/// <summary>
/// Set activity mode to idle
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private bool SetActivityMode_Idle()
{
try
{
if (iperlHead != null)
{
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
log.Debug("SetActivityMode_Idle called for iHead: " + iperlHead.ToString() + " serialDriver: " + serialDriver);
RadioService headService = new RadioService(serialDriver);
return headService.SetActivityMode_Idle(iperlHead);
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
public void Dispose()
{
CloseConnection();
}
/// <summary>
/// Read configuration from iHead
/// DiagnosticLedState is not readable, mus only be set!
/// </summary>
/// <param name="iHead"></param>
/// <param name="ledState"></param>
/// <returns></returns>
public bool ReadConfiguration(DiagnosticLedState ledState )
{
if (iperlHead.DebugLevel == DebugMode.Simulate)
{
return true;
}
try
{
if (iperlHead != null)
{
iperlHead.ConfigStruct = new ConfigStruct();
if (serialDriver == null)
serialDriver = BuildConnection(iperlHead);
RadioService headService = new RadioService(serialDriver);
iperlHead.ConfigStruct.PCBNumberString = headService.ReadRequest_PCB(ref iperlHead);
iperlHead.ConfigStruct.StatusMode = headService.GetActivityStatusMode(iperlHead);
iperlHead.ConfigStruct.Unit = headService.GetUnit(iperlHead);
if (ledState != DiagnosticLedState.StatusUnknown) // do set
{
iperlHead.ConfigStruct.OpthoStatusMode = headService.SetOptoStatusMode(iperlHead, ledState);
}
else
{
iperlHead.ConfigStruct.OpthoStatusMode = DiagnosticLedState.StatusUnknown;
}
iperlHead.ConfigStruct.Version = headService.GetVersion(iperlHead);
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
}
}
@@ -0,0 +1,296 @@
using log4net;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
using TBF.Rig.TestMethods.iPerlCommunication.communication.Utils;
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication
{
public class RadioService
{
private static readonly ILog log = LogManager.GetLogger(typeof(RadioService));
static string okResponse = "Command complete, no errors";
static string errorResponse = "Unable to execute";
private SerialDriver serialDriver;
public RadioService(SerialDriver serialDriver)
{
this.serialDriver = serialDriver;
log.Debug("RadioService created with serialDriver= " + serialDriver + "");
}
public string ReadRequest_PCB(ref IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.ViewFactoryId)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return null;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
if (decoded.IsOk)
{
string asciiPayload = decoded.GetAsciiPayload();
if (iHead.ConfigStruct != null) // store mechanism
{
iHead.ConfigStruct.PCBNumberString = asciiPayload;
}
return asciiPayload;
}
return null;
}
public ProtocolStatuses GetActivityStatusMode(IperlHead iHead)
{
if (!serialDriver.IsOpen())
serialDriver.Open();
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.ViewState)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return ProtocolStatuses.Unknown;
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
if (!decoded.IsOk)
return ProtocolStatuses.Unknown;
ProtocolStatuses statusMode = decoded.GetResponse<ProtocolStatuses>(out bool isOK);
if (!isOK)
return ProtocolStatuses.Unknown; // wrong payload
return statusMode;
}
public DiagnosticLedState SetOptoStatusMode(IperlHead iHead, DiagnosticLedState opthoStatusMode)
{
if (!serialDriver.IsOpen())
serialDriver.Open();
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
.AddPayload(opthoStatusMode)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return DiagnosticLedState.StatusUnknown;
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("SetOptoStatusMode isOK: " + decoded.IsOk);
// if is response ok - it set it correctly
if (!decoded.IsOk)
return DiagnosticLedState.StatusUnknown;
return opthoStatusMode;
}
private static ushort SafeIntToUShort(int value)
{
if (value < ushort.MinValue || value > ushort.MaxValue)
return 0xFD; // your error code
return (ushort)value;
}
public string GetVersion(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
byte[] request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.Question)
.AddPayload(IperlHatProtocolConstants.Version)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return "";
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("GetVersion isOK: " + decoded.IsOk);
if (decoded.IsOk)
{
return decoded.GetAsciiPayload();
}
return "";
}
public bool SetActivityMode_Active(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
//Set LED to state 4
byte[] request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.SetState)
.AddSubCommand(ProtocolStatuses.Active) // Active
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 5000);
if (rawData == null)
return false;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("SetActivityMode_Active isOK: " + decoded.IsOk);
return decoded.IsOk;
}
public bool SetActivityMode_Idle(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
//Set Activity State Idle
byte[] request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.SetState)
.AddSubCommand(ProtocolStatuses.Idle)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 2000);
if (rawData == null)
return false;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("SetActivityMode_Idle isOK: " + decoded.IsOk);
return decoded.IsOk;
}
public bool SetOptTestMode(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
//Set LED to state 4
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
.AddPayload(DiagnosticLedState.State4)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 5000);
if (rawData == null)
return false;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
bool isOk = decoded.IsOk;
log.Debug("SetOptTestMode isOK: " + isOk);
return isOk;
}
/// <summary>
/// stop data streaming by LED
/// </summary>
/// <param name="iHead"></param>
/// <returns></returns>
public bool SetOptActiveMode(IperlHead iHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
//Set LED to state 1
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState)
.AddPayload(DiagnosticLedState.StateOFF)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 5000);
if (rawData == null)
return false;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
log.Debug("SetOptActiveMode isOK: " + decoded.IsOk);
return decoded.IsOk;
}
public string GetUnit(IperlHead iperlHead)
{
if (!serialDriver.IsOpen())
{
serialDriver.Open();
}
var request = new IperlHatFrameBuilder()
.RequestResponse(true)
.AddCommand(ProtocolCommand.ViewFactoryId)
.BuildBytes();
byte[] rawData = serialDriver.SendAndWait(request, 10000);
if (rawData == null)
return null;
// parse rawData
var parser = new IperlHatFrameParser();
IperlHatResponse decoded = parser.Parse(rawData);
if (decoded.IsOk)
{
string asciiPayload = decoded.GetAsciiPayload();
if (iperlHead.ConfigStruct != null) // store mechanism
{
iperlHead.ConfigStruct.Unit = asciiPayload;
}
return asciiPayload;
}
return null;
}
}
}
@@ -0,0 +1,308 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Threading;
using FluentNHibernate.Conventions;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.Utils
{
public class SerialDriver : IDisposable
{
readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(SerialDriver));
public string ErrorMessage { get; private set; }
private List<byte> SerialPortReadBuffer = new List<byte>();
private SerialPort _serialPort;
private readonly List<byte> _binMessages = new List<byte>();
private bool _isReading;
// Stored configuration (used by Builder)
private readonly string _portName;
private readonly int _baudRate;
private readonly int _dataBits;
private readonly Parity _parity;
private readonly StopBits _stopBits;
private readonly int _readTimeout;
private readonly int _writeTimeout;
private readonly ManualResetEvent _responseReceived = new ManualResetEvent(false);
#region Constructors
// Default constructor (legacy support)
public SerialDriver()
{
_serialPort = new SerialPort();
}
// Builder constructor
internal SerialDriver(
string portName,
int baudRate,
int dataBits,
Parity parity,
StopBits stopBits,
int readTimeout,
int writeTimeout)
{
_portName = portName;
_baudRate = baudRate;
_dataBits = dataBits;
_parity = parity;
_stopBits = stopBits;
_readTimeout = readTimeout;
_writeTimeout = writeTimeout;
}
#endregion
#region Open / Close
// Builder-based open
public bool Open()
{
return OpenConnection(
_portName,
_baudRate,
_dataBits,
_parity,
_stopBits,
_readTimeout,
_writeTimeout
);
}
// Legacy API (unchanged)
public bool OpenConnection(
string comPort,
int baudrate,
int dataBits,
Parity parity,
StopBits stopbits,
int readTimeout = 1000,
int writeTimeout = 1000)
{
lock (this)
{
CloseConnection();
try
{
ErrorMessage = string.Empty;
_serialPort = new SerialPort(comPort, baudrate, parity, dataBits, stopbits)
{
ReadTimeout = readTimeout,
WriteTimeout = writeTimeout
};
_serialPort.DataReceived += DataReceivedHandler;
_serialPort.Open();
}
catch (Exception ex)
{
ErrorMessage = $"COM error: Open failed {comPort}. {ex.Message}";
return false;
}
if (!_serialPort.IsOpen)
{
ErrorMessage = $"COM error: Can't open {comPort}.";
return false;
}
log.Debug("SerialDriver opened successfully for port: " + comPort);
}
return true;
}
public void CloseConnection()
{
if (_serialPort != null)
{
_serialPort.DataReceived -= DataReceivedHandler;
if (_serialPort.IsOpen)
_serialPort.Close();
_serialPort.Dispose();
_serialPort = null;
}
}
public bool IsOpen() => _serialPort?.IsOpen == true;
#endregion
#region Send / Receive
public bool SendMessage(byte[] sendDataBytes, int length, int readTimeout = 1000, int writeTimeout = 1000)
{
if (!IsOpen()) return false;
if (sendDataBytes.Length == 0) return true;
try
{
PrepareReading();
_serialPort.WriteTimeout = writeTimeout;
_serialPort.ReadTimeout = readTimeout;
_serialPort.Write(sendDataBytes, 0, length);
_isReading = true;
var stopwatch = Stopwatch.StartNew();
while (_isReading)
{
if (stopwatch.ElapsedMilliseconds > readTimeout)
{
ErrorMessage = "COM error: Receive timeout";
return false;
}
}
}
catch (Exception ex)
{
ErrorMessage = $"COM error: Transmit failed {_serialPort.PortName}. {ex.Message}";
return false;
}
return true;
}
private void PrepareReading()
{
_serialPort.DiscardInBuffer();
_binMessages.Clear();
_responseReceived.Reset();
SerialPortReadBuffer.Clear();
_isReading = true;
}
public byte[] GetRawData()
{
return _binMessages.ToArray();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
lock (this)
{
if (_serialPort == null || !_serialPort.IsOpen) return;
try
{
//Thread.Sleep(5);
if (!SerialPortReadBuffer.IsEmpty())
{
SerialPortReadBuffer.Clear();
}
int iWordCounter = 0;
bool isStart = false;
bool isQuestion = false;
int iLength = 0;
while (true)//_serialPort.BytesToRead > 0
{
byte readByte = (byte)_serialPort.ReadByte();
//I have START
if (readByte == C4.IperlHatProtocol.IperlHatProtocolConstants.Start)
{
iWordCounter++;
isStart = true;
}
// I have QUESTION
if (readByte == C4.IperlHatProtocol.IperlHatProtocolConstants.Question)
{
iWordCounter++;
isQuestion = true;
}
//I count length from start
if (iWordCounter > 0)
iWordCounter++;
if (iWordCounter > 0)
{
//Store byte to data
SerialPortReadBuffer.Add(readByte);
}
// we have length
if (iLength == 0 && isStart && SerialPortReadBuffer.Count > 2 )
{
iLength = (int)SerialPortReadBuffer[2];
}
//If we have enough bytes
if (isStart && iLength > 0
&& (SerialPortReadBuffer.Count >= iLength ||
readByte == C4.IperlHatProtocol.IperlHatProtocolConstants.End
)
)
{
break;
}
//if we read END
if (isQuestion && readByte == C4.IperlHatProtocol.IperlHatProtocolConstants.End)
{
break;
}
}
if (SerialPortReadBuffer.Count > 0)
{
_binMessages.AddRange(SerialPortReadBuffer.ToArray());
_responseReceived.Set();
}
}
catch (TimeoutException te)
{
// Ignore shutdown race conditions
}
finally
{
_isReading = false;
}
}
}
public byte[] SendAndWait(byte[] data, int timeoutMs)
{
if (!IsOpen())
throw new InvalidOperationException("Serial port not open");
log.Debug("SendAndWait() - TX: " + HexFormatter.ToHex(data));
PrepareReading();
_serialPort.Write(data, 0, data.Length);
if (!_responseReceived.WaitOne(timeoutMs))
{
log.Error("SendAndWait() - Response timeout! Details: " +
" SerialPortReadBuffer: " + HexFormatter.ToHex(SerialPortReadBuffer.ToArray()) +
" _binMessages" + HexFormatter.ToHex(_binMessages.ToArray()) +
"_responseReceived: " + _responseReceived.WaitOne(0)
);
ErrorMessage = "COM error: response timeout";
return null;
}
return GetRawData();
}
#endregion
public void Dispose()
{
CloseConnection();
}
public override string ToString()
{
return "SerialDriver: " + _serialPort.PortName + " (opened status:" + _serialPort.IsOpen +")";
}
}
}
@@ -0,0 +1,82 @@
using System;
using System.IO.Ports;
namespace TBF.Rig.TestMethods.iPerlCommunication.communication.Utils
{
public class SerialDriverBuilder
{
private string _portName;
private int _baudRate = 9600;
private int _dataBits = 8;
private Parity _parity = Parity.None;
private StopBits _stopBits = StopBits.One;
private int _readTimeout = 1000;
private int _writeTimeout = 1000;
public SerialDriverBuilder WithPort(string portName)
{
_portName = portName;
return this;
}
public SerialDriverBuilder WithBaudRate(int baudRate)
{
_baudRate = baudRate;
return this;
}
public SerialDriverBuilder WithDataBits(int dataBits)
{
_dataBits = dataBits;
return this;
}
public SerialDriverBuilder WithParity(Parity parity)
{
_parity = parity;
return this;
}
public SerialDriverBuilder WithStopBits(StopBits stopBits)
{
_stopBits = stopBits;
return this;
}
public SerialDriverBuilder WithTimeouts(int readTimeout, int writeTimeout)
{
_readTimeout = readTimeout;
_writeTimeout = writeTimeout;
return this;
}
/// <summary>
/// Build driver WITHOUT opening connection
/// </summary>
public SerialDriver Build()
{
return new SerialDriver(
_portName,
_baudRate,
_dataBits,
_parity,
_stopBits,
_readTimeout,
_writeTimeout
);
}
/// <summary>
/// Build driver AND open connection
/// </summary>
public SerialDriver BuildAndConnect()
{
var driver = Build();
if (!driver.Open())
{
throw new InvalidOperationException(driver.ErrorMessage);
}
return driver;
}
}
}
File diff suppressed because it is too large Load Diff
@@ -24,7 +24,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication
public override void InitializeAll()
{
Activity = "Read Configuration";
Activity = iPerlCommunicationForm.ReadConfigurationStr;
SimultWithPrevious = false;
SimultWithNext = false;
}
@@ -3,264 +3,165 @@
///
using System;
using System.IO;
using System.Text;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
public class ConfigStruct
{
public const int Length = 32;
//public const int Length = 32; // dynamic
public Byte Version; /// 0: 1 byte
public MeterState MeterState; /// 1: 1 byte
public UInt32 TargetTimeVeryLowBatt; /// 2: 4 bytes in seconds
public UInt32 TargetTimeLowBatt; /// 6: 4 bytes, in seconds
public UInt32 TestModeTime; /// 10: 4 bytes, Max. test mode time in seconds
public UInt16 EmptyPipeThreshold; /// 14: 2 bytes
public byte[] PCBNumber; /// 16: 5 bytes
public byte TestModeConfig; /// 21: 1 byte
public UInt32 RadioAddress; /// 22: 4 bytes
public UInt16 TempCalibration; /// 26: 2 bytes
public UInt16 AlarmMask; /// 28: 2 bytes, Default 0xA3F7
public UInt16 ConfigCheckSum; /// 30: 2 bytes
//public Byte Version; // 0: 1 byte
public string PCBNumberString; // dynamic
public ProtocolStatuses StatusMode; // byte
public DiagnosticLedState OpthoStatusMode;// byte
public string Unit; //dynamic
public string Version; // dynamic
public ConfigStruct()
{
PCBNumber = new byte[5];
}
public byte[] ToByteArray()
//Optho test status mode
public DiagnosticLedState TestModeConfig
{
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;
get { return OpthoStatusMode; }
}
/// <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)
//Activity test status mode
public ProtocolStatuses MeterState
{
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;
get
{
return StatusMode;
}
}
/// <summary>
/// <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;
}
// public bool Update(int offset, )
// {
//
// /// 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]);
// PCBNumberString
// 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>
/// Returns PCB number string (12 characters, 12 decimal digits)
/// </summary>
/// <returns>PCB number STRING</returns>
public string GetPcbNrString()
{
return PCBNumber2String(this.PCBNumber);
}
public string GetPcbNrString(){
return PCBNumberString;
}
/// <summary>
/// Converts PCBNumber to string (12 characters, 12 decimal digits)
/// </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();
}
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,
GetPcbNrString(),
TestModeConfig.ToString("X2"),
RadioAddress,
TempCalibration,
AlarmMask.ToString("X4"),
ConfigCheckSum.ToString("X4"));
return string.Format(
"Config: PCB#={0} StatusMode={1} Unit={2} V{3}",
GetPcbNrString(),
StatusMode,
Unit,
Version
);
}
public string ToString(int sel)
{
return string.Format("{1} PCB#={6} TMCfg={7}",
Version,
MeterState,
TargetTimeVeryLowBatt,
TargetTimeLowBatt,
TestModeTime,
EmptyPipeThreshold,
GetPcbNrString(),
TestModeConfig.ToString("X2"),
RadioAddress,
TempCalibration,
AlarmMask.ToString("X4"),
ConfigCheckSum.ToString("X4"));
return string.Format(
"Config: PCB#={0} StatusMode={1} Unit={2} V{3}",
GetPcbNrString(),
StatusMode,
Unit,
Version
);
}
public virtual void WriteBinary(BinaryWriter writer)
{
writer.Write(Version);
writer.Write((byte)MeterState);
writer.Write(TargetTimeVeryLowBatt);
writer.Write(TargetTimeLowBatt);
writer.Write(TestModeTime);
writer.Write(EmptyPipeThreshold);
writer.Write(PCBNumber[0]);
writer.Write(PCBNumber[1]);
writer.Write(PCBNumber[2]);
writer.Write(PCBNumber[3]);
writer.Write(PCBNumber[4]);
writer.Write(TestModeConfig);
writer.Write(RadioAddress);
writer.Write(TempCalibration);
writer.Write(AlarmMask);
writer.Write(ConfigCheckSum);
writer.Write(0x11); // mark new type of verison
// Convert string to bytes (UTF8 is standard)
byte[] versionBytes = Encoding.UTF8.GetBytes(Version);
// 1) write length
writer.Write(versionBytes.Length);
// 2) write string bytes
writer.Write(versionBytes);
//writer.Write(Version);
writer.Write((byte)StatusMode);
byte[] PCBNumberStringBytes = Encoding.UTF8.GetBytes(PCBNumberString);
// 1) write length
writer.Write(PCBNumberStringBytes.Length);
// 2) write string bytes
writer.Write(PCBNumberStringBytes);
// Convert string to bytes (UTF8 is standard)
byte[] unitBytes = Encoding.UTF8.GetBytes(Unit);
// 1) write length
writer.Write(unitBytes.Length);
// 2) write string bytes
writer.Write(unitBytes);
//writer.Write(Version);
}
public virtual void ReadBinary(BinaryReader reader)
{
Version = reader.ReadByte();
MeterState = (MeterState)reader.ReadByte();
TargetTimeVeryLowBatt = reader.ReadUInt32();
TargetTimeLowBatt = reader.ReadUInt32();
TestModeTime = reader.ReadUInt32();
EmptyPipeThreshold = reader.ReadUInt16();
PCBNumber[0] = reader.ReadByte();
PCBNumber[1] = reader.ReadByte();
PCBNumber[2] = reader.ReadByte();
PCBNumber[3] = reader.ReadByte();
PCBNumber[4] = reader.ReadByte();
TestModeConfig = reader.ReadByte();
RadioAddress = reader.ReadUInt32();
TempCalibration = reader.ReadUInt16();
AlarmMask = reader.ReadUInt16();
ConfigCheckSum = reader.ReadUInt16();
int ReadBytesCount = 0;
// ---- Test Data type ----
var readByte = reader.ReadByte();
if (readByte != 0x11) return; // not correct version
ReadBytesCount++;
// ---- Version ----
// 1) read length
int length = reader.ReadInt32();
ReadBytesCount += 4 + length;
// 2) read string bytes
byte[] versionBytes = reader.ReadBytes(length);
// 3) convert back to string
Version = Encoding.UTF8.GetString(versionBytes);
// ---- PCB Number ----
// 1) read length
int lengthPCB = reader.ReadInt32();
ReadBytesCount += 4 + lengthPCB;
// 2) read string bytes
byte[] bytesPCB = reader.ReadBytes(lengthPCB);
// 3) convert back to string
PCBNumberString = Encoding.UTF8.GetString(bytesPCB);
// ---- Unit ----
// 1) read length
int lengthUnit = reader.ReadInt32();
ReadBytesCount += 4 + lengthUnit;
// 2) read string bytes
byte[] bytesUnit = reader.ReadBytes(lengthUnit);
// 3) convert back to string
Unit = Encoding.UTF8.GetString(bytesUnit);
}
}
}
@@ -11,40 +11,35 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
private static readonly ILog log = LogManager.GetLogger(typeof(IperlHead));
const int FIFO_SIZE = 64; /// 8 sec. @ 8Hz
const double MAX_OPTO_DROPOUT = 4.5; /// sec.
const int FIFO_SIZE = 64; // 8 sec @ 8Hz
const double MAX_OPTO_DROPOUT = 4.5; // sec
Int64[] volumeRawFifo; /// Volume FIFO buffer
Int64[] timestampFifo; /// Timestamp FIFO buffer
private readonly double[] volumeRawFifo;
private readonly double[] timestampFifo; // centered timestamps
int fifoCount; /// Number of valid FIFO items
int fifoIx; /// Index of the next FIFO item
DateTime lastFifoWriteTime; /// Time of the last write to FIFO
private int fifoCount;
private int fifoIx;
private DateTime lastFifoWriteTime;
///
/// Sums for linear regression calculation
///
decimal sumXX;
decimal sumX;
decimal sumXY;
decimal sumY;
decimal N;
// regression sums (double is ideal here)
private double sumXX;
private double sumX;
private double sumXY;
private double sumY;
double minSlope; /// max. slope of the regressed line, always positive or 0
double maxSlope; /// min. slope of the regressed line, always negative or 0
private double minSlope;
private double maxSlope;
// timestamp centering for numerical stability
private double firstTimestamp = double.NaN;
public FlowDirectionDetection()
{
volumeRawFifo = new Int64[FIFO_SIZE];
timestampFifo = new Int64[FIFO_SIZE];
volumeRawFifo = new double[FIFO_SIZE];
timestampFifo = new double[FIFO_SIZE];
ClearFifo();
}
/// <summary>
/// Clear FIFO data
/// </summary>
public void ClearFifo()
{
fifoCount = 0;
@@ -55,94 +50,93 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
sumX = 0;
sumXY = 0;
sumY = 0;
N = 0;
minSlope = 0;
maxSlope = 0;
firstTimestamp = double.NaN;
}
/// <summary>
/// Write data to FIFO
/// Add sample to rolling FIFO and update regression sums
/// </summary>
/// <param name="volumeRaw">Volume</param>
/// <param name="timestamp">Time stamp</param>
public void WriteToFifo(Int64 volumeRaw, Int64 timestamp)
public void WriteToFifo(double volumeRaw, double timestamp)
{
///
/// Update sums for linear regression calculation
///
// establish time origin (CRITICAL for double precision)
if (double.IsNaN(firstTimestamp))
firstTimestamp = timestamp;
double x = timestamp - firstTimestamp; // centered time
double y = volumeRaw;
// remove oldest sample if buffer full
if (fifoCount == FIFO_SIZE)
{
/// Buffer is already full, the oldest item will be re-written
sumXX -= timestampFifo[fifoIx] * timestampFifo[fifoIx];
sumX -= timestampFifo[fifoIx];
sumXY -= timestampFifo[fifoIx] * volumeRawFifo[fifoIx];
sumY -= volumeRawFifo[fifoIx];
N--;
double oldX = timestampFifo[fifoIx];
double oldY = volumeRawFifo[fifoIx];
sumXX -= oldX * oldX;
sumX -= oldX;
sumXY -= oldX * oldY;
sumY -= oldY;
}
sumXX += timestamp * timestamp;
sumX += timestamp;
sumXY += timestamp * volumeRaw;
sumY += volumeRaw;
N++;
else
{
fifoCount++;
}
// add new sample
sumXX += x * x;
sumX += x;
sumXY += x * y;
sumY += y;
// store sample
timestampFifo[fifoIx] = x;
volumeRawFifo[fifoIx] = y;
///
/// Save new values to FIFO
///
volumeRawFifo[fifoIx] = volumeRaw;
timestampFifo[fifoIx] = timestamp;
fifoIx = (fifoIx + 1) % FIFO_SIZE;
fifoCount = Math.Min(fifoCount + 1, FIFO_SIZE);
lastFifoWriteTime = DateTime.Now;
}
/// <summary>
/// Determine whether there are enough recent FIFO data
/// </summary>
/// <returns>true when data valid</returns>
public bool AreFifoDataValid()
{
return (DateTime.Now.Subtract(lastFifoWriteTime).TotalSeconds <= MAX_OPTO_DROPOUT) && (fifoCount == FIFO_SIZE);
return (DateTime.Now.Subtract(lastFifoWriteTime).TotalSeconds <= MAX_OPTO_DROPOUT)
&& (fifoCount == FIFO_SIZE);
}
/// <summary>
/// Verify whether the flow direction is correct
/// </summary>
/// <returns>OptoHeadState.OptoAndDirOK, OptoHeadState.OptoNok or OptoHeadState.DirNok</returns>
public OptoHeadState CheckFlowDirection(Counting counting, string iPerlHeadName)
{
if (!AreFifoDataValid()) return OptoHeadState.OptoNok;
if (!AreFifoDataValid())
return OptoHeadState.OptoNok;
try
{
decimal numer = N * sumXY - sumX * sumY;
decimal denom = N * sumXX - sumX * sumX;
double N = fifoCount;
if (denom == 0) return OptoHeadState.DirNok;
double numer = N * sumXY - sumX * sumY;
double denom = N * sumXX - sumX * sumX;
if (Math.Abs(denom) < 1e-12)
return OptoHeadState.DirNok;
double slope = numer / denom;
/// Calculate the slope of the regressed line, determine min. and max.
double slope = (double)(numer / denom);
if (slope > maxSlope) maxSlope = slope;
if (slope < minSlope) minSlope = slope;
if ( counting == Counting.Arbitrary ||
if (counting == Counting.Arbitrary ||
(counting == Counting.Positive && maxSlope > Math.Abs(2 * minSlope)) ||
(counting == Counting.Negative && minSlope < -Math.Abs(2 * maxSlope)))
{
return OptoHeadState.OptoAndDirOK;
}
else
{
return OptoHeadState.DirNok;
}
return OptoHeadState.DirNok;
}
catch (Exception)
catch (Exception ex)
{
log.ErrorFormat("{0} : CheckFlowDirection() failed", iPerlHeadName);
return OptoHeadState.DirNok; /// ???
log.ErrorFormat("{0} : CheckFlowDirection() failed: {1}", iPerlHeadName, ex);
return OptoHeadState.DirNok;
}
}
}
@@ -6,17 +6,22 @@ using System.IO;
using System.IO.Ports;
using log4net;
using Common;
using Common.Iperl;
using Config.Entities;
using TBF.Rig.Generic;
using TBF.Rig.GenericDevices;
using Sensus.iPerl.NfcHandler;
using NHibernate;
using Renci.SshNet;
using System.Linq;
using System.Xml;
using System.Xml.Linq; // This line is correct and does not need to be changed.
using System.Windows;
using System.Text;
using System.Xml.Linq;
using TBF.Rig.TestMethods.iPerlCommunication.communication; // This line is correct and does not need to be changed.
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.parserer;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed.utils;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger;
using TBF.Rig.TestMethods.iPerlCommunication.communication.Utils;
using OptoTelegramFlags = TBF.Rig.TestMethods.iPerlCommunication.common.OptoTelegramFlags;
using OptoTelegramRaw = TBF.Rig.TestMethods.iPerlCommunication.common.OptoTelegramRaw;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
@@ -26,6 +31,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
public class IperlHead : ComponentBase, IDevice,IRegReaderDatastream, ISessionDataMngmnt, IOperation
{
private static readonly ILog log = LogManager.GetLogger(typeof(IperlHead));
private static readonly ILog logStream = LogManager.GetLogger("StreamData");
public override string ToString() { return string.Format("{0}({1})", ClassName, Cfg.ToString(-1)); }
#if TURA_SPECIAL
@@ -39,6 +45,19 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
public const int StartEndFilterSamplesCount2 = 20; /// StartEndFilterSamplesCount = 2 * StartEndFilterSamplesCount2 + 1
public const int FeatureVectorSize = 9;
private OptoHeadTest _optoHeadTest;
public OptoHeadTest OptoHeadTest
{
get
{
if (_optoHeadTest == null)
_optoHeadTest = new OptoHeadTest(this);
return _optoHeadTest;
}
set { _optoHeadTest = value; }
}
readonly IperlHeadCfg iperlHeadCfg;
@@ -101,8 +120,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
/// <summary>
/// Passed to OptoTelegramRaw.UpdateFromString(...)
/// </summary>
Int64 volumeRawExtLast;
Int64 timestampExtLast;
double volumeRawExtLast;
double timestampExtLast;
FlowDirectionDetection flowDirectionDetection;
@@ -358,7 +377,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
///
/// Timestamp from the opto telegram
///
private Int64 lastTimestamp;
private double lastTimestamp;
private double timestampSec;
private double timestampSec0;
@@ -381,7 +400,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
///
/// Volume of water from the opto telegram
///
private Int64 lastVolumeRaw; /// Last read raw volume
private double lastVolumeRaw; /// Last read raw volume
private double volumeLtr;
private double volumeLtr0;
@@ -442,7 +461,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
/// Check whether head is connected, working
try
{
OpenOptoSerialPort($"COM{iperlHeadCfg.OptoComPortNr}", 9600, Parity.None, 8, StopBits.One, Handshake.None);
OpenOptoSerialPort($"COM{iperlHeadCfg.OptoComPortNr}", 38400, Parity.None, 8, StopBits.One, Handshake.None);
CloseOptoSerialPort();
log.FatalFormat($"{Name} initialized: {this}");
}
@@ -587,10 +606,10 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
ResultCode = 0;
volumeLtr = 0;
volumeLtr0 = 0;
timestampSec = 0;
timestampSec0 = 0;
volumeLtr = Double.NaN;
volumeLtr0 = Double.NaN;
timestampSec = Double.NaN;
timestampSec0 = Double.NaN;
extraDataPath = null;
@@ -856,6 +875,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
endWMState = volumeLtr;
wmVolume = Math.Abs(endWMState - beginWMState);
wmPulses = (int)(wmVolume * (double)PulsesPerLtr + 0.5);
log.Debug("wmPulses = " + wmPulses + "wmVolume = " + wmVolume + "PulsesPerLtr = " + PulsesPerLtr + "");
wmRefPulses = StateMachine.ControlBoardMain.RefPulses;
wmTestTime = timestampSec - timestampSec0;
}
@@ -865,12 +885,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
if (DebugLevel == DebugMode.FailureDuringOperation) DebugLevel = DebugMode.Normal;
if (DebugLevel == DebugMode.Normal)
{
/// Open serial port: 9600 Bd, 8 data bits, 1 stop bit, no parity
/// Open serial port: 38400 Bd, 8 data bits, 1 stop bit, no parity
try
{
CloseOptoSerialPort();
optoSerialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBit);
optoSerialPort.Handshake = handshake;
optoSerialPort.NewLine = "\r\n";
optoSerialPort.Encoding = Encoding.ASCII; // or UTF8 if needed
optoSerialPort.Open();
log.FatalFormat($"{Name} OptoPort opened: {this}");
}
@@ -906,7 +928,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
try
{
OpenOptoSerialPort($"COM{iperlHeadCfg.OptoComPortNr}", 9600, Parity.None, 8, StopBits.One, Handshake.None);
OpenOptoSerialPort($"COM{iperlHeadCfg.OptoComPortNr}", 38400, Parity.None, 8, StopBits.One, Handshake.None);
}
catch (Exception)
{
@@ -954,6 +976,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
bool synchronized2;
string partOfTelegram;
DiagnosticLedParser parser = new DiagnosticLedParser(DiagnosticLedState.State4);
/// <summary>
/// Reads opto-datastream via serial port. Invoked from RunDeviceBefore()
///
@@ -973,86 +996,66 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
int nrBytes = optoSerialPort.BytesToRead;
if (nrBytes > 0)
{
char[] buffer = new char[nrBytes];
optoSerialPort.Read(buffer, 0, nrBytes);
string received = new string(buffer);
string line = optoSerialPort.ReadLine(); // string
byte[] bytes = optoSerialPort.Encoding.GetBytes(line);
log.Debug("ComPort: "+ OptoComPortNr +" OPTHO RX ← " + HexFormatter.ToSerialHex(bytes));
string allRcvd = partOfTelegram + received;
while (true)
try
{
int pos = allRcvd.IndexOf("\r\n");
/// CR+LF found
if (optoState == DataStreamState.ProcessAndSave)
{
DiagnosticLedState4Data data = (DiagnosticLedState4Data)parser.ParseLine(line, false);
//DiagnostigLedDataByUnit unitData = new DiagnostigLedDataByUnit(Common.Unit.m3, Common.Unit.m3, data);
int bufferIx = BufferIdx(optoDataCount);
if (pos < 0)
{
/// No CR+LF found, wait for more characters in the next invocation
partOfTelegram = allRcvd;
return;
}
else
{
/// CR+LF found
if (optoState == DataStreamState.ProcessAndSave)
if (synchronized)
{
int bufferIx = BufferIdx(optoDataCount);
optoData[bufferIx].Counter = optoDataCount;
optoData[bufferIx].SetFlags(OptoTelegramFlags.SyncError);
}
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[bufferIx].Counter = optoDataCount;
optoData[bufferIx].SetFlags(OptoTelegramFlags.SyncError);
}
synchronized = true;
}
else if (optoData[bufferIx].UpdateFromString(allRcvd.Substring(pos - OptoTelegramRaw.Length + 2),
optoDataCount,
Convert.ToSingle(Sequences.ProcessData.RefFlow.Val),
ref volumeRawExtLast, ref timestampExtLast))
{
/// CR+LF was found && (pos >= OptoTelegramRaw.Length - 2) && the telegram is OK
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
OptoTelegramReceived(optoDataCount, synchronized2, volumeRawExtLast, timestampExtLast);
synchronized2 = synchronized;
allRcvd = allRcvd.Substring(pos + 2);
}
else
{
/// CR+LF was found && (pos >= OptoTelegramRaw.Length - 2) but the telgram was not OK
optoData[bufferIx].Counter = optoDataCount;
optoDataCount++;
allRcvd = allRcvd.Substring(pos + 2);
}
if (data != null)
{
//TODO BUMI UNITS
// apply units
log.Debug($"OPTHO {OptoComPortNr} Parsed optho data:" + data.ToString());
logStream.Debug($"ID: {OptoComPortNr} " + data.ToString());
optoData[bufferIx].UpdateFromSmart(data, optoDataCount,
Convert.ToSingle(Sequences.ProcessData.RefFlow.Val), ref volumeRawExtLast,
ref timestampExtLast);
log.Debug("OPTHO UpdateFromSmart() volumeRawExtLast:" + volumeRawExtLast + " timestampExtLast:" + timestampExtLast);
/// CR+LF was found && (pos >= OptoTelegramRaw.Length - 2) && the telegram is OK
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
OptoTelegramReceived(optoDataCount, true, volumeRawExtLast,
timestampExtLast);
}
else
{
/// CR+LF was found && (pos >= OptoTelegramRaw.Length - 2) but the telgram was not OK
optoData[bufferIx].Counter = optoDataCount;
optoDataCount++;
}
else /// optoState == OptoState.Flush
optoDataCount++;
}
else /// optoState == OptoState.Flush
{
DiagnosticLedState4Data data = (DiagnosticLedState4Data)parser.ParseLine(line, false);
{
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.UpdateFromString(allRcvd.Substring(pos - OptoTelegramRaw.Length + 2),
0,
Convert.ToSingle(Sequences.ProcessData.RefFlow.Val),
ref volumeRawExtLast, ref timestampExtLast))
{
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
synchronized2 = synchronized;
allRcvd = allRcvd.Substring(pos + 2);
}
else
{
allRcvd = allRcvd.Substring(pos + 2);
}
flowDirectionDetection.WriteToFifo(volumeRawExtLast, timestampExtLast);
}
}
}
catch (Exception e)
{
}
//OnOptoReceived(this, new OptoReceivedEventArgs(s));
}
@@ -1069,43 +1072,40 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
string received = ".";
lock (this)
{
int nrBytes = optoSerialPort.BytesToRead;
if (nrBytes > 0)
{
char[] buffer = new char[nrBytes];
optoSerialPort.Read(buffer, 0, nrBytes);
received = new string(buffer);
}
string line = optoSerialPort.ReadLine(); // string
byte[] bytes = optoSerialPort.Encoding.GetBytes(line);
received = HexFormatter.ToSerialHex(bytes);
log.Debug("RX ← " + received);
}
return received;
}
void OptoTelegramReceived(int currentIx, bool async, Int64 volumeRawExt, Int64 timestampRawExt)
void OptoTelegramReceived(int currentIx, bool async, double volumeRawExt, double timestampRawExt)
{
currentTelegramIx = currentIx;
lastVolumeRaw = volumeRawExt;
lastTimestamp = timestampRawExt;
if (volumeLtr == 0 && volumeLtr0 == 0)
if (Double.IsNaN(volumeLtr) && Double.IsNaN(volumeLtr0))
{
volumeLtr = (double)lastVolumeRaw * ScalingFactor() / 16000.0;
volumeLtr = lastVolumeRaw;
volumeLtr0 = volumeLtr;
}
else
{
volumeLtr = (double)lastVolumeRaw * ScalingFactor() / 16000.0;
volumeLtr = lastVolumeRaw;
}
if (timestampSec == 0 && timestampSec0 == 0)
if (Double.IsNaN(timestampSec)&& Double.IsNaN(timestampSec0))
{
timestampSec = (double)lastTimestamp / 8192.0;
timestampSec = lastTimestamp;
timestampSec0 = timestampSec;
}
else
{
timestampSec = (double)lastTimestamp / 8192.0;
timestampSec = lastTimestamp;
}
}
@@ -1210,25 +1210,50 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
/// <returns>Filtered volume</returns>
double VolumeFromSamples(OptoTelegramRaw[] optoData, int optoDataCount, int unwrappedIx, double scalingFactor, int samplesCount2 = 0)
{
if (samplesCount2 < 0) samplesCount2 = 0;
if ((unwrappedIx - samplesCount2) < 0 || (unwrappedIx + samplesCount2) >= optoDataCount) return 0;
Int64 sum = 0;
for (int i = unwrappedIx - samplesCount2; i <= unwrappedIx + samplesCount2; i++)
log.Debug("-- Get VolumeFromSamples() --");
if (unwrappedIx >= optoDataCount)
{
int wrappedIx = BufferIdx(i);
if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
{
return 0;
}
sum += optoData[wrappedIx].VolumeRawExt;
log.Debug(
$"-- FAILED VolumeFromSamples() - unwrappedIx {unwrappedIx} >= optoDataCount{optoDataCount}--");
return 0;
}
int wrappedIx = BufferIdx(unwrappedIx);
return 0.0000625 * scalingFactor * sum / (double)(2 * samplesCount2 + 1);
if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
{
log.Debug($"-- Get VolumeFromSamples() - Quit because:{optoData[wrappedIx].Flags}--");
return 0;
}
log.Debug($"Valid data VolumeRawExt: {optoData[wrappedIx].VolumeRawExt}");
return optoData[wrappedIx].VolumeRawExt;
//
// if (samplesCount2 < 0) samplesCount2 = 0;
// if ((unwrappedIx - samplesCount2) < 0 || (unwrappedIx + samplesCount2) >= optoDataCount) return 0;
//
//
// Int64 sum = 0;
// for (int i = unwrappedIx - samplesCount2; i <= unwrappedIx + samplesCount2; i++)
// {
// int wrappedIx = BufferIdx(i);
//
// if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
// optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
// optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
// {
// return 0;
// }
//
// sum += optoData[wrappedIx].VolumeRawExt;
// }
//
// return 0.0000625 * scalingFactor * sum / (double)(2 * samplesCount2 + 1);
}
/// <summary>
@@ -1239,25 +1264,45 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
/// <returns>Filtered time</returns>
double TimeFromSamples(OptoTelegramRaw[] optoData, int optoDataCount, int unwrappedIx, int samplesCount2 = 0)
{
if (samplesCount2 < 0) samplesCount2 = 0;
if ((unwrappedIx - samplesCount2) < 0 || (unwrappedIx + samplesCount2) >= optoDataCount) return 0;
Int64 sum = 0;
for (int i = unwrappedIx - samplesCount2; i <= unwrappedIx + samplesCount2; i++)
log.Debug("-- Get TimeFromSamples() --");
if (unwrappedIx >= optoDataCount)
{
int wrappedIx = BufferIdx(i);
if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
{
return 0;
}
sum += optoData[wrappedIx].TimestampExt;
log.Debug(
$"-- FAILED TimeFromSamples() - unwrappedIx {unwrappedIx} >= optoDataCount{optoDataCount}--");
return 0;
}
int wrappedIx = BufferIdx(unwrappedIx);
return sum / (double)(8192 * (2 * samplesCount2 + 1));
if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
{
log.Debug($"-- Get TimeFromSamples() - Quit because:{optoData[wrappedIx].Flags}--");
return 0;
}
log.Debug($"Valid data TimestampExt: {optoData[wrappedIx].TimestampExt}");
return optoData[wrappedIx].TimestampExt;
// if (samplesCount2 < 0) samplesCount2 = 0;
// if ((unwrappedIx - samplesCount2) < 0 || (unwrappedIx + samplesCount2) >= optoDataCount) return 0;
//
// Int64 sum = 0;
// for (int i = unwrappedIx - samplesCount2; i <= unwrappedIx + samplesCount2; i++)
// {
// int wrappedIx = BufferIdx(i);
//
// if (optoData[wrappedIx].Flags != OptoTelegramFlags.OK &&
// optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestStart &&
// optoData[wrappedIx].Flags != OptoTelegramFlags.OK_TestEnd)
// {
// return 0;
// }
//
// sum += optoData[wrappedIx].TimestampExt;
// }
//
// return sum / (double)(8192 * (2 * samplesCount2 + 1));
}
/// <summary>
@@ -1476,5 +1521,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
return this;
}
}
}
@@ -3,6 +3,7 @@ using System.Threading;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using TBF.Rig.Sequences;
using TBF.Rig.TestMethods.iPerlCommunication.communication;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
@@ -78,13 +79,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
ListItem rfidListItem = new ListItem();
rfidListItem.Attributes.Add("style", "font-weight:bold");
bool isTestModeSuccessful = false;
switch (rfidCommandComboBox.SelectedValue)
{
case "ReadPCB":
rfidListItem.Text = $"PCB: {OpticalHeadTest.ReadRequest_PCB(iPerlHead)}";
rfidListItem.Text = $"PCB: {iPerlHead.OptoHeadTest.ReadRequest_PCB()}";
break;
case "SetTestMode":
rfidListItem.Text = OpticalHeadTest.SetTestMode(iPerlHead);
rfidListItem.Text = iPerlHead.OptoHeadTest.SetTestMode(ref isTestModeSuccessful);
optoListBox.Items.Clear();
stopWorkerThread = false;
optoThread = new Thread(OptoWorker);
@@ -95,7 +97,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
}
break;
case "SetActiveMode":
rfidListItem.Text = OpticalHeadTest.SetActiveMode(iPerlHead);
rfidListItem.Text = iPerlHead.OptoHeadTest.SetActiveMode(ref isTestModeSuccessful);
stopWorkerThread = true;
iPerlHead.StopDataStreamProcessing(); // close opto port
break;
@@ -1,5 +1,8 @@
using System;
using System.IO;
using System.Linq;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed;
using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons;
namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
{
@@ -9,9 +12,32 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead
internal static int ReadRequest(TestMethodCfg cfg, IperlHead iperlHead, MessageID messageID, int offset, int length, out byte[] buffer)
{
byte[] configurationBuffer = new byte[ConfigStruct.Length] { 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 160, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
string pcbStr = iperlHead.RfidComPortNr.ToString().PadRight(10,'0') + iperlHead.Position.ToString("D2");
long decVal = Convert.ToInt64(pcbStr);
string nHexStr = decVal.ToString("X4");
ConfigStruct configStruct = new ConfigStruct();
configStruct.PCBNumberString = nHexStr;
configStruct.StatusMode = ProtocolStatuses.Active;
configStruct.OpthoStatusMode = DiagnosticLedState.State4;
configStruct.Version = "Good Version: 123456";
byte[] configurationBuffer;
using (var ms = new MemoryStream())
using (var writer = new BinaryWriter(ms))
{
configStruct.WriteBinary(writer);
writer.Flush();
configurationBuffer = ms.ToArray(); // ← this is the binary output
}
byte[] calibrationBuffer = new byte[CalibrationStructV4.Length] { 3, 0, 150, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 150, 10 };
buffer = new byte[length];
return 0;//switch off
if (messageID == MessageID.Configuration)
{
@@ -1,18 +0,0 @@
///
/// Copyright (c) 2015 Sensus Metering Systems
/// Author: Milan Hanajík
///
using System;
namespace TBF.Rig.Uni.SharedDialogs.iPerlCommunication
{
public class AllCompletedEventArgs : EventArgs
{
public string CommMessage;
public AllCompletedEventArgs(string commMessage)
{
this.CommMessage = commMessage;
}
}
}
@@ -1,41 +0,0 @@
///
/// Copyright (c) 2015-2019 Sensus Metering Systems
/// Author: Milan Hanajík
///
using System;
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
using TBF.Rig.RegisterReaders.iPerlReaderUNI.comminication;
namespace TBF.Rig.Uni.SharedDialogs.iPerlCommunication
{
public class CommCompletedEventArgs : EventArgs
{
public int ThreadId;
public int WMNr0; /// 0-based water meter position
public IPerlReader Ihead;
public Results.Entities.WaterMeter Wm;
public string CommMessage;
public CommErr CommErr;
public CommCompletedEventArgs(int threadId, int wmNr0, IPerlReader ihead, Results.Entities.WaterMeter wm, string commMessage, CommErr commErr)
{
this.ThreadId = threadId;
this.WMNr0 = wmNr0;
this.Ihead = ihead;
this.Wm = wm;
this.CommMessage = commMessage;
this.CommErr = commErr;
}
public override string ToString()
{
return string.Format("Thread={0} WMNr0={1} IHead={2} WM={3} CommMsg={4} CommErr={5}",
ThreadId,
WMNr0,
(Ihead != null) ? Ihead.Name : "null",
Wm.WMPosition,
(CommMessage != null) ? CommMessage : "null",
CommErr);
}
}
}

Some files were not shown because too many files have changed in this diff Show More