Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
302a7a682c | ||
|
|
e4b42b5b51 | ||
|
|
234bd39ed5 | ||
|
|
59cd5f9dde | ||
|
|
2fd2697e3b | ||
|
|
f51fd4709e | ||
|
|
d5c50189ba | ||
|
|
5a1db14e2a | ||
|
|
5ea88265b9 | ||
|
|
2b9a207342 | ||
|
|
c4b61d885b |
@@ -34,8 +34,6 @@ MergeResultsDBs/bin/
|
||||
MergeResultsDBs/obj/
|
||||
NfcC7_Dll/bin/
|
||||
NfcC7_Dll/obj/
|
||||
NfcC7_DLL.Tests/bin/
|
||||
NfcC7_DLL.Tests/obj/
|
||||
OrderManagement/bin/
|
||||
OrderManagement/obj/
|
||||
ProductionTracing/bin/
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<WarningLevel>0</WarningLevel>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="JetBrains.Annotations" Version="2023.3.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
|
||||
+6
-1
@@ -11,6 +11,7 @@ using NHibernate.Cfg;
|
||||
using NHibernate.Tool.hbm2ddl;
|
||||
using Common;
|
||||
using Results.Entities;
|
||||
using Results.Entities.helpers;
|
||||
|
||||
namespace Results
|
||||
{
|
||||
@@ -107,7 +108,11 @@ namespace Results
|
||||
throw new Exception("Connection string was not specified");
|
||||
}
|
||||
|
||||
if (SessionFactory == null) SessionFactory = CreateSessionFactory();
|
||||
if (SessionFactory == null)
|
||||
{
|
||||
DatabaseMigrationHelper.EnsureSchema(dbType, connectionString);
|
||||
SessionFactory = CreateSessionFactory();
|
||||
}
|
||||
|
||||
return SessionFactory.OpenSession();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
using System;
|
||||
using Common;
|
||||
using log4net;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
namespace Results.Entities.helpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Applies explicit, backwards-compatible results DB migrations before the
|
||||
/// first NHibernate session factory is created.
|
||||
/// </summary>
|
||||
public static class DatabaseMigrationHelper
|
||||
{
|
||||
private static readonly ILog log = LogManager.GetLogger(typeof(DatabaseMigrationHelper));
|
||||
|
||||
public static void EnsureSchema(DBType dbType, string connectionString)
|
||||
{
|
||||
switch (dbType)
|
||||
{
|
||||
case DBType.MySql:
|
||||
EnsureMySqlSchema(connectionString);
|
||||
break;
|
||||
case DBType.SQLite:
|
||||
EnsureSQLiteSchema(connectionString);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureMySqlSchema(string connectionString)
|
||||
{
|
||||
using (var conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
// Added by newer MeterTestRslt mapping; older customer DBs do
|
||||
// not contain it and otherwise reject the entire batch insert.
|
||||
EnsureColumnMySql(conn, "MeterTestRslt", "PulsesPerKilogram", "DOUBLE NOT NULL DEFAULT 0");
|
||||
EnsureColumnMySql(conn, "MeterTestRslt", "FlipMode", "INT NULL");
|
||||
EnsureColumnMySql(conn, "MeterTestRslt", "ExtraDataPath", "VARCHAR(255) NULL");
|
||||
EnsureMeterTestResultExtraColumnsMySql(conn);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureMeterTestResultExtraColumnsMySql(MySqlConnection conn)
|
||||
{
|
||||
for (int index = 1; index <= 9; index++)
|
||||
{
|
||||
EnsureColumnMySql(conn, "MeterTestRslt", "X" + index, "FLOAT NOT NULL DEFAULT 0");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureColumnMySql(
|
||||
MySqlConnection conn,
|
||||
string tableName,
|
||||
string columnName,
|
||||
string columnDefinition)
|
||||
{
|
||||
using (var transaction = conn.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
bool exists;
|
||||
using (var cmd = conn.CreateCommand())
|
||||
{
|
||||
cmd.Transaction = transaction;
|
||||
cmd.CommandText = @"
|
||||
SELECT COUNT(*)
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = @tableName
|
||||
AND COLUMN_NAME = @columnName";
|
||||
cmd.Parameters.AddWithValue("@tableName", tableName);
|
||||
cmd.Parameters.AddWithValue("@columnName", columnName);
|
||||
exists = Convert.ToInt32(cmd.ExecuteScalar()) > 0;
|
||||
}
|
||||
|
||||
if (!exists)
|
||||
{
|
||||
using (var alter = conn.CreateCommand())
|
||||
{
|
||||
alter.Transaction = transaction;
|
||||
alter.CommandText = "ALTER TABLE `" + tableName + "` ADD COLUMN `" +
|
||||
columnName + "` " + columnDefinition;
|
||||
alter.ExecuteNonQuery();
|
||||
log.WarnFormat("Results DB migration: added {0}.{1} ({2}).",
|
||||
tableName, columnName, columnDefinition);
|
||||
}
|
||||
}
|
||||
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureSQLiteSchema(string databaseFile)
|
||||
{
|
||||
using (var conn = new System.Data.SQLite.SQLiteConnection("Data Source=" + databaseFile))
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
EnsureColumnSQLite(conn, "MeterTestRslt", "PulsesPerKilogram", "REAL NOT NULL DEFAULT 0");
|
||||
EnsureColumnSQLite(conn, "MeterTestRslt", "FlipMode", "INTEGER NULL");
|
||||
EnsureColumnSQLite(conn, "MeterTestRslt", "ExtraDataPath", "TEXT NULL");
|
||||
EnsureMeterTestResultExtraColumnsSQLite(conn);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureMeterTestResultExtraColumnsSQLite(System.Data.SQLite.SQLiteConnection conn)
|
||||
{
|
||||
for (int index = 1; index <= 9; index++)
|
||||
{
|
||||
EnsureColumnSQLite(conn, "MeterTestRslt", "X" + index, "REAL NOT NULL DEFAULT 0");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureColumnSQLite(
|
||||
System.Data.SQLite.SQLiteConnection conn,
|
||||
string tableName,
|
||||
string columnName,
|
||||
string columnDefinition)
|
||||
{
|
||||
bool exists = false;
|
||||
using (var cmd = conn.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = "PRAGMA table_info(" + tableName + ")";
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
while (reader.Read())
|
||||
{
|
||||
if (string.Equals(reader["name"].ToString(), columnName,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
exists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!exists)
|
||||
{
|
||||
using (var alter = conn.CreateCommand())
|
||||
{
|
||||
alter.CommandText = "ALTER TABLE " + tableName + " ADD COLUMN " +
|
||||
columnName + " " + columnDefinition;
|
||||
alter.ExecuteNonQuery();
|
||||
log.WarnFormat("Results DB migration: added {0}.{1} ({2}).",
|
||||
tableName, columnName, columnDefinition);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,9 @@
|
||||
<Reference Include="NHibernate">
|
||||
<HintPath>..\packages\NHibernate.4.0.4.4000\lib\net40\NHibernate.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Data.SQLite, Version=2.0.3.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Data.SQLite.2.0.3\lib\net471\System.Data.SQLite.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Drawing" />
|
||||
@@ -69,6 +72,7 @@
|
||||
<Compile Include="DBase.cs" />
|
||||
<Compile Include="Entities\Batch.cs" />
|
||||
<Compile Include="Entities\Components.cs" />
|
||||
<Compile Include="Entities\helpers\DatabaseMigrationHelper.cs" />
|
||||
<Compile Include="Entities\MeterTestRslt.cs" />
|
||||
<Compile Include="Entities\PurchaseBox.cs" />
|
||||
<Compile Include="Entities\PurchaseOrder.cs" />
|
||||
@@ -265,4 +269,4 @@
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
|
||||
@@ -7,7 +7,7 @@
|
||||
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(UserProfile)\.nuget\packages\</NuGetPackageRoot>
|
||||
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\micha\.nuget\packages\</NuGetPackageFolders>
|
||||
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
|
||||
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">7.0.0</NuGetToolVersion>
|
||||
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.14.0</NuGetToolVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<SourceRoot Include="C:\Users\micha\.nuget\packages\" />
|
||||
|
||||
@@ -106,13 +106,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LabelPrinting", "LabelPrint
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TBFTests", "TBFTests\TBFTests.csproj", "{77EB589F-C670-4489-AAD6-2A3C02061FD1}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AppDiagnostic", "AppDiagnostic\AppDiagnostic.csproj", "{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3} = {8F942729-F454-4C99-BA6C-746962065AE3}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedComponents", "SharedComponents\SharedComponents.csproj", "{8F942729-F454-4C99-BA6C-746962065AE3}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sensus.iPerl.RfidCom", "..\iPerlHead\Sensus.iPerl.RfidCom\Sensus.iPerl.RfidCom.csproj", "{A3E14180-7F00-42E5-94A9-8DB62EAD6EE8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sensus.iPerl.TestConsole", "..\iPerlHead\Sensus.iPerl.TestConsole\Sensus.iPerl.TestConsole.csproj", "{5025ED8B-A94F-4E58-8BE0-68481B061609}"
|
||||
@@ -121,8 +114,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NfcS5_DLL", "..\NfcS5_DLL\N
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NfcC7_DLL", "NfcC7_DLL\NfcC7_DLL.csproj", "{53E75979-B530-4805-8FC9-B314F14A62BE}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NfcC7_DLL.Tests", "NfcC7_DLL.Tests\NfcC7_DLL.Tests.csproj", "{715605C5-568B-48D6-9C09-2DC5F2E81F66}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -483,30 +474,6 @@ Global
|
||||
{77EB589F-C670-4489-AAD6-2A3C02061FD1}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{77EB589F-C670-4489-AAD6-2A3C02061FD1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{77EB589F-C670-4489-AAD6-2A3C02061FD1}.Release|x86.Build.0 = Release|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{FA9ABAD1-7184-4295-ADE8-D44F2E3DE6B2}.Release|x86.Build.0 = Release|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{8F942729-F454-4C99-BA6C-746962065AE3}.Release|x86.Build.0 = Release|Any CPU
|
||||
{A3E14180-7F00-42E5-94A9-8DB62EAD6EE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A3E14180-7F00-42E5-94A9-8DB62EAD6EE8}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A3E14180-7F00-42E5-94A9-8DB62EAD6EE8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
@@ -555,18 +522,6 @@ Global
|
||||
{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
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{715605C5-568B-48D6-9C09-2DC5F2E81F66}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -19,6 +19,9 @@ using System.Runtime.InteropServices;
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
//Visibility to TBFTests internal classes
|
||||
[assembly: InternalsVisibleTo("TBFTests")]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("2c13538e-15ee-48b2-af0f-2c95afb67186")]
|
||||
|
||||
@@ -29,5 +32,5 @@ using System.Runtime.InteropServices;
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
[assembly: AssemblyVersion("3.9.2149.4")]
|
||||
[assembly: AssemblyFileVersion("3.9.2149.4")]
|
||||
[assembly: AssemblyVersion("3.9.2206.0")]
|
||||
[assembly: AssemblyFileVersion("3.9.2206.0")]
|
||||
|
||||
@@ -3,3 +3,13 @@
|
||||
| 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 |
|
||||
| 3.9.2149.1 | General release | Version iteration | Assembly and file version increment. |
|
||||
| 3.9.2149.2 | Poseidon register reader | Poseidon pulse and timing handling | Added reference-pulse reading in `Run()` and improved Poseidon timing/task tracking. |
|
||||
| 3.9.2149.4 | Mass collection / Poseidon start-stop | Mass collection update | Refactored standing-start mass collection, extended Poseidon start/end data-entry configuration and improved dialog/task handling. |
|
||||
| 3.9.2200.1 | Test infrastructure | TBF test assembly access | Added `InternalsVisibleTo` support for `TBFTests`. |
|
||||
| 3.9.2201.1 | Poseidon CLI | Poseidon CLI configuration | Added macro descriptions, refined serial-port/CLI argument configuration and extended CLI test coverage. |
|
||||
| 3.9.2202.1 | Poseidon CLI | CLI release iteration | Assembly and file version increment for the Poseidon CLI workstream. |
|
||||
| 3.9.2203.1 | Poseidon CLI / smart-meter sequence | CLI test and configuration update | Updated CLI executable test setup, serial-port default responses and smart-meter component-name handling. |
|
||||
| 3.9.2204.1 | Morrisville / Poseidon CLI | Morrisville CLI diagnostics | Restored lost 2204 versioning, added detailed CLI command/response logging and used a fixed CLI directory for deployment. |
|
||||
| 3.9.2205.1 | Morrisville / Poseidon CLI / Results DB | Poseidon read diagnostics and results DB migration | Improved Poseidon CLI execution and diagnostics (fixed CLI working directory, exit code/stdout/stderr capture, JSON/NFC/reading validation and culture-independent decimal parsing). Added reader-cycle and fake-CLI test coverage. Prevented a device/CLI error while changing the legacy optical-head mode from crashing the UI. Results DB now creates missing `MeterTestRslt` compatibility columns (`FlipMode`, `ExtraDataPath`, `X1`-`X9`) automatically for MySQL and SQLite before results are saved. |
|
||||
| 3.9.2206.0 | Morrisville / Poseidon CLI / Results DB | Poseidon start/end rearm and simulation isolation | Fixed the Poseidon start/end read cycle so a completed START reader is armed again once for END, preventing reused START values or skipped END CLI calls. Added trace logging for CLI response, dialog prefill and confirmed dialog values. In `Simulate` mode, `PoseidonCmdStartStop` now always runs the fixed `C:\TBF\Cli\cmdSleepTest.exe` instead of the configured physical Hat CLI. Added regression tests for customer CLI JSON responses, decimal comma/dot and non-zero readings, start/end dialog transfer, full/reduced reader cycles and simulation CLI selection. Extended results-schema migration with `MeterTestRslt.PulsesPerKilogram`. |
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
/// Copyright (c) 2021-2023 Sensus Slovensko a.s.
|
||||
///
|
||||
using System;
|
||||
using Common;
|
||||
using log4net;
|
||||
using TBF.Rig.Sequences;
|
||||
|
||||
@@ -12,10 +11,6 @@ namespace TBF.Rig.ControlBoard.Uni
|
||||
{
|
||||
private static readonly ILog log = LogManager.GetLogger(typeof(FlyingStartStopTestOp));
|
||||
public override string ToString() { return string.Format("FlyingStartStopTestOp()"); }
|
||||
|
||||
private DateTime startTimeForSimulation;
|
||||
private bool simulationTimerStarted = false;
|
||||
|
||||
|
||||
/// Arguments of the constructor
|
||||
readonly UniCB uniCB;
|
||||
@@ -128,28 +123,6 @@ namespace TBF.Rig.ControlBoard.Uni
|
||||
{
|
||||
log.DebugFormat("Op.Run() opState={0}", opState);
|
||||
|
||||
//Simulation of processing time 25 seconds
|
||||
if (uniCB.DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
if (opState == OpState.StartingTest)
|
||||
{
|
||||
startTimeForSimulation = DateTime.Now;
|
||||
simulationTimerStarted = false;
|
||||
}
|
||||
if (opState == OpState.TestInProgress)
|
||||
{
|
||||
if (!simulationTimerStarted)
|
||||
{
|
||||
startTimeForSimulation = DateTime.Now;
|
||||
simulationTimerStarted = true;
|
||||
}
|
||||
else if (DateTime.Now - startTimeForSimulation > TimeSpan.FromSeconds(25))
|
||||
{
|
||||
return Event.TestCompleted;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch (opState)
|
||||
{
|
||||
case OpState.StartingTest:
|
||||
|
||||
@@ -17,8 +17,7 @@ using TBF.Boxes;
|
||||
using TBF.Rig.GenericDevices;
|
||||
using TBF.Rig.Sequences;
|
||||
using TBF.UiBridge;
|
||||
using AppDiagnostic;
|
||||
using SharedComponents;
|
||||
|
||||
|
||||
namespace TBF.Rig.ControlBoard.Uni
|
||||
{
|
||||
|
||||
@@ -268,10 +268,16 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
{
|
||||
dlg.WMStartState[item] = poseidonReader.BeginWMState;
|
||||
dlg.WMStartStateStr[item] = poseidonReader.BeginWMState.ToString();
|
||||
log.InfoFormat("Poseidon dialog prefill: phase=Start, WM{0}, reader={1}, value={2}",
|
||||
item + 1, poseidonReader.Name, dlg.WMStartState[item]);
|
||||
}
|
||||
|
||||
if (currentOp == CurrentOp.ReadDatastream_EndStates)
|
||||
{
|
||||
dlg.WMEndState[item] = poseidonReader.EndWMState;
|
||||
log.InfoFormat("Poseidon dialog prefill: phase=End, WM{0}, reader={1}, value={2}",
|
||||
item + 1, poseidonReader.Name, dlg.WMEndState[item]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,31 +332,10 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (modelessDlg is TestStartEndForm && currentOp == CurrentOp.ReadDatastream_StartStates)
|
||||
else if (modelessDlg is TestStartEndForm)
|
||||
{
|
||||
/// Fixed start test - start
|
||||
TestStartEndForm dlg = (modelessDlg as TestStartEndForm);
|
||||
if (dlg != null)
|
||||
{
|
||||
for (int i = 0; i < dlg.WaterMetersCount; i++)
|
||||
{
|
||||
wmStartState[i] = dlg.WMStartState[i];
|
||||
wmStartStateStr[i] = dlg.WMStartStateStr[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (modelessDlg is TestStartEndForm && currentOp == CurrentOp.ReadDatastream_EndStates)
|
||||
{
|
||||
/// Fixed start test - end
|
||||
TestStartEndForm dlg = (modelessDlg as TestStartEndForm);
|
||||
if (dlg != null)
|
||||
{
|
||||
for (int i = 0; i < dlg.WaterMetersCount; i++)
|
||||
{
|
||||
wmEndState[i] = dlg.WMEndState[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
StoreAcceptedDialogValues((TestStartEndForm)modelessDlg);
|
||||
}
|
||||
resultSaved = true;
|
||||
modelessDlg = null;
|
||||
}
|
||||
@@ -358,6 +343,36 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
return Event.ModelessFormClosed; /// Form closed
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies values confirmed by the Poseidon start/end dialog into the
|
||||
/// data-entry state used later by the result calculation.
|
||||
/// </summary>
|
||||
private void StoreAcceptedDialogValues(TestStartEndForm dlg)
|
||||
{
|
||||
if (dlg == null)
|
||||
return;
|
||||
|
||||
if (currentOp == CurrentOp.ReadDatastream_StartStates)
|
||||
{
|
||||
for (int i = 0; i < dlg.WaterMetersCount; i++)
|
||||
{
|
||||
wmStartState[i] = dlg.WMStartState[i];
|
||||
wmStartStateStr[i] = dlg.WMStartStateStr[i];
|
||||
log.InfoFormat("Poseidon dialog accepted: phase=Start, WM{0}, text='{1}', value={2}",
|
||||
i + 1, wmStartStateStr[i], wmStartState[i]);
|
||||
}
|
||||
}
|
||||
else if (currentOp == CurrentOp.ReadDatastream_EndStates)
|
||||
{
|
||||
for (int i = 0; i < dlg.WaterMetersCount; i++)
|
||||
{
|
||||
wmEndState[i] = dlg.WMEndState[i];
|
||||
log.InfoFormat("Poseidon dialog accepted: phase=End, WM{0}, value={1}",
|
||||
i + 1, wmEndState[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stop this operation</summary>
|
||||
public void Stop()
|
||||
{
|
||||
@@ -433,35 +448,45 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
|| (currentOp == CurrentOp.ReadDatastream_EndStates))
|
||||
{
|
||||
bool finishedReading = regReaders == null; // we can work only with register readers
|
||||
List<IPoseidonReadOperation> poseidonReaders = new List<IPoseidonReadOperation>();
|
||||
if (regReaders != null)
|
||||
{
|
||||
foreach (var iRegReader in regReaders)
|
||||
{
|
||||
PoseidonReader poseidonReader = iRegReader as PoseidonReader;
|
||||
if (poseidonReader != null)
|
||||
{
|
||||
poseidonReader.SetCliLogging(CliLogging);
|
||||
poseidonReaders.Add(new PoseidonReaderOperation(poseidonReader));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var phaseRunner = new PoseidonReadPhaseRunner(
|
||||
currentOp == CurrentOp.ReadDatastream_StartStates);
|
||||
while (!finishedReading) //TODO BUMI lock - fuck ?
|
||||
{
|
||||
bool bAllReadersFinished = true;
|
||||
foreach (var iRegReader in regReaders )
|
||||
foreach (IPoseidonReadOperation poseidonReader in poseidonReaders)
|
||||
{
|
||||
if (iRegReader is PoseidonReader)
|
||||
if (poseidonReader.IsNotStarted || poseidonReader.IsFinished)
|
||||
log.DebugFormat("Poseidon read: arming {0} for {1}, previous state finished={2}",
|
||||
currentOp, poseidonReader.Name, poseidonReader.IsFinished);
|
||||
}
|
||||
|
||||
bool bAllReadersFinished = phaseRunner.RunIteration(poseidonReaders);
|
||||
foreach (IPoseidonReadOperation poseidonReader in poseidonReaders)
|
||||
{
|
||||
if (poseidonReader.IsFinished)
|
||||
{
|
||||
PoseidonReader poseidonReader = (iRegReader as PoseidonReader);
|
||||
if(poseidonReader == null)
|
||||
continue;
|
||||
poseidonReader.SetCliLogging(CliLogging);
|
||||
if (!(poseidonReader.CurrentOp == PoseidonReader.CurrentPoseidonOp.ReadDatastream_Done
|
||||
|| poseidonReader.CurrentOp == PoseidonReader.CurrentPoseidonOp.ReadDatastream_Running))
|
||||
{
|
||||
poseidonReader.SetCurrentOp((currentOp == CurrentOp.ReadDatastream_StartStates)?
|
||||
PoseidonReader.CurrentPoseidonOp.ReadDataStream_Start :
|
||||
PoseidonReader.CurrentPoseidonOp.ReadDataStream_End);
|
||||
}
|
||||
/// Send start data stream
|
||||
poseidonReader.Run();
|
||||
if (!(poseidonReader.CurrentOp == PoseidonReader.CurrentPoseidonOp.Done
|
||||
|| poseidonReader.CurrentOp == PoseidonReader.CurrentPoseidonOp.Error))
|
||||
{
|
||||
bAllReadersFinished = false;
|
||||
}
|
||||
if (poseidonReader.HasError)
|
||||
log.ErrorFormat("Poseidon read: {0} completed with Error during {1}", poseidonReader.Name, currentOp);
|
||||
else
|
||||
log.DebugFormat("Poseidon read: {0} completed during {1}", poseidonReader.Name, currentOp);
|
||||
}
|
||||
}
|
||||
if (bAllReadersFinished)
|
||||
{
|
||||
log.DebugFormat("Poseidon read: all readers finished for {0}", currentOp);
|
||||
finishedReading = true;
|
||||
}
|
||||
else
|
||||
|
||||
@@ -144,6 +144,9 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
|
||||
private void SetUiBusy(bool busy, long deltaTime = -1)
|
||||
{
|
||||
log.DebugFormat("Poseidon UI: SetUiBusy busy={0}, deltaTime={1}, enabledTextBoxes={2}",
|
||||
busy, deltaTime, enabledTextBoxes.Count);
|
||||
|
||||
// show wait cursor for form and children
|
||||
this.UseWaitCursor = busy;
|
||||
|
||||
@@ -290,10 +293,15 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
// Ensure we are on the UI thread
|
||||
if (InvokeRequired)
|
||||
{
|
||||
log.DebugFormat("Poseidon UI: queue UpdateValues startValue={0}, enableEdit={1}, deltaTime={2}",
|
||||
stratValue, enableEdit, deltaTime);
|
||||
BeginInvoke(new Action(() => UpdateValues(stratValue, enableEdit)));
|
||||
return;
|
||||
}
|
||||
|
||||
log.DebugFormat("Poseidon UI: UpdateValues on UI thread startValue={0}, enableEdit={1}, deltaTime={2}",
|
||||
stratValue, enableEdit, deltaTime);
|
||||
|
||||
for (int i = 0; i < TextBoxesCount; i++)
|
||||
{
|
||||
if (stratValue)
|
||||
@@ -317,6 +325,7 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
if (enableEdit)
|
||||
{
|
||||
SetUiBusy(false, deltaTime);
|
||||
log.Debug("Poseidon UI: values applied and dialog released from Loading...");
|
||||
}
|
||||
// if you also need to enable/disable editing, do it here,
|
||||
// it's now safely on the UI thread.
|
||||
@@ -345,6 +354,8 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
if (endTextBoxes[i].Visible && endTextBoxes[i].Enabled)
|
||||
{
|
||||
WMEndState[i] = Utils.ParseUDouble(endTextBoxes[i].Text);
|
||||
log.InfoFormat("Poseidon dialog OK: phase=End, WM{0}, enteredText='{1}', parsedValue={2}",
|
||||
i + 1, endTextBoxes[i].Text, WMEndState[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -356,6 +367,8 @@ namespace TBF.Rig.DataEntry.PoseidonCmd
|
||||
{
|
||||
WMStartStateStr[i] = startTextBoxes[i].Text;
|
||||
WMStartState[i] = Utils.ParseUDouble(startTextBoxes[i].Text);
|
||||
log.InfoFormat("Poseidon dialog OK: phase=Start, WM{0}, enteredText='{1}', parsedValue={2}",
|
||||
i + 1, startTextBoxes[i].Text, WMStartState[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,42 +3,16 @@
|
||||
///
|
||||
|
||||
using System;
|
||||
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.CommonRR.IPerl.communication
|
||||
{
|
||||
public class OptoReceivedEventArgs : EventArgs
|
||||
{
|
||||
public string Data;
|
||||
public WaterMetrologyData WaterMetrologyData;
|
||||
public byte[] RawData;
|
||||
|
||||
public OptoReceivedEventArgs(string data)
|
||||
{
|
||||
this.Data = data;
|
||||
WaterMetrologyData = null;
|
||||
RawData = null;
|
||||
}
|
||||
|
||||
public OptoReceivedEventArgs(string data, WaterMetrologyData waterMetrologyData)
|
||||
{
|
||||
this.Data = data;
|
||||
this.WaterMetrologyData = waterMetrologyData;
|
||||
RawData = null;
|
||||
}
|
||||
|
||||
public OptoReceivedEventArgs(byte[] data)
|
||||
{
|
||||
this.RawData = data;
|
||||
Data = null;
|
||||
WaterMetrologyData = null;
|
||||
}
|
||||
|
||||
public OptoReceivedEventArgs(WaterMetrologyData data)
|
||||
{
|
||||
WaterMetrologyData = data;
|
||||
Data = null;
|
||||
RawData = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace TBF.Rig.RegisterReaders.IPerlReader
|
||||
public override XmlSerializer GetSerializer() { return Serializer; }
|
||||
public IComponentCfgCtrl GetControl(IList<Component> cmpntEntities)
|
||||
{
|
||||
return new iPerlASICReader.IPerlUniCfgCtrl();
|
||||
return new IPerlUniCfgCtrl();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -58,7 +58,7 @@ namespace TBF.Rig.RegisterReaders.IPerlReader
|
||||
muxBoardNrTextBox.Text = config.MuxBoardNr.ToString();
|
||||
groupTextBox.Text = config.Group.ToString();
|
||||
comboBoxCommunicationInterface.SelectedItem = config.CommunicationInterface.ToString();
|
||||
tabPage2.Controls.Add(new iPerlASICReader.IperlASICUniHeadTestCtrl(config));
|
||||
tabPage2.Controls.Add(new IperlUniHeadTestCtrl(config));
|
||||
}
|
||||
|
||||
public void Unlock()
|
||||
|
||||
@@ -2,7 +2,6 @@ using System;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
using TBF.Rig.RegisterReaders.CommonRR.IPerl.communication;
|
||||
using TBF.Rig.RegisterReaders.IPerlReader.implementations;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI.common;
|
||||
using TBF.Rig.RegisterReaders.PoseidonReader.implementations;
|
||||
@@ -21,7 +20,7 @@ namespace TBF.Rig.RegisterReaders.IPerlReader
|
||||
|
||||
public IperlUniHeadTestCtrl(iPerlReaderUNI.IPerlCfg config)
|
||||
{
|
||||
this._ctrl = new IPerlImplHeadTestCtrl();
|
||||
this._ctrl = new PoseidonImplHeadTestCtrl();
|
||||
Ctrl.config = config;
|
||||
InitializeComponent();
|
||||
if (config == null) return;
|
||||
|
||||
@@ -4,7 +4,6 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Web.UI.WebControls;
|
||||
using System.Windows.Forms;
|
||||
using Common;
|
||||
using TBF.Rig.Generic;
|
||||
using TBF.Rig.RegisterReaders.CommonRR.IPerl.communication;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI.common;
|
||||
@@ -38,51 +37,35 @@ namespace TBF.Rig.RegisterReaders.IPerlReader.implementations
|
||||
optoThread.Abort();
|
||||
}
|
||||
}
|
||||
|
||||
private const string StrReadPcbCmd = "ReadPCB";
|
||||
private const string StrSetTestModeCmd = "SetTestMode";
|
||||
private const string StrSetActiveModeCmd = "SetActiveMode";
|
||||
private const string StrReadOptoDataCmd = "ReadOptoData";
|
||||
private const string StrStopReadOptoDataCmd = "StopReadOptoData";
|
||||
private const string StrResetNfcHeadCmd = "ResetNfcHead";
|
||||
private const string StrSetNfcHeadCmd = "SetNfcHead";
|
||||
private const string StrSetRfidHeadCmd = "SetRfidHead";
|
||||
private const string StrEmptyCmd = "";
|
||||
|
||||
public enum Operations
|
||||
{
|
||||
[Description(StrReadPcbCmd)]ReadPcbCmd,
|
||||
[Description(StrSetTestModeCmd)]SetTestModeCmd,
|
||||
[Description(StrSetActiveModeCmd)]SetActiveModeCmd,
|
||||
[Description(StrReadOptoDataCmd)]ReadOptoDataCmd,
|
||||
[Description(StrStopReadOptoDataCmd)]StopReadOptoDataCmd,
|
||||
[Description(StrResetNfcHeadCmd)]ResetNfcHeadCmd,
|
||||
[Description(StrSetNfcHeadCmd)]SetNfcHeadCmd,
|
||||
[Description(StrSetRfidHeadCmd)]SetRfidHeadCmd,
|
||||
[Description(StrEmptyCmd)]EmptyCmd
|
||||
}
|
||||
|
||||
|
||||
private const string ReadPCBCmd = "ReadPCB";
|
||||
private const string SetTestModeCmd = "SetTestMode";
|
||||
private const string SetActiveModeCmd = "SetActiveMode";
|
||||
private const string ReadOptoDataCmd = "ReadOptoData";
|
||||
private const string StopReadOptoDataCmd = "StopReadOptoData";
|
||||
private const string ResetNfcHeadCmd = "ResetNfcHead";
|
||||
private const string SetNfcHeadCmd = "SetNfcHead";
|
||||
private const string SetRfidHeadCmd = "SetRfidHead";
|
||||
private const string EmptyCmd = "";
|
||||
|
||||
private static readonly Dictionary<string, Operations> ItemsForIperlOperations = new Dictionary<string, Operations>
|
||||
private static readonly Dictionary<string, string> ItemsForIperlOperations = new Dictionary<string, string>
|
||||
{
|
||||
{"Read PCB", Operations.ReadPcbCmd},
|
||||
{"Set Test Mode", Operations.SetTestModeCmd},
|
||||
{"Set Active Mode", Operations.SetActiveModeCmd},
|
||||
{"Read PCB", ReadPCBCmd},
|
||||
{"Set Test Mode", SetTestModeCmd},
|
||||
{"Set Active Mode", SetActiveModeCmd},
|
||||
#if DEBUG
|
||||
{"Start Read Opto Data", Operations.ReadOptoDataCmd},
|
||||
{"Stop Read Opto Data", Operations.StopReadOptoDataCmd},
|
||||
{"Start Read Opto Data", ReadOptoDataCmd},
|
||||
{"Stop Read Opto Data", StopReadOptoDataCmd},
|
||||
#endif
|
||||
{" ", Operations.EmptyCmd},
|
||||
{"Reset NFC Head", Operations.ResetNfcHeadCmd},
|
||||
{"Set NFC Head Interface", Operations.SetNfcHeadCmd},
|
||||
{"Set RFID Head interface", Operations.SetRfidHeadCmd}
|
||||
{" ", EmptyCmd},
|
||||
{"Reset NFC Head", ResetNfcHeadCmd},
|
||||
{"Set NFC Head Interface", SetNfcHeadCmd},
|
||||
{"Set RFID Head interface", SetRfidHeadCmd}
|
||||
};
|
||||
|
||||
public (string Name, string Value)[] GetComboOperationsPairs()
|
||||
{
|
||||
//return ItemsForIperlOperations.Select(kvp => (kvp.Key, kvp.Value)).ToArray();
|
||||
return ItemsForIperlOperations.Select(kvp => (kvp.Key, kvp.Value.ToDescription())).ToArray();
|
||||
return ItemsForIperlOperations.Select(kvp => (kvp.Key, kvp.Value)).ToArray();
|
||||
}
|
||||
|
||||
public void CommandTestButtonClick(object sender, MouseEventArgs e, Arguments a)
|
||||
@@ -93,15 +76,12 @@ namespace TBF.Rig.RegisterReaders.IPerlReader.implementations
|
||||
{
|
||||
ListItem rfidListItem = new ListItem();
|
||||
rfidListItem.Attributes.Add("style", "font-weight:bold");
|
||||
Operations selectedOperation;
|
||||
if(!ItemsForIperlOperations.TryGetValue((string)a.RfidCommandComboBox.SelectedValue, out selectedOperation))
|
||||
selectedOperation = Operations.EmptyCmd;
|
||||
switch (selectedOperation)
|
||||
switch (a.RfidCommandComboBox.SelectedValue)
|
||||
{
|
||||
case Operations.ReadPcbCmd:
|
||||
case ReadPCBCmd:
|
||||
rfidListItem.Text = $"PCB: {OpticalHeadTest.ReadRequest_PCB(a.ISmartReader)}";
|
||||
break;
|
||||
case Operations.SetTestModeCmd:
|
||||
case SetTestModeCmd:
|
||||
rfidListItem.Text = OpticalHeadTest.SetTestMode(a.ISmartReader);
|
||||
a.OptoListBox.Items.Clear();
|
||||
stopWorkerThread = false;
|
||||
@@ -111,23 +91,22 @@ namespace TBF.Rig.RegisterReaders.IPerlReader.implementations
|
||||
a.ISmartReader.StartDataStreamProcessing(); // open opto port
|
||||
optoThread.Start();
|
||||
}
|
||||
|
||||
break;
|
||||
case Operations.SetActiveModeCmd:
|
||||
case SetActiveModeCmd:
|
||||
rfidListItem.Text = OpticalHeadTest.SetActiveMode(a.ISmartReader);
|
||||
stopWorkerThread = true;
|
||||
a.ISmartReader.StopDataStreamProcessing(); // close opto port
|
||||
break;
|
||||
case Operations.ResetNfcHeadCmd:
|
||||
case ResetNfcHeadCmd:
|
||||
a.ISmartReader.ResetNfcInterface();
|
||||
break;
|
||||
case Operations.SetNfcHeadCmd:
|
||||
case SetNfcHeadCmd:
|
||||
a.ISmartReader.SetNfcInterface();
|
||||
break;
|
||||
case Operations.SetRfidHeadCmd:
|
||||
case SetRfidHeadCmd:
|
||||
a.ISmartReader.SetRfidInterface();
|
||||
break;
|
||||
case Operations.ReadOptoDataCmd:
|
||||
case ReadOptoDataCmd:
|
||||
a.OptoListBox.Items.Clear();
|
||||
stopWorkerThread = false;
|
||||
optoThread = new Thread(OptoWorker);
|
||||
@@ -136,20 +115,17 @@ namespace TBF.Rig.RegisterReaders.IPerlReader.implementations
|
||||
stopWorkerThread = true;
|
||||
a.ISmartReader.StopDataStreamProcessing(); // close opto port
|
||||
}
|
||||
|
||||
if (!optoThread.IsAlive)
|
||||
{
|
||||
a.ISmartReader.StartDataStreamProcessing(); // open opto port
|
||||
optoThread.Start();
|
||||
}
|
||||
|
||||
break;
|
||||
case Operations.StopReadOptoDataCmd:
|
||||
case StopReadOptoDataCmd:
|
||||
stopWorkerThread = true;
|
||||
a.ISmartReader.StopDataStreamProcessing(); // close opto port
|
||||
break;
|
||||
}
|
||||
|
||||
a.RfidOutputListBox.Items.Add(rfidListItem);
|
||||
a.RfidOutputListBox.Items.AddRange(logChecker.Messages.ToArray());
|
||||
}
|
||||
|
||||
@@ -13,46 +13,29 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
public class CliRunner
|
||||
{
|
||||
//static readonly ILog log = LogManager.GetLogger(typeof(CliRunner));
|
||||
private readonly ILog log;
|
||||
private List<Task> taskPool = new List<Task>();
|
||||
private long startTime;
|
||||
private long incommingTime;
|
||||
|
||||
public List<Task> TaskPool { get { return taskPool; } }
|
||||
public void AddTask(Task task) { taskPool.Add(task); }
|
||||
public void WaitAll() { Task.WaitAll(taskPool.ToArray()); }
|
||||
public void Clear() { taskPool.Clear(); }
|
||||
public void CancelAll() { Task.WhenAll(taskPool).ContinueWith(t => { }); }
|
||||
private readonly List<CliTaskInfo> taskPool = new List<CliTaskInfo>();
|
||||
private long startTimeMs;
|
||||
private long incommingTimeMs;
|
||||
|
||||
public void StartAll()
|
||||
public List<CliTaskInfo> TaskPool
|
||||
{
|
||||
taskPool.ForEach(t => t.Start());
|
||||
}
|
||||
|
||||
public bool AreTasksDone()
|
||||
{
|
||||
return taskPool.All(task => task.IsCompleted);
|
||||
get { return taskPool; }
|
||||
}
|
||||
|
||||
public long StartTime
|
||||
{
|
||||
get => startTime;
|
||||
get { return startTimeMs; }
|
||||
}
|
||||
|
||||
public long IncommingTime
|
||||
{
|
||||
get => incommingTime;
|
||||
get { return incommingTimeMs; }
|
||||
}
|
||||
|
||||
public bool TimeOutReceived(long timeout)
|
||||
{
|
||||
return (DateTime.Now.Ticks - startTime) > timeout;
|
||||
}
|
||||
|
||||
public CliRunner(bool isCliLogging)
|
||||
{
|
||||
startTime = DateTime.Now.Ticks;
|
||||
ResetStartTime();
|
||||
|
||||
if (isCliLogging)
|
||||
{
|
||||
@@ -60,173 +43,432 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
log = new ScopedLoggerFactory().CreateLogger<CliRunner>(
|
||||
@"C:\TBF\Logs\CliRunner.txt",
|
||||
10, // maxFileSizeMB
|
||||
7, // maxBackups
|
||||
10,
|
||||
7,
|
||||
log4net.Core.Level.Debug,
|
||||
true, // zipRolledFiles
|
||||
true, // singleZipPerDay
|
||||
TimeSpan.FromMinutes(2) // zipScanInterval
|
||||
true,
|
||||
true,
|
||||
TimeSpan.FromMinutes(2)
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Fallback to console or handle gracefully
|
||||
Console.WriteLine($"Failed to initialize logger: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="args"></param>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public void AddSendAsync(SerialPortData data, SerialPortData.EMeterArg eMeterArg)
|
||||
public void ResetStartTime()
|
||||
{
|
||||
var task = SendAsync(data.SerialPortCmdClientPath, data.DefaultArgSettings(eMeterArg));
|
||||
taskPool.Add(task);
|
||||
}
|
||||
|
||||
public void AddSendAsync(string fileName, string args)
|
||||
{
|
||||
var task = SendAsync(fileName, args);
|
||||
taskPool.Add(task);
|
||||
}
|
||||
|
||||
|
||||
public async Task<string> SendAsync(string fileName, string args, CancellationToken ct = default)
|
||||
{
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
Arguments = args,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
|
||||
using var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
|
||||
process.Start();
|
||||
|
||||
Task<string> stdOutTask = process.StandardOutput.ReadToEndAsync();
|
||||
Task<string> stdErrTask = process.StandardError.ReadToEndAsync();
|
||||
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(stdOutTask, stdErrTask, process.WaitForExitAsync(ct));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
if (!process.HasExited)
|
||||
{
|
||||
process.Kill();
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
//comming answer from serial port - good place for time stamp
|
||||
incommingTime = DateTime.Now.Ticks;
|
||||
string allOutput = (stdOutTask.Result ?? "") + (stdErrTask.Result ?? "");
|
||||
log?.Debug(allOutput);
|
||||
return allOutput;
|
||||
startTimeMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
}
|
||||
|
||||
|
||||
public void AddRunAndCaptureJsonAsync<T>(SerialPortData data, SerialPortData.EMeterArg eMeterArg) where T : new()
|
||||
public void Clear()
|
||||
{
|
||||
var task = RunAndCaptureJsonAsync<T>(data.SerialPortCmdClientPath, data.DefaultArgSettings(eMeterArg));
|
||||
taskPool.Add(task);
|
||||
}
|
||||
|
||||
public async Task<T> RunAndCaptureJsonAsync<T>(string fileName, string args, CancellationToken ct = default) where T : new()
|
||||
{
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
Arguments = args,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
|
||||
using var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
|
||||
process.Start();
|
||||
|
||||
var stdoutTask = process.StandardOutput.ReadToEndAsync();
|
||||
var stderrTask = process.StandardError.ReadToEndAsync();
|
||||
|
||||
await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(ct));
|
||||
|
||||
string allOutput = (stdoutTask.Result ?? "") + (stderrTask.Result ?? "");
|
||||
log?.Debug(allOutput);
|
||||
|
||||
string json = ExtractJson(allOutput);
|
||||
if (TryJsonStringDeserialize(json, out T result)) return result;
|
||||
return default;
|
||||
}
|
||||
|
||||
public bool TryJsonStringDeserialize<T>(string json, out T runAndCaptureJsonAsync) where T : new()
|
||||
{
|
||||
if (json != null)
|
||||
foreach (var item in taskPool)
|
||||
{
|
||||
try
|
||||
{
|
||||
runAndCaptureJsonAsync = JsonConvert.DeserializeObject<T>(json);
|
||||
return true;
|
||||
item?.Cts?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (item?.Process != null)
|
||||
{
|
||||
item.Process.Dispose();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
taskPool.Clear();
|
||||
}
|
||||
|
||||
public void WaitAll()
|
||||
{
|
||||
var tasks = taskPool
|
||||
.Where(t => t != null && t.Task != null)
|
||||
.Select(t => t.Task)
|
||||
.ToArray();
|
||||
|
||||
if (tasks.Length == 0)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Task.WaitAll(tasks);
|
||||
}
|
||||
catch (AggregateException)
|
||||
{
|
||||
RefreshTaskStates();
|
||||
}
|
||||
}
|
||||
|
||||
public bool AreTasksDone()
|
||||
{
|
||||
RefreshTaskStates();
|
||||
return taskPool.Count > 0 && taskPool.All(t => t.State != CliTaskState.Running);
|
||||
}
|
||||
|
||||
public bool TimeOutReceived(long timeoutMs)
|
||||
{
|
||||
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
return (nowMs - startTimeMs) > timeoutMs;
|
||||
}
|
||||
|
||||
public void RefreshTaskStates()
|
||||
{
|
||||
foreach (var item in taskPool)
|
||||
{
|
||||
if (item == null || item.Task == null)
|
||||
continue;
|
||||
|
||||
if (item.State == CliTaskState.TimedOut)
|
||||
continue;
|
||||
|
||||
if (!item.Task.IsCompleted)
|
||||
{
|
||||
item.State = CliTaskState.Running;
|
||||
}
|
||||
else if (item.Task.IsCanceled)
|
||||
{
|
||||
item.State = CliTaskState.Canceled;
|
||||
}
|
||||
else if (item.Task.IsFaulted)
|
||||
{
|
||||
item.State = CliTaskState.Faulted;
|
||||
}
|
||||
else
|
||||
{
|
||||
item.State = CliTaskState.Completed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void CancelUndoneTasksAsTimedOut()
|
||||
{
|
||||
foreach (var item in taskPool)
|
||||
{
|
||||
if (item == null || item.Task == null)
|
||||
continue;
|
||||
|
||||
if (item.Task.IsCompleted)
|
||||
{
|
||||
if (item.Task.IsCanceled)
|
||||
item.State = CliTaskState.Canceled;
|
||||
else if (item.Task.IsFaulted)
|
||||
item.State = CliTaskState.Faulted;
|
||||
else
|
||||
item.State = CliTaskState.Completed;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
item.State = CliTaskState.TimedOut;
|
||||
|
||||
try
|
||||
{
|
||||
item.Cts?.Cancel();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
log.Debug(ex.Message);
|
||||
runAndCaptureJsonAsync = TryConvert<T>(json);
|
||||
return true;
|
||||
log?.Warn("Cancel token failed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
runAndCaptureJsonAsync = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
private static T TryConvert<T>(string json) where T : new()
|
||||
{
|
||||
|
||||
T obj = new T();
|
||||
|
||||
try
|
||||
{
|
||||
JObject jObject = JObject.Parse(json);
|
||||
|
||||
foreach (PropertyInfo prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
if (item.Process != null && !item.Process.HasExited)
|
||||
{
|
||||
if (!prop.CanWrite) continue;
|
||||
|
||||
JToken token;
|
||||
if (jObject.TryGetValue(prop.Name, StringComparison.OrdinalIgnoreCase, out token))
|
||||
{
|
||||
try
|
||||
{
|
||||
object value = token.ToObject(prop.PropertyType);
|
||||
prop.SetValue(obj, value);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// leave default if conversion fails
|
||||
}
|
||||
}
|
||||
// else → keep default value
|
||||
item.Process.Kill();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"TryConvert failed: {ex.Message}");
|
||||
log?.Warn("Kill process failed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AddSendAsync(SerialPortData data, SerialPortData.EMeterArg eMeterArg)
|
||||
{
|
||||
AddSendAsync(data.SerialPortCmdClientPath, data.DefaultArgSettings(eMeterArg));
|
||||
}
|
||||
|
||||
public void AddSendAsync(string fileName, string args)
|
||||
{
|
||||
ResetStartTime();
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
var info = new CliTaskInfo
|
||||
{
|
||||
Cts = cts,
|
||||
Name = "SendAsync"
|
||||
};
|
||||
|
||||
var task = SendAsync(fileName, args, info, cts.Token);
|
||||
info.Task = task;
|
||||
taskPool.Add(info);
|
||||
}
|
||||
|
||||
public async Task<string> SendAsync(string fileName, string args, CliTaskInfo info, CancellationToken ct = default)
|
||||
{
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
Arguments = args,
|
||||
WorkingDirectory = System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(fileName)),
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
|
||||
using (var process = new Process { StartInfo = psi, EnableRaisingEvents = true })
|
||||
{
|
||||
info.Process = process;
|
||||
|
||||
try
|
||||
{
|
||||
process.Start();
|
||||
|
||||
Task<string> stdOutTask = process.StandardOutput.ReadToEndAsync();
|
||||
Task<string> stdErrTask = process.StandardError.ReadToEndAsync();
|
||||
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(stdOutTask, stdErrTask, process.WaitForExitAsync(ct));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
if (info.State != CliTaskState.TimedOut)
|
||||
info.State = CliTaskState.Canceled;
|
||||
|
||||
if (!process.HasExited)
|
||||
{
|
||||
process.Kill();
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
incommingTimeMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
|
||||
info.ExitCode = process.ExitCode;
|
||||
info.StandardOutput = stdOutTask.Result ?? "";
|
||||
info.StandardError = stdErrTask.Result ?? "";
|
||||
string allOutput = info.StandardOutput + info.StandardError;
|
||||
log?.Debug(allOutput);
|
||||
|
||||
if (info.ExitCode != 0)
|
||||
{
|
||||
info.FailureReason = $"CLI exited with exit code {info.ExitCode}.";
|
||||
log?.Error($"{info.Name}: {info.FailureReason} stderr='{info.StandardError}'");
|
||||
}
|
||||
|
||||
info.State = CliTaskState.Completed;
|
||||
return allOutput;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
info.State = CliTaskState.Faulted;
|
||||
log?.Error("SendAsync failed", ex);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
info.Process = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRunAndCaptureJsonAsync<T>(SerialPortData data, SerialPortData.EMeterArg eMeterArg) where T : new()
|
||||
{
|
||||
AddRunAndCaptureJsonAsync<T>(
|
||||
data.SerialPortCmdClientPath,
|
||||
data.DefaultArgSettings(eMeterArg));
|
||||
}
|
||||
|
||||
public void AddRunAndCaptureJsonAsync<T>(string fileName, string args) where T : new()
|
||||
{
|
||||
// Tests deliberately create CliRunner without a logger. Starting a CLI task
|
||||
// must not depend on diagnostics being configured.
|
||||
log?.Debug($"CLI: {fileName}");
|
||||
log?.Debug($"ARGS: {args}");
|
||||
|
||||
ResetStartTime();
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
var info = new CliTaskInfo
|
||||
{
|
||||
Cts = cts,
|
||||
Name = $"RunAndCaptureJsonAsync<{typeof(T).Name}>"
|
||||
};
|
||||
|
||||
var task = RunAndCaptureJsonAsync<T>(fileName, args, info, cts.Token);
|
||||
|
||||
info.Task = task;
|
||||
taskPool.Add(info);
|
||||
}
|
||||
|
||||
public async Task<T> RunAndCaptureJsonAsync<T>(string fileName, string args, CliTaskInfo info, CancellationToken ct = default) where T : new()
|
||||
{
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
Arguments = args,
|
||||
WorkingDirectory = System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(fileName)),
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
|
||||
using (var process = new Process { StartInfo = psi, EnableRaisingEvents = true })
|
||||
{
|
||||
info.Process = process;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
log?.Debug($"FileName = '{psi.FileName}'");
|
||||
log?.Debug($"Arguments = '{psi.Arguments}'");
|
||||
log?.Debug($"WorkingDirectory = '{psi.WorkingDirectory}'");
|
||||
log?.Debug($"Exists = {System.IO.File.Exists(psi.FileName)}");
|
||||
|
||||
process.Start();
|
||||
|
||||
var stdoutTask = process.StandardOutput.ReadToEndAsync();
|
||||
var stderrTask = process.StandardError.ReadToEndAsync();
|
||||
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(ct));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
if (info.State != CliTaskState.TimedOut)
|
||||
info.State = CliTaskState.Canceled;
|
||||
|
||||
if (!process.HasExited)
|
||||
{
|
||||
process.Kill();
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
incommingTimeMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
|
||||
info.ExitCode = process.ExitCode;
|
||||
info.StandardOutput = stdoutTask.Result ?? "";
|
||||
info.StandardError = stderrTask.Result ?? "";
|
||||
string allOutput = info.StandardOutput + info.StandardError;
|
||||
log?.Debug(allOutput);
|
||||
|
||||
if (info.ExitCode != 0)
|
||||
{
|
||||
info.FailureReason = $"CLI exited with exit code {info.ExitCode}.";
|
||||
log?.Error($"{info.Name}: {info.FailureReason} stderr='{info.StandardError}'");
|
||||
info.State = CliTaskState.Completed;
|
||||
return default(T);
|
||||
}
|
||||
|
||||
string json = ExtractJson(allOutput);
|
||||
T result;
|
||||
if (TryJsonStringDeserialize(json, out result))
|
||||
{
|
||||
info.State = CliTaskState.Completed;
|
||||
return result;
|
||||
}
|
||||
|
||||
info.FailureReason = "CLI completed without a valid JSON response.";
|
||||
log?.Error($"{info.Name}: {info.FailureReason} stdout='{info.StandardOutput}' stderr='{info.StandardError}'");
|
||||
info.State = CliTaskState.Completed;
|
||||
return default(T);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
info.State = CliTaskState.Faulted;
|
||||
log?.Error("RunAndCaptureJsonAsync failed", ex);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
info.Process = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryJsonStringDeserialize<T>(string json, out T value) where T : new()
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
try
|
||||
{
|
||||
value = JsonConvert.DeserializeObject<T>(json);
|
||||
return value != null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
log?.Debug(ex.Message);
|
||||
return TryConvert(json, out value);
|
||||
}
|
||||
}
|
||||
|
||||
value = default(T);
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryConvert<T>(string json, out T value) where T : new()
|
||||
{
|
||||
T obj = new T();
|
||||
|
||||
try
|
||||
{
|
||||
JObject jObject = JObject.Parse(json);
|
||||
|
||||
foreach (PropertyInfo prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (!prop.CanWrite)
|
||||
continue;
|
||||
|
||||
JToken token;
|
||||
if (jObject.TryGetValue(prop.Name, StringComparison.OrdinalIgnoreCase, out token))
|
||||
{
|
||||
try
|
||||
{
|
||||
object propertyValue = token.ToObject(prop.PropertyType);
|
||||
prop.SetValue(obj, propertyValue);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return obj;
|
||||
|
||||
value = obj;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"TryConvert failed: {ex.Message}");
|
||||
value = default(T);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public string ExtractJson(string text)
|
||||
@@ -241,6 +483,20 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
internal void AddTaskForTest(Task task, string name = "TestTask", CancellationTokenSource cts = null)
|
||||
{
|
||||
taskPool.Add(new CliTaskInfo
|
||||
{
|
||||
Task = task,
|
||||
Cts = cts,
|
||||
Name = name,
|
||||
State = task.IsCompleted
|
||||
? (task.IsCanceled ? CliTaskState.Canceled :
|
||||
task.IsFaulted ? CliTaskState.Faulted :
|
||||
CliTaskState.Completed)
|
||||
: CliTaskState.Running
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
public class CliTaskInfo
|
||||
{
|
||||
public Task Task { get; set; }
|
||||
public CancellationTokenSource Cts { get; set; }
|
||||
public Process Process { get; set; }
|
||||
public CliTaskState State { get; set; } = CliTaskState.Running;
|
||||
public string Name { get; set; }
|
||||
public int? ExitCode { get; set; }
|
||||
public string StandardOutput { get; set; }
|
||||
public string StandardError { get; set; }
|
||||
public string FailureReason { get; set; }
|
||||
|
||||
public bool UseResult
|
||||
{
|
||||
get
|
||||
{
|
||||
return State == CliTaskState.Completed
|
||||
&& Task != null
|
||||
&& Task.Status == TaskStatus.RanToCompletion;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
public enum CliTaskState
|
||||
{
|
||||
Running,
|
||||
Completed,
|
||||
TimedOut,
|
||||
Canceled,
|
||||
Faulted
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
public static class GetDescription
|
||||
{
|
||||
public static string ToDescription(this Enum en)
|
||||
{
|
||||
Type type = en.GetType();
|
||||
MemberInfo[] memInfo = type.GetMember(en.ToString());
|
||||
|
||||
if (memInfo != null && memInfo.Length > 0)
|
||||
{
|
||||
object[] attrs = memInfo[0].GetCustomAttributes(
|
||||
typeof(DescriptionAttribute),
|
||||
false);
|
||||
|
||||
if (attrs != null && attrs.Length > 0)
|
||||
return ((DescriptionAttribute)attrs[0]).Description;
|
||||
}
|
||||
|
||||
return en.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,53 @@
|
||||
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
public class JsonDataFromPoseidon
|
||||
{
|
||||
public bool? NfcTagDetected { get; set; }
|
||||
public int? ProductType { get; set; }
|
||||
public string ProductTypeVersion { get; set; }
|
||||
public bool NfcTagDetected { get; set; }
|
||||
public bool ReadingComplete { get; set; }
|
||||
|
||||
public string DeviceId { get; set; }
|
||||
public string ProductType { get; set; }
|
||||
public string ProductTypeVersion { get; set; }
|
||||
public string CliVersion { get; set; }
|
||||
|
||||
public string Reading { get; set; }
|
||||
public string Reading_Totalizer { get; set; }
|
||||
public string Reading_Digits { get; set; }
|
||||
public string Reading_Shift { get; set; }
|
||||
public string Reading_Resolution { get; set; }
|
||||
|
||||
public object Reading_Totalizer { get; set; }
|
||||
public object Reading_FlowRate { get; set; }
|
||||
public object Reading_FlowDirection { get; set; }
|
||||
public object Reading_Digits { get; set; }
|
||||
public object Reading_Shift { get; set; }
|
||||
public object Reading_Resolution { get; set; }
|
||||
public string Reading_Units { get; set; }
|
||||
public string Reading_FlowDirection { get; set; }
|
||||
public string Reading_FlowRate { get; set; }
|
||||
|
||||
public string MeterState { get; set; }
|
||||
public string CalibrationFactor { get; set; }
|
||||
public bool? ReadingComplete { get; set; }
|
||||
public string OpticalDataMode { get; set; }
|
||||
|
||||
public string BuildInformation { get; set; }
|
||||
public string ManufactureDate { get; set; }
|
||||
public string MeterSize { get; set; }
|
||||
public string FactoryId { get; set; }
|
||||
public string CustomerText { get; set; }
|
||||
|
||||
public string TestTotalizer { get; set; }
|
||||
public string FlowUnits { get; set; }
|
||||
public string ReadingUnits { get; set; }
|
||||
|
||||
public string SpreadSpectrumParameters { get; set; }
|
||||
|
||||
public string SpreadSpect_DisableSpreadSpectrum { get; set; }
|
||||
public string SpreadSpect_AlwaysUseFullRateBags { get; set; }
|
||||
public string SpreadSpect_PowerUp { get; set; }
|
||||
public string SpreadSpect_HighNoise { get; set; }
|
||||
public string SpreadSpect_EmptyPipe { get; set; }
|
||||
public string SpreadSpect_BadAdc { get; set; }
|
||||
public string SpreadSpect_InitLearningCompleteCount { get; set; }
|
||||
public string SpreadSpect_MinOffsetLearningSampleCount { get; set; }
|
||||
public string SpreadSpect_AdcShiftUpdateInterval { get; set; }
|
||||
public string SpreadSpect_MaxPreviousAdcAge { get; set; }
|
||||
public string SpreadSpect_AdcOffsetLearningGuard { get; set; }
|
||||
public string SpreadSpect_DisplacementCorrectionCount { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@
|
||||
///
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Ports;
|
||||
using System.ComponentModel;
|
||||
using System.Xml.Serialization;
|
||||
using Common;
|
||||
using TBF.Rig.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Common;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
@@ -22,7 +24,22 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
///
|
||||
public int ComPortNr;
|
||||
public string CliFileName;
|
||||
public int MeterType;
|
||||
|
||||
[XmlIgnore]
|
||||
public SerialPortData.MeterProduct MeterType = SerialPortData.MeterProduct.Poseidon;
|
||||
|
||||
[XmlElement("MeterProduct")]
|
||||
public string MeterProductXml
|
||||
{
|
||||
get { return SerialPortData.MeterToString(MeterType); }
|
||||
set { MeterType = SerialPortData.StringToMeter(value); }
|
||||
}
|
||||
|
||||
public SerialPortData.HatType HatType = SerialPortData.HatType.Mth;
|
||||
public int TimeOut = 30;
|
||||
public string MainMacro = SerialPortData.MacroTypes.readall.ToDescription();
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary> Procedure parameters </summary>
|
||||
@@ -31,14 +48,68 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
public override IParamsProvider GetRuntimeProcParamsProvider() { return ProcParams; }
|
||||
public override IParamsProvider CreateProcParamsProvider() { return new PoseidonProcParams(true); }
|
||||
|
||||
public static bool TryParseMeter(
|
||||
string description,
|
||||
out SerialPortData.MeterProduct meter)
|
||||
{
|
||||
var found = Enum.GetValues(typeof(SerialPortData.MeterProduct))
|
||||
.Cast<SerialPortData.MeterProduct>()
|
||||
.FirstOrDefault(e =>
|
||||
string.Equals(
|
||||
e.GetType()
|
||||
.GetField(e.ToString())
|
||||
.GetCustomAttribute<DescriptionAttribute>()
|
||||
?.Description,
|
||||
description,
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (!Equals(found, default(SerialPortData.MeterProduct)) ||
|
||||
string.Equals(description, "Poseidon", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
meter = found;
|
||||
return true;
|
||||
}
|
||||
|
||||
meter = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool TryParseMacro(
|
||||
string description,
|
||||
out string macro)
|
||||
{
|
||||
var found = Enum.GetValues(typeof(SerialPortData.MacroTypes))
|
||||
.Cast<SerialPortData.MacroTypes>()
|
||||
.FirstOrDefault(e =>
|
||||
string.Equals(
|
||||
e.GetType()
|
||||
.GetField(e.ToString())
|
||||
.GetCustomAttribute<DescriptionAttribute>()
|
||||
?.Description,
|
||||
description,
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (!Equals(found, default(SerialPortData.MacroTypes)) ||
|
||||
string.Equals(description, "readall", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
macro = found.ToDescription();
|
||||
return true;
|
||||
}
|
||||
|
||||
macro = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
string[] paramNames = new string[]
|
||||
{
|
||||
"Serial port number", /// 0
|
||||
"CLI program name", /// 1
|
||||
"Meter Type", /// 2
|
||||
"Hat Type", /// 3
|
||||
"TimeOut [s]", /// 4
|
||||
"Main Macro" /// 5
|
||||
};
|
||||
|
||||
public string ParamName(int i) { return paramNames[i]; }
|
||||
public int ParamsCount() { return paramNames.Length; }
|
||||
|
||||
@@ -51,8 +122,27 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
case 1:
|
||||
return new string[] { "HatCLI.exe"};
|
||||
case 2:
|
||||
return new string[] { "74" };
|
||||
|
||||
return new string[] {
|
||||
SerialPortData.MeterProduct.Poseidon.ToDescription() ,
|
||||
SerialPortData.MeterProduct.Ally.ToDescription(),
|
||||
SerialPortData.MeterProduct.IperlPlus.ToDescription(),
|
||||
SerialPortData.MeterProduct.IperlLegacy.ToDescription()
|
||||
};
|
||||
case 3:
|
||||
return new string[]
|
||||
{
|
||||
SerialPortData.HatType.Mth.ToDescription(),
|
||||
SerialPortData.HatType.Harry.ToDescription()
|
||||
};
|
||||
case 4:
|
||||
return new string[] { "30", "60", "90"};
|
||||
case 5:
|
||||
string macro0 = SerialPortData.MacroTypes.readall.ToDescription();
|
||||
string macro1 = SerialPortData.MacroTypes.macro1.ToDescription();
|
||||
string macro2 = SerialPortData.MacroTypes.macro2.ToDescription();
|
||||
string macro3 = SerialPortData.MacroTypes.macro3.ToDescription();
|
||||
|
||||
return new string[] { macro0, macro1, macro2, macro3 };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -60,12 +150,15 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
|
||||
public IComponentCfgCtrl GetControl(IList<Config.Entities.Component> cmpntEntities) { return new Configs.ParamsProvider.ComponentCfgCtrl(this, null); }
|
||||
|
||||
|
||||
|
||||
public void InitializeAll()
|
||||
{
|
||||
ComPortNr = 3;
|
||||
CliFileName = "HatCLI.exe";
|
||||
MeterType = 74;
|
||||
CliFileName = "HatCLI.exe";
|
||||
MeterType = SerialPortData.MeterProduct.Poseidon;
|
||||
HatType = SerialPortData.HatType.Mth;
|
||||
TimeOut = 30;
|
||||
MainMacro = SerialPortData.MacroTypes.readall.ToDescription();
|
||||
}
|
||||
|
||||
public bool ValidateParam(int i, string strValue, out string message)
|
||||
@@ -83,8 +176,17 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
if(System.Text.RegularExpressions.Regex.IsMatch(strValue, @"^[a-zA-Z0-9_-]+\.exe$")) return true; //validate exe file name
|
||||
break;
|
||||
case 2:
|
||||
if (TryParseMeter(strValue, out var meter)) return true;
|
||||
break;
|
||||
case 3:
|
||||
if (TryParseHatType(strValue, out var hatType)) return true;
|
||||
break;
|
||||
case 4:
|
||||
if (int.TryParse(strValue, out idummy) && idummy > 0) return true;
|
||||
break;
|
||||
case 5:
|
||||
if (TryParseMacro(strValue, out string macroType)) return true;
|
||||
break;
|
||||
default:
|
||||
message = "Invalid index";
|
||||
return false;
|
||||
@@ -100,11 +202,38 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
case 0: ComPortNr = int.Parse(str); return CfgUpdateFlags.RestartRqrd;
|
||||
case 1: CliFileName = str; return CfgUpdateFlags.RestartRqrd;
|
||||
case 2: MeterType = int.Parse(str); return CfgUpdateFlags.RestartRqrd;
|
||||
case 2: TryParseMeter(str, out MeterType); return CfgUpdateFlags.RestartRqrd;
|
||||
case 3: TryParseHatType(str, out HatType); return CfgUpdateFlags.RestartRqrd;
|
||||
case 4: TimeOut = int.Parse(str); return CfgUpdateFlags.RestartRqrd;
|
||||
case 5: MainMacro = str; return CfgUpdateFlags.RestartRqrd;
|
||||
default: return CfgUpdateFlags.None;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryParseHatType(string description, out SerialPortData.HatType hatType)
|
||||
{
|
||||
var found = Enum.GetValues(typeof(SerialPortData.HatType))
|
||||
.Cast<SerialPortData.HatType>()
|
||||
.FirstOrDefault(e =>
|
||||
string.Equals(
|
||||
e.GetType()
|
||||
.GetField(e.ToString())
|
||||
.GetCustomAttribute<DescriptionAttribute>()
|
||||
?.Description,
|
||||
description,
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (!Equals(found, default(SerialPortData.HatType)) ||
|
||||
string.Equals(description, "Mth", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
hatType = found;
|
||||
return true;
|
||||
}
|
||||
|
||||
hatType = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool UpdateEmbeddedDbEntity()
|
||||
{
|
||||
return true; /// =OK, do nothing
|
||||
@@ -139,9 +268,12 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
case 0: return ComPortNr.ToString();
|
||||
case 1: return CliFileName;
|
||||
case 2: return MeterType.ToString();
|
||||
case 3: return HatType.ToString();
|
||||
case 4: return TimeOut.ToString();
|
||||
case 5: return MainMacro;
|
||||
default:
|
||||
return string.Format("{0}: Com{1}, CliName =`{2}`, MeterType = {3}",
|
||||
Name, ComPortNr, CliFileName, MeterType);
|
||||
return string.Format("{0}: Com{1}, CliName =`{2}`, MeterType = {3}, HatType = {4}, TimeOut = {5}",
|
||||
Name, ComPortNr, CliFileName, MeterType, HatType, TimeOut);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,6 +282,9 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
prms.ComPortNr = this.ComPortNr;
|
||||
prms.CliFileName = this.CliFileName;
|
||||
prms.MeterType = this.MeterType;
|
||||
prms.HatType = this.HatType;
|
||||
prms.TimeOut = this.TimeOut;
|
||||
prms.MainMacro = this.MainMacro;
|
||||
prms.ProcParams = this.ProcParams;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using TBF.Rig;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
/// <summary>
|
||||
/// A single polling step for the Poseidon start/end read dialog.
|
||||
///
|
||||
/// A reader is armed only from None. In particular, a terminal reader
|
||||
/// must not be armed again: doing so starts a new CLI process on every
|
||||
/// polling iteration and leaves the dialog in Loading.
|
||||
/// </summary>
|
||||
public interface IPoseidonReadOperation
|
||||
{
|
||||
string Name { get; }
|
||||
bool IsNotStarted { get; }
|
||||
bool IsFinished { get; }
|
||||
bool HasError { get; }
|
||||
void Start(bool readStart);
|
||||
Event Run();
|
||||
}
|
||||
|
||||
public sealed class PoseidonReaderOperation : IPoseidonReadOperation
|
||||
{
|
||||
private readonly PoseidonReader reader;
|
||||
|
||||
public PoseidonReaderOperation(PoseidonReader reader)
|
||||
{
|
||||
if (reader == null) throw new ArgumentNullException(nameof(reader));
|
||||
this.reader = reader;
|
||||
}
|
||||
|
||||
public string Name { get { return reader.Name; } }
|
||||
public bool IsNotStarted { get { return reader.CurrentOp == PoseidonReader.CurrentPoseidonOp.None; } }
|
||||
public bool IsFinished
|
||||
{
|
||||
get
|
||||
{
|
||||
return reader.CurrentOp == PoseidonReader.CurrentPoseidonOp.Done ||
|
||||
reader.CurrentOp == PoseidonReader.CurrentPoseidonOp.Error;
|
||||
}
|
||||
}
|
||||
public bool HasError { get { return reader.CurrentOp == PoseidonReader.CurrentPoseidonOp.Error; } }
|
||||
public void Start(bool readStart)
|
||||
{
|
||||
reader.SetCurrentOp(readStart
|
||||
? PoseidonReader.CurrentPoseidonOp.ReadDataStream_Start
|
||||
: PoseidonReader.CurrentPoseidonOp.ReadDataStream_End);
|
||||
}
|
||||
public Event Run() { return reader.Run(); }
|
||||
}
|
||||
|
||||
public static class PoseidonReadCycle
|
||||
{
|
||||
public static bool RunIteration(IEnumerable<IPoseidonReadOperation> readers, bool readStart)
|
||||
{
|
||||
if (readers == null)
|
||||
return true;
|
||||
|
||||
bool allReadersFinished = true;
|
||||
foreach (IPoseidonReadOperation reader in readers)
|
||||
{
|
||||
if (reader == null)
|
||||
continue;
|
||||
|
||||
// None means that this dialog operation has not been started yet.
|
||||
// Done/Error are terminal and deliberately remain terminal.
|
||||
if (reader.IsNotStarted)
|
||||
reader.Start(readStart);
|
||||
|
||||
reader.Run();
|
||||
|
||||
if (!reader.IsFinished)
|
||||
allReadersFinished = false;
|
||||
}
|
||||
|
||||
return allReadersFinished;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Owns one logical dialog phase. A new phase must arm a reader even when
|
||||
/// the preceding phase left it in Done/Error; within this phase it is armed
|
||||
/// only once.
|
||||
/// </summary>
|
||||
public sealed class PoseidonReadPhaseRunner
|
||||
{
|
||||
private readonly bool readStart;
|
||||
private readonly HashSet<IPoseidonReadOperation> startedReaders =
|
||||
new HashSet<IPoseidonReadOperation>();
|
||||
|
||||
public PoseidonReadPhaseRunner(bool readStart)
|
||||
{
|
||||
this.readStart = readStart;
|
||||
}
|
||||
|
||||
public bool RunIteration(IEnumerable<IPoseidonReadOperation> readers)
|
||||
{
|
||||
if (readers == null)
|
||||
return true;
|
||||
|
||||
bool allReadersFinished = true;
|
||||
foreach (IPoseidonReadOperation reader in readers)
|
||||
{
|
||||
if (reader == null)
|
||||
continue;
|
||||
|
||||
if (startedReaders.Add(reader))
|
||||
reader.Start(readStart);
|
||||
|
||||
reader.Run();
|
||||
if (!reader.IsFinished)
|
||||
allReadersFinished = false;
|
||||
}
|
||||
|
||||
return allReadersFinished;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
///
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.IO.Ports;
|
||||
using System.Text.RegularExpressions;
|
||||
@@ -24,14 +25,15 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
public class PoseidonReader : ComponentBase, IDevice, IRegReaderDatastream, ISessionDataMngmnt, IOperation, ICommonRegReader
|
||||
{
|
||||
private static readonly ILog log = LogManager.GetLogger(typeof(PoseidonReader));
|
||||
// The simulator must never open the configured physical Hat CLI. The
|
||||
// deterministic test CLI returns a valid Poseidon JSON response instead.
|
||||
internal const string SimulatedCliFileName = "cmdSleepTest.exe";
|
||||
public override string ToString() { return string.Format("{0}({1})", ClassName, Cfg.ToString(-1)); }
|
||||
|
||||
readonly PoseidonCfg registerReaderCfg;
|
||||
readonly ControlBoard.IControlBoard controlBoard;
|
||||
|
||||
public int ComPortNr => registerReaderCfg?.ComPortNr ?? -1;
|
||||
public PoseidonCfg RegPoseidonCfg => registerReaderCfg;
|
||||
|
||||
|
||||
|
||||
private bool activeHandlerSessioEnabled = false;
|
||||
private CliRunner _cliRunner;
|
||||
|
||||
@@ -282,11 +284,23 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
if ((DebugLevel == DebugMode.Normal)||(DebugLevel == DebugMode.Simulate))
|
||||
{
|
||||
/// Prepare serial port
|
||||
string cliFileName = GetCliFileNameForMode(DebugLevel, registerReaderCfg.CliFileName);
|
||||
serialPort = new SerialPortData(string.Format("COM{0}", registerReaderCfg.ComPortNr),
|
||||
registerReaderCfg.CliFileName,
|
||||
registerReaderCfg.MeterType);
|
||||
cliFileName,
|
||||
registerReaderCfg.MeterType, //registerReaderCfg.MeterType, //MeterProduct.Poseidon
|
||||
registerReaderCfg.HatType,//HatType.Mth
|
||||
registerReaderCfg.TimeOut, //timeoutSeconds
|
||||
registerReaderCfg.MainMacro
|
||||
);
|
||||
|
||||
|
||||
if (DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
log.WarnFormat(
|
||||
"{0}: simulation mode enabled; overriding configured CLI '{1}' with '{2}'.",
|
||||
Name, registerReaderCfg.CliFileName, serialPort.SerialPortCmdClientPath);
|
||||
}
|
||||
|
||||
//TODO BUMI prepare serial port - for us do nothing
|
||||
//serialPort.Open();
|
||||
//we can check file program if exists
|
||||
@@ -307,6 +321,13 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
}
|
||||
}
|
||||
|
||||
internal static string GetCliFileNameForMode(DebugMode debugMode, string configuredCliFileName)
|
||||
{
|
||||
return debugMode == DebugMode.Simulate
|
||||
? SimulatedCliFileName
|
||||
: configuredCliFileName;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
log.DebugFormat("{0}:Clear()", Name);
|
||||
@@ -332,13 +353,21 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
/// for debug purposes what time will consume answer
|
||||
/// </summary>
|
||||
private long startTimeInMilis = -1, fullTimeInMilis = -1;
|
||||
/// 30 seconds
|
||||
private static long SafetyTimeOut = 30 * 1000;
|
||||
private long incommingTime = -1;
|
||||
private bool _lastOpTimedOut;
|
||||
private bool lastCliReadingParsed;
|
||||
private string lastCliReadFailureReason;
|
||||
private bool lastCliReadSucceeded;
|
||||
|
||||
|
||||
/// 30 seconds
|
||||
|
||||
public long DeltaTime { get{return fullTimeInMilis;}}
|
||||
public long IncommingTime { get{return incommingTime;}}
|
||||
public bool LastCliReadingParsed { get { return lastCliReadingParsed; } }
|
||||
public string LastCliReadFailureReason { get { return lastCliReadFailureReason; } }
|
||||
public bool LastCliReadSucceeded { get { return lastCliReadSucceeded; } }
|
||||
|
||||
/// <summary>Run this operation</summary>
|
||||
/// <returns>eventDone</returns>
|
||||
@@ -352,108 +381,262 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
|
||||
if (_currentOp == CurrentPoseidonOp.SendStartDataStream)
|
||||
{
|
||||
CliRunner.Clear();
|
||||
_lastOpTimedOut = false;
|
||||
CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.AllParams);
|
||||
return Event.Busy;
|
||||
_currentOp = CurrentPoseidonOp.SendStartDataStream_Runing;
|
||||
return Event.Busy;
|
||||
}
|
||||
else if (_currentOp == CurrentPoseidonOp.SendStartDataStream_Runing)
|
||||
{
|
||||
if (CliRunner.AreTasksDone()
|
||||
|| CliRunner.TimeOutReceived(SafetyTimeOut))
|
||||
if (CliRunner.AreTasksDone())
|
||||
{
|
||||
_currentOp = CurrentPoseidonOp.SendStartDataStream_Done;
|
||||
}
|
||||
return Event.Busy;
|
||||
else if (CliRunner.TimeOutReceived(SafetyTimeOut))
|
||||
{
|
||||
_lastOpTimedOut = true;
|
||||
CliRunner.CancelUndoneTasksAsTimedOut();
|
||||
_currentOp = CurrentPoseidonOp.SendStartDataStream_Done;
|
||||
}
|
||||
|
||||
return Event.Busy;
|
||||
}
|
||||
else if (_currentOp == CurrentPoseidonOp.SendStartDataStream_Done)
|
||||
{
|
||||
var firstTask = CliRunner.TaskPool.FindLast(t => t is Task<string>);
|
||||
var firstTaskInfo = CliRunner.TaskPool
|
||||
.FindLast(t => t.Task is Task<string> && t.UseResult);
|
||||
|
||||
|
||||
if (firstTask != null && firstTask is Task<string>)
|
||||
if (firstTaskInfo != null)
|
||||
{
|
||||
string data = null;
|
||||
data = (firstTask as Task<string>).Result;
|
||||
var task = (Task<string>)firstTaskInfo.Task;
|
||||
string data = task.Result;
|
||||
|
||||
if (data != null && TryGetDeviceId(data, out wmSerialNr))
|
||||
if (!string.IsNullOrEmpty(data))
|
||||
{
|
||||
|
||||
TryGetDeviceId(data, out wmSerialNr);
|
||||
}
|
||||
}
|
||||
else if (_lastOpTimedOut)
|
||||
{
|
||||
log.Warn(
|
||||
$"PoseidonReader {Name}: SendStartDataStream timed out, no completed result will be used.");
|
||||
}
|
||||
|
||||
_currentOp = CurrentPoseidonOp.Done;
|
||||
CliRunner.Clear();
|
||||
_currentOp = _lastOpTimedOut ? CurrentPoseidonOp.Error : CurrentPoseidonOp.Done;
|
||||
return Event.Done;
|
||||
}
|
||||
else if (_currentOp == CurrentPoseidonOp.ReadDataStream_Start
|
||||
else if (_currentOp == CurrentPoseidonOp.ReadDataStream_Start
|
||||
|| _currentOp == CurrentPoseidonOp.ReadDataStream_End)
|
||||
{
|
||||
startTimeInMilis = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
|
||||
lastCliReadingParsed = false;
|
||||
lastCliReadFailureReason = null;
|
||||
lastCliReadSucceeded = false;
|
||||
startTimeInMilis = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
incommingTime = -1;
|
||||
_isReadingStart = (_currentOp == CurrentPoseidonOp.ReadDataStream_Start);
|
||||
CliRunner.AddRunAndCaptureJsonAsync<JsonDataFromPoseidon>(serialPort, SerialPortData.EMeterArg.AllParams);
|
||||
|
||||
CliRunner.Clear();
|
||||
_lastOpTimedOut = false;
|
||||
log.DebugFormat("{0}: starting CLI read, direction={1}, path='{2}', args='{3}'",
|
||||
Name,
|
||||
_isReadingStart ? "start" : "end",
|
||||
serialPort == null ? "<not initialized>" : serialPort.SerialPortCmdClientPath,
|
||||
serialPort == null ? "<not initialized>" : serialPort.DefaultArgSettings(SerialPortData.EMeterArg.AllParams));
|
||||
CliRunner.AddRunAndCaptureJsonAsync<JsonDataFromPoseidon>(serialPort,
|
||||
SerialPortData.EMeterArg.AllParams);
|
||||
_currentOp = CurrentPoseidonOp.ReadDatastream_Running;
|
||||
return Event.Busy;
|
||||
}else if (_currentOp == CurrentPoseidonOp.ReadDatastream_Running)
|
||||
}
|
||||
else if (_currentOp == CurrentPoseidonOp.ReadDatastream_Running)
|
||||
{
|
||||
if (CliRunner.AreTasksDone()
|
||||
|| CliRunner.TimeOutReceived(SafetyTimeOut))
|
||||
if (CliRunner.AreTasksDone())
|
||||
{
|
||||
_currentOp = CurrentPoseidonOp.ReadDatastream_Done;
|
||||
//set time stamp - end of reading
|
||||
incommingTime = CliRunner.IncommingTime;
|
||||
log.DebugFormat("{0}: CLI read task finished, taskCount={1}, incomingTime={2}",
|
||||
Name, CliRunner.TaskPool.Count, incommingTime);
|
||||
}
|
||||
else if (CliRunner.TimeOutReceived(SafetyTimeOut))
|
||||
{
|
||||
_lastOpTimedOut = true;
|
||||
CliRunner.CancelUndoneTasksAsTimedOut();
|
||||
_currentOp = CurrentPoseidonOp.ReadDatastream_Done;
|
||||
incommingTime = CliRunner.IncommingTime;
|
||||
}
|
||||
|
||||
return Event.Busy;
|
||||
}
|
||||
else if (_currentOp == CurrentPoseidonOp.ReadDatastream_Done)
|
||||
{
|
||||
fullTimeInMilis = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - startTimeInMilis;
|
||||
log.Debug($"PoseidonReader.Run() Name= {Cfg.Name} fullTimeInMilis = {fullTimeInMilis} ");
|
||||
JsonDataFromPoseidon data = null;
|
||||
var first = CliRunner.TaskPool.FindLast(t => t is Task<JsonDataFromPoseidon>);
|
||||
if (first != null && first is Task<JsonDataFromPoseidon>)
|
||||
{
|
||||
data = (first as Task<JsonDataFromPoseidon>).Result;
|
||||
fullTimeInMilis = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - startTimeInMilis;
|
||||
log.Debug($"PoseidonReader.Run() Name= {Cfg.Name} fullTimeInMilis = {fullTimeInMilis}");
|
||||
|
||||
//GET serial number
|
||||
JsonDataFromPoseidon data = null;
|
||||
|
||||
var firstTaskInfo = CliRunner.TaskPool
|
||||
.FindLast(t => t.Task is Task<JsonDataFromPoseidon> && t.UseResult);
|
||||
|
||||
if (firstTaskInfo != null)
|
||||
{
|
||||
var task = (Task<JsonDataFromPoseidon>)firstTaskInfo.Task;
|
||||
data = task.Result;
|
||||
if (data == null)
|
||||
{
|
||||
lastCliReadFailureReason = firstTaskInfo.FailureReason ?? "CLI returned no Poseidon JSON data.";
|
||||
log.ErrorFormat("{0}: Poseidon {1} read failed. reason='{2}', exitCode={3}, stderr='{4}'",
|
||||
Name,
|
||||
_isReadingStart ? "Begin" : "End",
|
||||
lastCliReadFailureReason,
|
||||
firstTaskInfo.ExitCode,
|
||||
firstTaskInfo.StandardError);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var lastTaskInfo = CliRunner.TaskPool.FindLast(t => t.Task is Task<JsonDataFromPoseidon>);
|
||||
lastCliReadFailureReason = lastTaskInfo == null
|
||||
? "No CLI task was created."
|
||||
: lastTaskInfo.FailureReason ?? "CLI task was not usable, state=" + lastTaskInfo.State + ".";
|
||||
if (_lastOpTimedOut)
|
||||
{
|
||||
log.Warn($"PoseidonReader {Name}: ReadDatastream timed out, no completed result available. {lastCliReadFailureReason}");
|
||||
}
|
||||
else
|
||||
{
|
||||
log.Error($"PoseidonReader {Name}: no usable JsonDataFromPoseidon task. {lastCliReadFailureReason}");
|
||||
}
|
||||
}
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
log.DebugFormat("{0}: CLI read result deviceId={1}, reading={2}, readingComplete={3}, nfcTagDetected={4}",
|
||||
Name, data.DeviceId, data.Reading, data.ReadingComplete, data.NfcTagDetected);
|
||||
string validationError;
|
||||
if (!TryValidateCliReadResponse(data, out validationError))
|
||||
{
|
||||
lastCliReadFailureReason = validationError;
|
||||
log.ErrorFormat("{0}: Poseidon {1} read rejected. {2}. Begin={3}, End={4}",
|
||||
Name, _isReadingStart ? "Begin" : "End", validationError, beginWMState, endWMState);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(wmSerialNr))
|
||||
{
|
||||
try
|
||||
{
|
||||
wmSerialNr = data?.DeviceId ?? wmSerialNr;
|
||||
wmSerialNr = data.DeviceId ?? wmSerialNr;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.Error("Serial Nr - parse error!");
|
||||
log.Error("Serial Nr - parse error!", e);
|
||||
}
|
||||
}
|
||||
|
||||
//GET volume
|
||||
if (data != null && Double.TryParse(data.Reading, out double Volume))
|
||||
double volumeLi;
|
||||
string dialogValueFailureReason;
|
||||
if (TryGetDialogValue(data, out volumeLi, out dialogValueFailureReason))
|
||||
{
|
||||
double VolumeLi = Units.ConvertFrom(Unit.USgal, Volume);
|
||||
//double VolumeM3 = Units.ConvertTo(Unit.m3, VolumeLi);
|
||||
if (_isReadingStart)
|
||||
{
|
||||
//volume
|
||||
beginWMState = VolumeLi;
|
||||
}
|
||||
else
|
||||
{
|
||||
//volume
|
||||
endWMState = VolumeLi;
|
||||
}
|
||||
}
|
||||
lastCliReadingParsed = true;
|
||||
lastCliReadSucceeded = true;
|
||||
double volume;
|
||||
TryParseCliReading(data.Reading, out volume);
|
||||
|
||||
if (_isReadingStart)
|
||||
beginWMState = volumeLi;
|
||||
else
|
||||
endWMState = volumeLi;
|
||||
|
||||
log.InfoFormat("{0}: Poseidon {1} value stored. deviceId={2}, rawReading='{3}', gallons={4}, litres={5}, Begin={6}, End={7}",
|
||||
Name, _isReadingStart ? "Begin" : "End", data.DeviceId, data.Reading, volume, volumeLi, beginWMState, endWMState);
|
||||
}
|
||||
else
|
||||
{
|
||||
lastCliReadFailureReason = dialogValueFailureReason;
|
||||
log.ErrorFormat("{0}: cannot parse CLI reading '{1}' using invariant or current culture.",
|
||||
Name, data.Reading);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Finish reading and loop
|
||||
_currentOp = CurrentPoseidonOp.Done;
|
||||
|
||||
CliRunner.Clear();
|
||||
_currentOp = _lastOpTimedOut ? CurrentPoseidonOp.Error : CurrentPoseidonOp.Done;
|
||||
return Event.Done;
|
||||
}
|
||||
|
||||
return Event.None;
|
||||
|
||||
return Event.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CLI values must not depend on the Windows UI culture. Both dot and comma
|
||||
/// are accepted as a decimal separator and normalized before parsing.
|
||||
/// </summary>
|
||||
public static bool TryParseCliReading(string reading, out double value)
|
||||
{
|
||||
value = 0;
|
||||
if (String.IsNullOrWhiteSpace(reading))
|
||||
return false;
|
||||
|
||||
string normalizedReading = reading.Trim().Replace(',', '.');
|
||||
return Double.TryParse(normalizedReading, NumberStyles.Float, CultureInfo.InvariantCulture, out value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a validated CLI response to the value written into the
|
||||
/// start/end dialog. Poseidon reports US gallons; TBF stores litres.
|
||||
/// </summary>
|
||||
public static bool TryGetDialogValue(JsonDataFromPoseidon data, out double valueLitres,
|
||||
out string failureReason)
|
||||
{
|
||||
valueLitres = 0;
|
||||
if (!TryValidateCliReadResponse(data, out failureReason))
|
||||
return false;
|
||||
|
||||
double valueGallons;
|
||||
if (!TryParseCliReading(data.Reading, out valueGallons))
|
||||
{
|
||||
failureReason = "Reading could not be parsed: '" + data.Reading + "'.";
|
||||
return false;
|
||||
}
|
||||
|
||||
valueLitres = Units.ConvertFrom(Unit.USgal, valueGallons);
|
||||
failureReason = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool TryValidateCliReadResponse(JsonDataFromPoseidon data, out string failureReason)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
failureReason = "CLI returned no JSON data.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!data.NfcTagDetected)
|
||||
{
|
||||
failureReason = "NfcTagDetected=false.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!data.ReadingComplete)
|
||||
{
|
||||
failureReason = "ReadingComplete=false.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (String.IsNullOrWhiteSpace(data.Reading))
|
||||
{
|
||||
failureReason = "Reading is empty.";
|
||||
return false;
|
||||
}
|
||||
|
||||
failureReason = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>Stop this operation</summary>
|
||||
public void Stop()
|
||||
{
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
public class SerialPortData
|
||||
{
|
||||
public const string CliDirectory = @"C:\TBF\Cli";
|
||||
|
||||
private Boolean? _cliExists;
|
||||
public bool CliExists { get {
|
||||
if (_cliExists == null || !_cliExists.HasValue)
|
||||
@@ -13,39 +18,245 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
}
|
||||
return _cliExists.Value;
|
||||
} }
|
||||
public string SerialPortCmdClientPath {
|
||||
#if DEBUG
|
||||
get { return Path.Combine("C:\\","TBF","Cli", CmdClientName);}
|
||||
#else
|
||||
get { return Path.Combine("..","Cli", CmdClientName);}
|
||||
#endif
|
||||
}
|
||||
public string SerialPortCmdClientPath
|
||||
{
|
||||
get
|
||||
{
|
||||
// The configured value is a file name, not an executable path.
|
||||
// Keeping the CLI directory fixed prevents a bench configuration
|
||||
// from starting an unintended executable or failing due to a
|
||||
// relative path/current-directory change.
|
||||
string cliFileName = Path.GetFileName(CmdClientName);
|
||||
if (string.IsNullOrWhiteSpace(cliFileName))
|
||||
cliFileName = "HalCli.exe";
|
||||
|
||||
return Path.Combine(CliDirectory, cliFileName);
|
||||
}
|
||||
}
|
||||
public string CmdClientName { get; set; } = "HalCli.exe";
|
||||
public string PortName { get; set; }
|
||||
public int MeterType { get; set; }
|
||||
// Backward compatibility: old numeric meter type
|
||||
public int? OldMeterType { get; set; }
|
||||
|
||||
public enum EMeterArg {
|
||||
// New v2.0 parameters
|
||||
public HatType Hat { get; set; } = HatType.Mth;
|
||||
public int TimeoutSeconds { get; set; } = 10;
|
||||
public string Macro { get; set; } = "readall";
|
||||
|
||||
[XmlIgnore]
|
||||
public MeterProduct Meter { get; set; } = MeterProduct.Poseidon;
|
||||
|
||||
[XmlElement("MeterProduct")]
|
||||
public string MeterXml
|
||||
{
|
||||
get { return MeterToString(Meter); }
|
||||
set { Meter = StringToMeter(value); }
|
||||
}
|
||||
|
||||
public static string MeterToString(MeterProduct meter)
|
||||
{
|
||||
switch (meter)
|
||||
{
|
||||
case MeterProduct.Poseidon:
|
||||
return "Poseidon"; //Poseidon
|
||||
case MeterProduct.Ally:
|
||||
return "ally";
|
||||
case MeterProduct.IperlPlus:
|
||||
return "iperlplus";
|
||||
case MeterProduct.IperlLegacy:
|
||||
return "iperllegacy";
|
||||
default:
|
||||
return "74";
|
||||
}
|
||||
}
|
||||
|
||||
public static MeterProduct StringToMeter(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return MeterProduct.Poseidon;
|
||||
|
||||
// old numeric values: 74, 7889, etc.
|
||||
if (int.TryParse(value, out _))
|
||||
return MeterProduct.Poseidon;
|
||||
|
||||
if (string.Equals(value, "cTouchRead", StringComparison.OrdinalIgnoreCase))
|
||||
return MeterProduct.Poseidon;
|
||||
|
||||
if (string.Equals(value, "Poseidon", StringComparison.OrdinalIgnoreCase))
|
||||
return MeterProduct.Poseidon;
|
||||
|
||||
if (string.Equals(value, "ally", StringComparison.OrdinalIgnoreCase))
|
||||
return MeterProduct.Ally;
|
||||
|
||||
if (string.Equals(value, "iperlplus", StringComparison.OrdinalIgnoreCase))
|
||||
return MeterProduct.IperlPlus;
|
||||
|
||||
if (string.Equals(value, "iperllegacy", StringComparison.OrdinalIgnoreCase))
|
||||
return MeterProduct.IperlLegacy;
|
||||
|
||||
return MeterProduct.Poseidon;
|
||||
}
|
||||
|
||||
public static bool TryParseMeter(
|
||||
string description,
|
||||
out SerialPortData.MeterProduct meter)
|
||||
{
|
||||
foreach (SerialPortData.MeterProduct value in
|
||||
Enum.GetValues(typeof(SerialPortData.MeterProduct)))
|
||||
{
|
||||
var attr = value.GetType()
|
||||
.GetField(value.ToString())
|
||||
.GetCustomAttribute<DescriptionAttribute>();
|
||||
|
||||
if (string.Equals(attr?.Description, description, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(value.ToString(), description, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
meter = value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
meter = SerialPortData.MeterProduct.Poseidon;
|
||||
return false;
|
||||
}
|
||||
|
||||
public enum MacroTypes
|
||||
{
|
||||
[Description("readall")]
|
||||
readall = 0,
|
||||
[Description("readmacro1")]
|
||||
macro1 = 1,
|
||||
[Description("readmacro2")]
|
||||
macro2 = 2,
|
||||
[Description("readmacro3")]
|
||||
macro3 = 3
|
||||
}
|
||||
|
||||
public enum HatType
|
||||
{
|
||||
[Description("Mth")]
|
||||
Mth = 0,
|
||||
[Description("Harry")]
|
||||
Harry = 1
|
||||
}
|
||||
|
||||
public enum MeterProduct
|
||||
{
|
||||
[Description("Poseidon")]
|
||||
[XmlEnum("74")]
|
||||
Poseidon = 74,
|
||||
|
||||
[Description("ally")]
|
||||
[XmlEnum("ally")]
|
||||
Ally = 75,
|
||||
|
||||
[Description("iperlplus")]
|
||||
[XmlEnum("iperlplus")]
|
||||
IperlPlus = 76,
|
||||
|
||||
[Description("iperllegacy")]
|
||||
[XmlEnum("iperllegacy")]
|
||||
IperlLegacy = 77
|
||||
}
|
||||
|
||||
public enum EMeterArg
|
||||
{
|
||||
Calibration = 0,
|
||||
AllParams = 2,
|
||||
DeviceId = 3,
|
||||
}
|
||||
EMeterArg _eMeterArg = EMeterArg.AllParams;
|
||||
|
||||
// New macro operations - just waste
|
||||
ReadMacro1 = 10,
|
||||
ReadMacro2 = 11,
|
||||
ReadMacro3 = 12
|
||||
}
|
||||
|
||||
public string DefaultArgSettings(EMeterArg eMeterArg)
|
||||
public string DefaultArgSettings(EMeterArg eMeterArg)
|
||||
{
|
||||
string commonArgs = BuildCommonArgs();
|
||||
|
||||
switch (eMeterArg)
|
||||
{
|
||||
case EMeterArg.Calibration:
|
||||
return $"-p {PortName} -m {MeterType} --operation write --parameter Calibration --value 1";
|
||||
case EMeterArg.AllParams:
|
||||
return $"-p {PortName} -m {MeterType} --operation readall";
|
||||
return $"{commonArgs} --operation write --parameter Calibration --value 1";
|
||||
|
||||
case EMeterArg.DeviceId:
|
||||
return $"-p {PortName} -m {MeterType} --operation read --parameter DeviceId";
|
||||
return $"{commonArgs} --operation read --parameter DeviceId";
|
||||
|
||||
case EMeterArg.AllParams:
|
||||
case EMeterArg.ReadMacro1:
|
||||
case EMeterArg.ReadMacro2:
|
||||
case EMeterArg.ReadMacro3:
|
||||
return $"{commonArgs} --operation {Macro}";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private string BuildCommonArgs()
|
||||
{
|
||||
return $"-p {PortName} " +
|
||||
$"-m {GetMeterArgument()} " +
|
||||
$"--hat {GetHatArgument()} " +
|
||||
$"--timeout {TimeoutSeconds}";
|
||||
}
|
||||
|
||||
private string GetMeterArgument()
|
||||
{
|
||||
// Old compatibility mode
|
||||
if (OldMeterType.HasValue)
|
||||
return OldMeterType.Value.ToString();
|
||||
|
||||
switch (Meter)
|
||||
{
|
||||
case MeterProduct.Poseidon:
|
||||
return "74"; //return "Poseidon";
|
||||
|
||||
case MeterProduct.Ally:
|
||||
return "ally";
|
||||
|
||||
case MeterProduct.IperlPlus:
|
||||
return "iperlplus";
|
||||
|
||||
case MeterProduct.IperlLegacy:
|
||||
return "iperllegacy";
|
||||
|
||||
default:
|
||||
return "74"; //return "Poseidon";
|
||||
}
|
||||
}
|
||||
|
||||
private string GetHatArgument()
|
||||
{
|
||||
switch (Hat)
|
||||
{
|
||||
case HatType.Harry:
|
||||
return "harry";
|
||||
|
||||
case HatType.Mth:
|
||||
default:
|
||||
return "mth";
|
||||
}
|
||||
}
|
||||
|
||||
// New constructor for v2.0
|
||||
public SerialPortData(
|
||||
string portName,
|
||||
string cmdClientName,
|
||||
MeterProduct meter = MeterProduct.Poseidon,
|
||||
HatType hat = HatType.Mth,
|
||||
int timeoutSeconds = 10,
|
||||
string macro = "readall")
|
||||
{
|
||||
PortName = portName;
|
||||
CmdClientName = cmdClientName;
|
||||
Meter = meter;
|
||||
Hat = hat;
|
||||
TimeoutSeconds = timeoutSeconds;
|
||||
Macro = macro;
|
||||
}
|
||||
|
||||
// Old constructor kept for backward compatibility
|
||||
public SerialPortData(
|
||||
string portName,
|
||||
string cmdClientName,
|
||||
@@ -53,7 +264,9 @@ namespace TBF.Rig.RegisterReaders.PoseidonCmdStartStop
|
||||
{
|
||||
PortName = portName;
|
||||
CmdClientName = cmdClientName;
|
||||
MeterType = meterType;
|
||||
OldMeterType = meterType;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ using System;
|
||||
using System.IO;
|
||||
using System.IO.Ports;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms.VisualStyles;
|
||||
using System.Xml.Linq;
|
||||
using Common;
|
||||
using Common.Iperl;
|
||||
@@ -12,8 +11,6 @@ using NHibernate;
|
||||
using Sensus.iPerl.NfcHandler;
|
||||
using TBF.Rig.Generic;
|
||||
using TBF.Rig.GenericDevices;
|
||||
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7;
|
||||
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.common;
|
||||
using CalibrationStruct = TBF.Rig.RegisterReaders.CommonRR.IPerl.communication.CalibrationStruct;
|
||||
@@ -48,7 +45,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
readonly PoseidonCfg _poseidonCfg;
|
||||
|
||||
|
||||
public PoseidonCfg RegPoseidonCfg { get { return _poseidonCfg; } }
|
||||
public int RfidComPortNr { get { return _poseidonCfg.RfidComPortNr; } }
|
||||
public int OptoComPortNr { get { return _poseidonCfg.OptoComPortNr; } }
|
||||
public MeterType MeterType { get { return _poseidonCfg.MeterType; } }
|
||||
@@ -90,21 +86,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
|
||||
float[] x;
|
||||
public float[] X { get { return x; } }
|
||||
|
||||
|
||||
|
||||
// Volume of water from the opto telegram
|
||||
private DateTime _firstSampleTime;
|
||||
private DateTime _lastSampleTime;
|
||||
|
||||
private double _averageFlow;
|
||||
private long _averageFlowCount;
|
||||
private readonly object _avgLock = new object();
|
||||
private bool _optoheadStarted = false;
|
||||
|
||||
private OptoHeadService _optoHeadService;
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Passed to OptoTelegramRaw.UpdateFromString(...)
|
||||
@@ -183,7 +164,9 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
///
|
||||
/// Timestamp from the opto telegram
|
||||
///
|
||||
|
||||
private Int64 lastTimestamp;
|
||||
private double timestampSec;
|
||||
private double timestampSec0;
|
||||
|
||||
int timeFromStart; /// [s] Time from test start to determine when the test start sample should be taken
|
||||
|
||||
@@ -191,22 +174,12 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
/// Test start volume for metrology in seconds
|
||||
public double TimestampSecStart
|
||||
{
|
||||
get
|
||||
{
|
||||
return _lastSampleTime != DateTime.MinValue ? 1 : 0; // return one second if is initialized, 0 - is false
|
||||
//return TimeFromSamples(optoData, optoDataCount, TestStartTelegramIx, StartEndFilterSamplesCount2);
|
||||
}
|
||||
get { return TimeFromSamples(optoData, optoDataCount, TestStartTelegramIx, StartEndFilterSamplesCount2); }
|
||||
}
|
||||
/// Test end time for metrology in seconds
|
||||
public double TimestampSecEnd
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_lastSampleTime == DateTime.MinValue) return 0;
|
||||
TimeSpan delta = _lastSampleTime - _firstSampleTime;
|
||||
return (delta.TotalSeconds + 1);
|
||||
//return TimeFromSamples(optoData, optoDataCount, TestEndTelegramIx, StartEndFilterSamplesCount2);
|
||||
}
|
||||
get { return TimeFromSamples(optoData, optoDataCount, TestEndTelegramIx, StartEndFilterSamplesCount2); }
|
||||
}
|
||||
///
|
||||
public bool NoSamples
|
||||
@@ -224,20 +197,12 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
/// Test start volume for metrology in liters
|
||||
public double VolumeLtrStart
|
||||
{
|
||||
get
|
||||
{
|
||||
return 0;
|
||||
//return NoSamples ? 0 : VolumeFromSamples(optoData, optoDataCount, TestStartTelegramIx, ScalingFactor(), StartEndFilterSamplesCount2);
|
||||
}
|
||||
get { return NoSamples ? 0 : VolumeFromSamples(optoData, optoDataCount, TestStartTelegramIx, ScalingFactor(), StartEndFilterSamplesCount2); }
|
||||
}
|
||||
/// Test end volume for metrology in liters
|
||||
public double VolumeLtrEnd
|
||||
{
|
||||
get
|
||||
{
|
||||
return wmVolume; // complet calculated volume (time * flowrate)
|
||||
//return NoSamples ? 0 : VolumeFromSamples(optoData, optoDataCount, TestEndTelegramIx, ScalingFactor(), StartEndFilterSamplesCount2);
|
||||
}
|
||||
get { return NoSamples ? 0 : VolumeFromSamples(optoData, optoDataCount, TestEndTelegramIx, ScalingFactor(), StartEndFilterSamplesCount2); }
|
||||
}
|
||||
|
||||
|
||||
@@ -309,10 +274,9 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
{
|
||||
if (_poseidonCfg != null)
|
||||
{
|
||||
|
||||
// OpenOptoSerialPort($"COM{_poseidonCfg.OptoComPortNr}", 9600, Parity.None, 8, StopBits.One,
|
||||
// Handshake.None);
|
||||
// CloseOptoSerialPort();
|
||||
OpenOptoSerialPort($"COM{_poseidonCfg.OptoComPortNr}", 9600, Parity.None, 8, StopBits.One,
|
||||
Handshake.None);
|
||||
CloseOptoSerialPort();
|
||||
log.FatalFormat($"{Name} initialized: {this}");
|
||||
}
|
||||
else
|
||||
@@ -437,16 +401,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
Q2CorrRL = 0;
|
||||
Q2CorrLR = 0;
|
||||
|
||||
|
||||
lock (_avgLock)
|
||||
{
|
||||
_firstSampleTime = DateTime.MinValue;
|
||||
_lastSampleTime = DateTime.MinValue;
|
||||
_averageFlow = 0;
|
||||
_averageFlowCount = 0;
|
||||
log.Debug("Initializing datastream state");
|
||||
}
|
||||
|
||||
simulatedPcbNr = null;
|
||||
|
||||
dataStreamState = DataStreamState.Flush;
|
||||
@@ -488,12 +442,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
{
|
||||
timeFromStart += StateMachine.Period;
|
||||
ReadPulses();
|
||||
|
||||
//TODO read flow
|
||||
if (_optoHeadService!= null && !_optoHeadService.IsRunning)
|
||||
StartOptohead();
|
||||
|
||||
|
||||
|
||||
if (!startSampleAcquired && (timeFromStart >= 8) && (currentTelegramIx >= 0))
|
||||
{
|
||||
@@ -514,94 +462,7 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
return Event.ReadRegisterDone;
|
||||
}
|
||||
|
||||
private void StartOptohead()
|
||||
{
|
||||
lock (_avgLock)
|
||||
{
|
||||
_firstSampleTime = DateTime.MinValue;
|
||||
_lastSampleTime = DateTime.MinValue;
|
||||
_averageFlow = 0;
|
||||
_averageFlowCount = 0;
|
||||
}
|
||||
|
||||
StartOptoTestInputLoop(new EventHandler<CommonRR.IPerl.communication.OptoReceivedEventArgs>(OnOptoHandler));
|
||||
}
|
||||
|
||||
private bool OpenOptoConnection(PoseidonCfg iHeadCfg)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (iHeadCfg != null)
|
||||
{
|
||||
if (_optoHeadService != null) return false;
|
||||
|
||||
OptoHeadService.Con connection = new OptoHeadService.Con($"COM{iHeadCfg.OptoComPortNr}", iHeadCfg.DebugLevel);
|
||||
_optoHeadService = new OptoHeadService(connection);
|
||||
return _optoHeadService.CreateSerialConnection();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool StartOptoTestInputLoop(EventHandler<CommonRR.IPerl.communication.OptoReceivedEventArgs> onOptoReceivedHandler)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_optoHeadService != null)
|
||||
{
|
||||
if (_optoHeadService.IsRunning) return false;
|
||||
|
||||
_optoHeadService.RunLoop(onOptoReceivedHandler);
|
||||
//run loop runstate = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
log.Error(ex.Message);
|
||||
throw ex;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void OnOptoHandler(object sender, CommonRR.IPerl.communication.OptoReceivedEventArgs e)
|
||||
{
|
||||
//received data from optohead
|
||||
WaterMetrologyData eWaterMetrologyData = e?.WaterMetrologyData;
|
||||
if (eWaterMetrologyData != null && eWaterMetrologyData.C7Data != null)
|
||||
{
|
||||
double flowRateLPerS = eWaterMetrologyData.C7Data?.FlowRateLPerS ?? 0;
|
||||
|
||||
lock (_avgLock)
|
||||
{
|
||||
if (_averageFlowCount == 0)
|
||||
{
|
||||
_firstSampleTime = eWaterMetrologyData.C7Data?.Dt ?? DateTime.Now;
|
||||
}
|
||||
|
||||
_lastSampleTime = eWaterMetrologyData.C7Data?.Dt ?? DateTime.Now;
|
||||
|
||||
_averageFlowCount++;
|
||||
|
||||
// Running average (no overflow)
|
||||
_averageFlow += (flowRateLPerS - _averageFlow) / _averageFlowCount;
|
||||
TimeSpan delta = _lastSampleTime - _firstSampleTime;
|
||||
if (delta.TotalMilliseconds == 0)
|
||||
wmVolume = 0;
|
||||
else
|
||||
wmVolume = _averageFlow * (delta.TotalMilliseconds / 1000); //volume in liters
|
||||
//wmVolume = Units.ConvertFrom(Unit.l, _averageFlow * (delta.TotalMilliseconds / 1000));
|
||||
log.Info("Calculated Value:" + wmVolume);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// <summary>
|
||||
/// Stop this operation
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
@@ -709,7 +570,78 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Q2 correction factor calculated from the last test (Q2).
|
||||
/// This factor should be used only for R800 meters.
|
||||
/// </summary>
|
||||
/// <param name="q2TestResult">A test result from which to calculate the factor</param>
|
||||
/// <param name="nominalFlow">Nominal flow in m3/h</param>
|
||||
/// <param name="currentFactor">0 or the current Q2 correction factor when updating the factor</param>
|
||||
/// <returns>Calculated Q2 correction factor</returns>
|
||||
public double CalculateQ2CorrectionFactor(Results.Entities.MeterTestRslt currentQ2Result, int currentFactor, double nominalFlow, double errorTarget = 0)
|
||||
{
|
||||
double nominalTestFlowLph = Units.ConvertTo(Unit.lph, nominalFlow);
|
||||
double volumeRefShiftedToTarget = currentQ2Result.VolumeRef * (1.0 + errorTarget / 100.0);
|
||||
double q2adjErrorShiftedToTarget = Config.Formulas.ErrorFromVolumes(currentQ2Result.VolumeMeter, volumeRefShiftedToTarget);
|
||||
|
||||
double A = 16.0 / ScalingFactor(); /// Raw units per ml: DN15=16, DN20=8, DN25=4, DN32=2, DN40=1
|
||||
const double B = 8.0; /// Raw units per minute, 8
|
||||
const double C = B * 60.0; /// Raw units per hour, 480
|
||||
double D = C / A; /// ml correction per hour
|
||||
double F = D / (nominalTestFlowLph * 10.0); /// Error corrected with 8 Raw Units per minute [%]
|
||||
double G = F / B; /// Error corrected with 1 Raw Unit per minute [%]
|
||||
|
||||
/// Do not change the factor for an invalid measurement (q2adjResult.VolumeMeter == 0)
|
||||
double q2CorrectionFactor = (Math.Abs(currentQ2Result.VolumeMeter) <= float.Epsilon) ? Convert.ToDouble(currentFactor) :
|
||||
Convert.ToDouble(currentFactor) - (q2adjErrorShiftedToTarget / G) * (volumeRefShiftedToTarget / currentQ2Result.VolumeMeter);
|
||||
|
||||
log.WarnFormat("CalculateQ2CorrectionFactor() : Pos={0}, PCB#={1}, Error={2}%, Target={3}%, Current factor={4} New factor={5}",
|
||||
Name,
|
||||
SerialNr,
|
||||
currentQ2Result.Error.ToString("F2"),
|
||||
errorTarget.ToString("F3"),
|
||||
currentFactor.ToString("F1"),
|
||||
q2CorrectionFactor.ToString("F1"));
|
||||
|
||||
return q2CorrectionFactor;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 2 Hz correction factor calculated from two Q3 tests - done at 2Hz and at 8Hz.
|
||||
/// This factors should be used only for DN32 and DN40 meters.
|
||||
/// </summary>
|
||||
/// <param name="resultAt2Hz">Test result @2Hz from which to calculate the factor</param>
|
||||
/// <param name="resultAt8Hz">Test result @8Hz from which to calculate the factor</param>
|
||||
/// <param name="hz2CorrectionFactor">The calculated Q2 correction factor</param>
|
||||
/// <returns>true = OK, false = failed</returns>
|
||||
public bool Calculate2HzCorrectionFactor(Results.Entities.MeterTestRslt resultAt2Hz,
|
||||
Results.Entities.MeterTestRslt resultAt8Hz,
|
||||
out double diff2Hz8Hz, out int hz2CorrectionFactor)
|
||||
{
|
||||
hz2CorrectionFactor = 0;
|
||||
diff2Hz8Hz = 0;
|
||||
|
||||
if ((resultAt2Hz == null) || (resultAt8Hz == null))
|
||||
{
|
||||
return false; /// Test result @2Hz and/or @8Hz is missing ==> water meter failed
|
||||
}
|
||||
|
||||
diff2Hz8Hz = resultAt2Hz.Error - resultAt8Hz.Error;
|
||||
|
||||
if (Math.Abs(diff2Hz8Hz) > 2.5) return false; /// Difference of errors > 2.5 % ==> water meter failed
|
||||
|
||||
hz2CorrectionFactor = -1 * (int)Math.Round(10 * diff2Hz8Hz);
|
||||
|
||||
log.WarnFormat("2Hz correction: Pos={0}, PCB#={1}, corrFactor={2}, erro@2Hz={3}%, erro@8Hz={4}%",
|
||||
Name,
|
||||
SerialNr,
|
||||
hz2CorrectionFactor,
|
||||
resultAt2Hz.Error.ToString("F2"),
|
||||
resultAt8Hz.Error.ToString("F2"));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -771,24 +703,147 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
/// <param name="optoState">OptoState.Read or OptoState.Flush</param>
|
||||
void ReadOptoData(DataStreamState optoState)
|
||||
{
|
||||
|
||||
// lock (this)
|
||||
// {
|
||||
//
|
||||
// }
|
||||
if (optoSerialPort is null) return;
|
||||
lock (this)
|
||||
{
|
||||
int nrBytes = optoSerialPort.BytesToRead;
|
||||
if (nrBytes > 0)
|
||||
{
|
||||
char[] buffer = new char[nrBytes];
|
||||
optoSerialPort.Read(buffer, 0, nrBytes);
|
||||
string received = new string(buffer);
|
||||
|
||||
string allRcvd = partOfTelegram + received;
|
||||
|
||||
while (true)
|
||||
{
|
||||
int pos = allRcvd.IndexOf("\r\n");
|
||||
|
||||
if (pos < 0)
|
||||
{
|
||||
/// No CR+LF found, wait for more characters in the next invocation
|
||||
partOfTelegram = allRcvd;
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
/// CR+LF found
|
||||
if (optoState == DataStreamState.ProcessAndSave)
|
||||
{
|
||||
int bufferIx = BufferIdx(optoDataCount);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
optoDataCount++;
|
||||
}
|
||||
else /// optoState == OptoState.Flush
|
||||
{
|
||||
if (pos < OptoTelegramRaw.Length - 2)
|
||||
{
|
||||
/// CR+LF found too early, truncate the beginning incl CR+LF and keep scanning in this loop
|
||||
allRcvd = allRcvd.Substring(pos + 2);
|
||||
synchronized = true;
|
||||
}
|
||||
// CR+LF found and (pos >= OptoTelegram.Length - 2)
|
||||
else if (toBeFlushed.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//OnOptoReceived(this, new OptoReceivedEventArgs(s));
|
||||
}
|
||||
else
|
||||
{
|
||||
//OnOptoReceived(this, new OptoReceivedEventArgs("."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string ReadOptoData()
|
||||
{
|
||||
if (optoSerialPort is null) return "";
|
||||
string received = ".";
|
||||
// lock (this)
|
||||
// {
|
||||
//
|
||||
// }
|
||||
lock (this)
|
||||
{
|
||||
int nrBytes = optoSerialPort.BytesToRead;
|
||||
if (nrBytes > 0)
|
||||
{
|
||||
char[] buffer = new char[nrBytes];
|
||||
optoSerialPort.Read(buffer, 0, nrBytes);
|
||||
received = new string(buffer);
|
||||
}
|
||||
}
|
||||
return received;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void OptoTelegramReceived(int currentIx, bool async, Int64 volumeRawExt, Int64 timestampRawExt)
|
||||
{
|
||||
currentTelegramIx = currentIx;
|
||||
|
||||
lastVolumeRaw = volumeRawExt;
|
||||
lastTimestamp = timestampRawExt;
|
||||
|
||||
if (volumeLtr == 0 && volumeLtr0 == 0)
|
||||
{
|
||||
volumeLtr = (double)lastVolumeRaw * ScalingFactor() / 16000.0;
|
||||
volumeLtr0 = volumeLtr;
|
||||
}
|
||||
else
|
||||
{
|
||||
volumeLtr = (double)lastVolumeRaw * ScalingFactor() / 16000.0;
|
||||
}
|
||||
|
||||
if (timestampSec == 0 && timestampSec0 == 0)
|
||||
{
|
||||
timestampSec = (double)lastTimestamp / 8192.0;
|
||||
timestampSec0 = timestampSec;
|
||||
}
|
||||
else
|
||||
{
|
||||
timestampSec = (double)lastTimestamp / 8192.0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -947,15 +1002,12 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
|
||||
void ReadPulses()
|
||||
{
|
||||
TimeSpan delta = _lastSampleTime - _firstSampleTime;
|
||||
double volume = _averageFlow * (delta.TotalMilliseconds / 1000);
|
||||
//log.Debug("ReadPulses - Calculated Value:" + volume);
|
||||
beginWMState = 1;
|
||||
endWMState = beginWMState + volume ;
|
||||
beginWMState = volumeLtr0;
|
||||
endWMState = volumeLtr;
|
||||
wmVolume = Math.Abs(endWMState - beginWMState);
|
||||
wmPulses = (int)(wmVolume * (double)PulsesPerLtr + 0.5);
|
||||
wmRefPulses = StateMachine.ControlBoardMain.RefPulses;
|
||||
wmTestTime = delta.TotalSeconds;
|
||||
wmTestTime = timestampSec - timestampSec0;
|
||||
}
|
||||
|
||||
private void OpenOptoSerialPort(string comPort, int baudRate, Parity parity, int dataBits, StopBits stopBit, Handshake handshake)
|
||||
@@ -966,7 +1018,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
/// Open serial port: 9600 Bd, 8 data bits, 1 stop bit, no parity
|
||||
try
|
||||
{
|
||||
|
||||
CloseOptoSerialPort();
|
||||
optoSerialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBit);
|
||||
optoSerialPort.Handshake = handshake;
|
||||
@@ -988,15 +1039,12 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
|
||||
private void CloseOptoSerialPort()
|
||||
{
|
||||
if (_optoHeadService != null)
|
||||
if (optoSerialPort != null)
|
||||
{
|
||||
_optoHeadService.CloseSerialConnection();
|
||||
_optoHeadService = null;
|
||||
optoSerialPort.Close();
|
||||
optoSerialPort = null;
|
||||
log.FatalFormat($"{Name} OptoPort closed: {this}");
|
||||
}
|
||||
|
||||
|
||||
communication.OpticalHeadTest.SetActiveMode(_poseidonCfg);
|
||||
}
|
||||
|
||||
|
||||
@@ -1008,14 +1056,10 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
{
|
||||
try
|
||||
{
|
||||
//set test mode via the cli
|
||||
communication.OpticalHeadTest.SetTestMode(_poseidonCfg);
|
||||
//open opto serial port
|
||||
OpenOptoConnection(_poseidonCfg);
|
||||
OpenOptoSerialPort($"COM{_poseidonCfg.OptoComPortNr}", 9600, Parity.None, 8, StopBits.One, Handshake.None);
|
||||
}
|
||||
catch (Exception e)
|
||||
catch (Exception)
|
||||
{
|
||||
log.Error($"{Name} OptoPort - error opening port: {_poseidonCfg.OptoComPortNr}, Details: {e.Message}");
|
||||
}
|
||||
/// Reset opto-data, etc.
|
||||
optoDataCount = 0;
|
||||
@@ -1438,7 +1482,8 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
|
||||
volumeLtr = 0;
|
||||
volumeLtr0 = 0;
|
||||
|
||||
timestampSec = 0;
|
||||
timestampSec0 = 0;
|
||||
|
||||
extraDataPath = null;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
using log4net;
|
||||
using TBF.Rig.RegisterReaders.CommonRR.IPerl.communication;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI.common;
|
||||
using TBF.Rig.RegisterReaders.PoseidonReader.implementations;
|
||||
@@ -11,6 +12,7 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
{
|
||||
public partial class UniHeadTestCtrl : UserControl
|
||||
{
|
||||
private static readonly ILog log = LogManager.GetLogger(typeof(UniHeadTestCtrl));
|
||||
private IUniHeadTestCtrl _ctrl;
|
||||
private IUniHeadTestCtrl Ctrl { get => _ctrl; }
|
||||
|
||||
@@ -77,6 +79,12 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader
|
||||
RfidOutputListBox = rfidOutputListBox
|
||||
});
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// A device/CLI communication failure must not terminate Application.Run.
|
||||
log.Error("Poseidon head test command failed.", exception);
|
||||
rfidOutputListBox.Items.Add("Error: " + exception.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
commandTestButton.Enabled = true;
|
||||
|
||||
@@ -2,7 +2,7 @@ using System;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using log4net;
|
||||
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Utils;
|
||||
using CliRunner = TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Utils.CliRunnerOld;
|
||||
using OptoHeadStatus = TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols.OptoHeadStatus;
|
||||
using SerialPortData = TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Utils.SerialPortData;
|
||||
@@ -13,7 +13,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
public class NfcHeadServiceOld
|
||||
{
|
||||
|
||||
private static readonly ILog log = LogManager.GetLogger(typeof(NfcHeadServiceOld));
|
||||
private bool activeHandlerSessioEnabled = false;
|
||||
private CliRunner _cliRunner;
|
||||
|
||||
@@ -209,8 +208,7 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
}
|
||||
else
|
||||
{
|
||||
log.Error($"Failed to parse OptoHeadStatus from output. Result: {result}");
|
||||
//throw new Exception($"Failed to parse OptoHeadStatus from output. Result: {result}");
|
||||
throw new Exception($"Failed to parse OptoHeadStatus from output. Result: {result}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using System.Threading.Tasks;
|
||||
using Common;
|
||||
using log4net;
|
||||
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols;
|
||||
using TBF.Rig.Sequences;
|
||||
using SERIAL_Driver = TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Utils.SERIAL_Driver;
|
||||
using WaterMetrologyData = TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols.WaterMetrologyData;
|
||||
|
||||
@@ -12,11 +8,9 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
{
|
||||
public class OptoHeadService
|
||||
{
|
||||
static readonly ILog log = LogManager.GetLogger("PoseidonConnection");
|
||||
|
||||
|
||||
public class Con
|
||||
{
|
||||
|
||||
public string com = "COM5";
|
||||
public int baudrate = 38400;
|
||||
public int dataBits = 8;
|
||||
@@ -24,8 +18,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
public StopBits stopbits = StopBits.Two;
|
||||
public int readTimeout = 5000;
|
||||
public int writeTimeout = 1000;
|
||||
private DebugMode _debugLevel;
|
||||
public DebugMode DebugModeSetting { get => _debugLevel; }
|
||||
|
||||
public Con(string com, int baudrate, int dataBits, Parity parity, StopBits stopbits, int readTimeout,
|
||||
int writeTimeout) : this(com)
|
||||
@@ -37,23 +29,10 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
this.readTimeout = readTimeout;
|
||||
this.writeTimeout = writeTimeout;
|
||||
}
|
||||
|
||||
public Con(DebugMode debugLevel,string com, int baudrate, int dataBits, Parity parity, StopBits stopbits, int readTimeout,
|
||||
int writeTimeout) : this(com)
|
||||
{
|
||||
this._debugLevel = debugLevel;
|
||||
this.baudrate = baudrate;
|
||||
this.dataBits = dataBits;
|
||||
this.parity = parity;
|
||||
this.stopbits = stopbits;
|
||||
this.readTimeout = readTimeout;
|
||||
this.writeTimeout = writeTimeout;
|
||||
}
|
||||
|
||||
public Con(string com, DebugMode debugLevel = DebugMode.Normal)
|
||||
public Con(string com)
|
||||
{
|
||||
this.com = com;
|
||||
this._debugLevel = debugLevel;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,19 +55,11 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
OnOptoReceivedHandler = null;
|
||||
bool isopen = false;
|
||||
Con con = Connection;
|
||||
if (con == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] message = {0x00};
|
||||
byte[] bytesReceived;
|
||||
|
||||
if (con?.DebugModeSetting == DebugMode.Simulate)
|
||||
{
|
||||
isopen = true;
|
||||
}
|
||||
else if (!driver.isOpen())
|
||||
if (!driver.isOpen())
|
||||
{
|
||||
|
||||
isopen = driver.OpenConnection(
|
||||
@@ -101,8 +72,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
con.writeTimeout);
|
||||
}
|
||||
|
||||
_bRunStarted = false;
|
||||
|
||||
return isopen;
|
||||
}
|
||||
|
||||
@@ -110,39 +79,24 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
{
|
||||
dissableRunLoop = true;
|
||||
OnOptoReceivedHandler = null;
|
||||
if (Connection?.DebugModeSetting != DebugMode.Simulate)
|
||||
{
|
||||
driver.Close();
|
||||
}
|
||||
_bRunStarted = false;
|
||||
driver.Close();
|
||||
OnOptoReceivedHandler = null;
|
||||
}
|
||||
|
||||
private EventHandler<CommonRR.IPerl.communication.OptoReceivedEventArgs> OnOptoReceivedHandler;
|
||||
|
||||
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get { return !dissableRunLoop
|
||||
&& ((Connection?.DebugModeSetting != DebugMode.Simulate) ? driver.isOpen() : true)
|
||||
&& _bRunStarted;}
|
||||
}
|
||||
|
||||
public void RunLoop(EventHandler<CommonRR.IPerl.communication.OptoReceivedEventArgs> onOptoReceivedHandler)
|
||||
{
|
||||
log.Debug("RunLoop started on event!");
|
||||
OnOptoReceivedHandler = onOptoReceivedHandler;
|
||||
Task.Run(() => Run());
|
||||
}
|
||||
|
||||
public void RunLoop()
|
||||
{
|
||||
log.Debug("RunLoop started!");
|
||||
Task.Run(() => Run());
|
||||
}
|
||||
|
||||
private bool dissableRunLoop = false;
|
||||
private bool _bRunStarted = false;
|
||||
/// <summary>
|
||||
/// Run the service. Catch one communication to WaterMetrologyData field.
|
||||
/// </summary>
|
||||
@@ -150,12 +104,10 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
{
|
||||
while (!dissableRunLoop)
|
||||
{
|
||||
_bRunStarted = true;
|
||||
WaterMetrologyData = ParseData(RunReading());
|
||||
if (OnOptoReceivedHandler != null && WaterMetrologyData != null)
|
||||
{
|
||||
log.Debug($"Received OptoData: {WaterMetrologyData}");
|
||||
OnOptoReceivedHandler?.Invoke(this, new CommonRR.IPerl.communication.OptoReceivedEventArgs(WaterMetrologyData?.ToString(), WaterMetrologyData));
|
||||
OnOptoReceivedHandler.Invoke(this, new CommonRR.IPerl.communication.OptoReceivedEventArgs(WaterMetrologyData.ToString()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,20 +115,13 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
|
||||
byte[] RunReading()
|
||||
{
|
||||
if (Connection?.DebugModeSetting != DebugMode.Simulate)
|
||||
{
|
||||
return new byte[] {0x00};
|
||||
}
|
||||
if (driver.isOpen())
|
||||
{
|
||||
driver.SendMessage(new byte[] {0x00}, 1);
|
||||
byte[] rawData = driver.GetRawData();
|
||||
log.Debug($"Received data size: {rawData?.Length ?? 0} bytes, raw data: {(rawData==null? "" :BitConverter.ToString(rawData))}");
|
||||
return rawData;
|
||||
return driver.GetRawData();
|
||||
}
|
||||
else
|
||||
{
|
||||
log.Debug("Serial port is not open.");
|
||||
dissableRunLoop = true;
|
||||
}
|
||||
|
||||
@@ -185,10 +130,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7
|
||||
|
||||
public WaterMetrologyData ParseData(byte[] data)
|
||||
{
|
||||
if (Connection?.DebugModeSetting != DebugMode.Simulate)
|
||||
{
|
||||
return WaterMetrologyData.SimulateC7();
|
||||
}
|
||||
try
|
||||
{
|
||||
if (data == null || data.Length == 0)
|
||||
|
||||
+1
-16
@@ -1,5 +1,5 @@
|
||||
using System;
|
||||
|
||||
using NfcC7_DLL.NfcHandler.Protocols;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols
|
||||
{
|
||||
@@ -37,21 +37,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols
|
||||
return waterMetrologyData;
|
||||
}
|
||||
|
||||
public static WaterMetrologyData SimulateC7()
|
||||
{
|
||||
WaterMetrologyData waterMetrologyData = new WaterMetrologyData();
|
||||
waterMetrologyData.c7Data = WaterMetrologyDataC7.Simulate();
|
||||
return waterMetrologyData;
|
||||
}
|
||||
|
||||
public static WaterMetrologyData SimulateC2()
|
||||
{
|
||||
WaterMetrologyData waterMetrologyData = new WaterMetrologyData();
|
||||
waterMetrologyData.c2Data = WaterMetrologyDataC2.Simulate();
|
||||
return waterMetrologyData;
|
||||
}
|
||||
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"Status: {_optoHeadStatus}, C7Data: {c7Data}, C2Data: {c2Data}";
|
||||
|
||||
+1
-37
@@ -21,17 +21,7 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols
|
||||
public bool FastHPFC { get; set; }
|
||||
public bool FieldPolarity { get; set; }
|
||||
public bool ImpedancePolarity { get; set; }
|
||||
|
||||
|
||||
public double FlowRateLPerS // Flow Rate in L/s metric units
|
||||
{
|
||||
get
|
||||
{
|
||||
double flowRateGPM = FlowRate / 10000; //investigation flow meter GPM
|
||||
double flowRateLPerS = flowRateGPM * 0.063090196432096 ; // conversion factor from GPM to L/s with minimal digit lost
|
||||
return flowRateLPerS;
|
||||
}
|
||||
}
|
||||
|
||||
public double CalcFlowmLps
|
||||
{
|
||||
get { return FlowRate / 4.0; } // FlowRate is in 1/4 mL/s
|
||||
@@ -51,32 +41,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols
|
||||
return Parse(data, dt, dutinfo);
|
||||
}
|
||||
|
||||
public static WaterMetrologyDataC2 Simulate()
|
||||
{
|
||||
var result = new WaterMetrologyDataC2();
|
||||
|
||||
result.DutInfo = "dutinfo";
|
||||
result.Dt = DateTime.Now;
|
||||
result.AdcSample = 1;
|
||||
result.LastField = 2;
|
||||
result.FlowRate = 12456;
|
||||
result.Accumulator = 789465;
|
||||
result.FlipPeriod = 1;
|
||||
result.VinfStart = 0;
|
||||
result.VinfEnd = 0;
|
||||
result.ElectrodeDelta = 1;
|
||||
result.Impedance = 1;
|
||||
result.FieldDriveTime = 0x00 ;
|
||||
|
||||
result.IsInLowFlow = false;
|
||||
result.IsInEmptyPipe = false;
|
||||
result.FastHPFC = false; // Fast High Pass Filter Constant in bit 2
|
||||
result.FieldPolarity = false; // Field Polarity in bit 3
|
||||
result.ImpedancePolarity = false; // Impedance Polarity in bit 4
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static WaterMetrologyDataC2 Parse(byte[] data, DateTime dt, string dutinfo)
|
||||
{
|
||||
if (data.Length < 24)
|
||||
|
||||
-41
@@ -23,47 +23,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Protocols
|
||||
public bool IsLearningActive { get; set; }
|
||||
public bool AdcShiftsUpdated { get; set; }
|
||||
|
||||
public static WaterMetrologyDataC7 Simulate()
|
||||
{
|
||||
var result = new WaterMetrologyDataC7();
|
||||
|
||||
result.DutInfo = "dutinfo";
|
||||
result.Dt = DateTime.Now;
|
||||
result.AdcSample = 1;
|
||||
result.LastField = 2;
|
||||
result.FlowRate = 12456;
|
||||
result.Accumulator = 789465;
|
||||
result.FlipPeriod = 1;
|
||||
result.VinfStart = 0;
|
||||
result.VinfEnd = 0;
|
||||
result.ElectrodeDelta = 1;
|
||||
result.Impedance = 1;
|
||||
result.FieldDriveTime = 0x00 ;
|
||||
|
||||
result.IsInLowFlow = false;
|
||||
result.IsInEmptyPipe = false;
|
||||
result.FastHPFC = false; // Fast High Pass Filter Constant in bit 2
|
||||
result.FieldPolarity = false; // Field Polarity in bit 3
|
||||
result.ImpedancePolarity = false; // Impedance Polarity in bit 4
|
||||
|
||||
result.MagTamperState = true; // bits 5 and 6 represent MagTamperState
|
||||
result.IsLearningActive = true; // bit 7 represents IsLearningActive
|
||||
|
||||
|
||||
|
||||
result.AdcShiftsUpdated = false; // bit 0 represents AdcShiftsUpdated
|
||||
|
||||
result.LastFieldmilliGauss = 0;
|
||||
result.ImpedanceI = 0; // in phase
|
||||
result.ImpedanceQ = 0; // out of phase
|
||||
result.NoiseMetric = 0; //
|
||||
result.LearningLockout = 0;
|
||||
result.ReverseBuffer = 0;
|
||||
result.ConditionedAdc = 0;
|
||||
result.Totalalizer = 0;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static WaterMetrologyDataC7 Parse(string base64Data, DateTime dt, string dutinfo)
|
||||
{
|
||||
|
||||
@@ -7,7 +7,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
using NfcC7_DLL.NfcHandler.Utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.PoseidonReader.communication.C7.Utils
|
||||
{
|
||||
|
||||
@@ -6,6 +6,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
|
||||
{
|
||||
[Description("..")] None,
|
||||
[Description("Nfc")] Nfc,
|
||||
[Description("cTouchRead")]Touched,
|
||||
[Description("Touch Capl")]Touched,
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
|
||||
internal class OpticalHeadTest
|
||||
{
|
||||
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
|
||||
|
||||
DebugMode _debugMode;
|
||||
public DebugMode DebugMode { get => _debugMode; set => _debugMode = value; }
|
||||
|
||||
internal static string OpenSealing(ISmartReader iHead)
|
||||
{
|
||||
@@ -29,11 +26,6 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
|
||||
|
||||
internal static string ReadRequest_SerialNo(PoseidonCfg iHeadCfg)
|
||||
{
|
||||
if (iHeadCfg != null && iHeadCfg.DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
return "1111";
|
||||
}
|
||||
|
||||
string serialNo = null;
|
||||
try
|
||||
{
|
||||
@@ -85,26 +77,26 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
|
||||
|
||||
internal static string SetActiveMode(PoseidonCfg iHeadCfg)
|
||||
{
|
||||
if (iHeadCfg != null && iHeadCfg.DebugLevel == DebugMode.Simulate)
|
||||
try
|
||||
{
|
||||
return "OK";
|
||||
SerialPortData serialPortData = new SerialPortData(
|
||||
$"COM{iHeadCfg.RfidComPortNr}",
|
||||
iHeadCfg.CliProgramName,
|
||||
iHeadCfg.CliMeterType);
|
||||
NfcHeadServiceOld headService = new NfcHeadServiceOld(serialPortData);
|
||||
OptoHeadStatus optoHeadStatus = headService.SetTestingMode(OptoHeadStatus.OptoHeadDisabled);
|
||||
if (optoHeadStatus == OptoHeadStatus.OptoHeadDisabled)
|
||||
{
|
||||
_lastOptoHeadStatus = optoHeadStatus;
|
||||
return "OK";
|
||||
}
|
||||
|
||||
return "Error Set Active Mode";
|
||||
}
|
||||
|
||||
SerialPortData serialPortData = new SerialPortData(
|
||||
$"COM{iHeadCfg.RfidComPortNr}",
|
||||
iHeadCfg.CliProgramName,
|
||||
iHeadCfg.CliMeterType);
|
||||
NfcHeadServiceOld headService = new NfcHeadServiceOld(serialPortData);
|
||||
// Wait synchronously
|
||||
OptoHeadStatus optoHeadStatus = headService.SetTestingMode(OptoHeadStatus.OptoHeadDisabled);
|
||||
if (optoHeadStatus == OptoHeadStatus.OptoHeadDisabled)
|
||||
catch (Exception exception)
|
||||
{
|
||||
_lastOptoHeadStatus = optoHeadStatus;
|
||||
return "OK";
|
||||
}
|
||||
else
|
||||
{
|
||||
return "Error Set Test Mode";
|
||||
rfidDataLogger.Error("Poseidon Set Active Mode failed.", exception);
|
||||
return "Error Set Active Mode: " + exception.Message;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,38 +105,34 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
|
||||
|
||||
internal static string SetTestMode(PoseidonCfg iHeadCfg)
|
||||
{
|
||||
if (iHeadCfg != null && iHeadCfg.DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
return "OK";
|
||||
}
|
||||
|
||||
SerialPortData serialPortData = new SerialPortData(
|
||||
$"COM{iHeadCfg.RfidComPortNr}",
|
||||
iHeadCfg.CliProgramName,
|
||||
iHeadCfg.CliMeterType);
|
||||
NfcHeadServiceOld headService = new NfcHeadServiceOld(serialPortData);
|
||||
// Wait synchronously
|
||||
OptoHeadStatus optoHeadStatus = headService.SetTestingMode(OptoHeadStatus.OptoHeadC7);
|
||||
if (optoHeadStatus == OptoHeadStatus.OptoHeadC7)
|
||||
{
|
||||
_lastOptoHeadStatus = optoHeadStatus;
|
||||
_lastIHeadCfg = iHeadCfg;
|
||||
return "OK";
|
||||
}
|
||||
else
|
||||
try
|
||||
{
|
||||
SerialPortData serialPortData = new SerialPortData(
|
||||
$"COM{iHeadCfg.RfidComPortNr}",
|
||||
iHeadCfg.CliProgramName,
|
||||
iHeadCfg.CliMeterType);
|
||||
NfcHeadServiceOld headService = new NfcHeadServiceOld(serialPortData);
|
||||
OptoHeadStatus optoHeadStatus = headService.SetTestingMode(OptoHeadStatus.OptoHeadC7);
|
||||
if (optoHeadStatus == OptoHeadStatus.OptoHeadC7)
|
||||
{
|
||||
_lastOptoHeadStatus = optoHeadStatus;
|
||||
_lastIHeadCfg = iHeadCfg;
|
||||
return "OK";
|
||||
}
|
||||
|
||||
return "Error Set Test Mode";
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
rfidDataLogger.Error("Poseidon Set Test Mode failed.", exception);
|
||||
return "Error Set Test Mode: " + exception.Message;
|
||||
}
|
||||
}
|
||||
|
||||
private static OptoHeadService optoHeadService;
|
||||
|
||||
public static void Deactivate()
|
||||
{
|
||||
if (_lastIHeadCfg != null && _lastIHeadCfg.DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
return;
|
||||
}
|
||||
StopOptoTestInputLoop();
|
||||
if (_lastOptoHeadStatus != OptoHeadStatus.Unknown &&
|
||||
_lastOptoHeadStatus != OptoHeadStatus.OptoHeadDisabled &&
|
||||
@@ -164,7 +152,7 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.communication
|
||||
{
|
||||
if (optoHeadService != null) return false;
|
||||
|
||||
OptoHeadService.Con connection = new OptoHeadService.Con($"COM{iHeadCfg.OptoComPortNr}", iHeadCfg.DebugLevel);
|
||||
OptoHeadService.Con connection = new OptoHeadService.Con($"COM{iHeadCfg.OptoComPortNr}");
|
||||
optoHeadService = new OptoHeadService(connection);
|
||||
optoHeadService.CreateSerialConnection();
|
||||
optoHeadService.RunLoop(onOptoReceivedHandler);
|
||||
|
||||
+13
-11
@@ -85,18 +85,20 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.implementations
|
||||
rfidListItem.Text = $"ReadSerialNo: {OpticalHeadTest.ReadRequest_SerialNo(poseidonCfg)}";
|
||||
break;
|
||||
case Operations.SetTestModeOn:
|
||||
rfidListItem.Text = $"SetTestMode: {OpticalHeadTest.SetTestMode(poseidonCfg)}";
|
||||
//Do start thread
|
||||
|
||||
a.OptoListBox.Items.Clear();
|
||||
stopWorkerThread = false;
|
||||
optoThread = new Thread(OptoWorker);
|
||||
if (!optoThread.IsAlive)
|
||||
string setTestModeResult = OpticalHeadTest.SetTestMode(poseidonCfg);
|
||||
rfidListItem.Text = $"SetTestMode: {setTestModeResult}";
|
||||
// Start the opto worker only after a successful mode change.
|
||||
if (setTestModeResult == "OK")
|
||||
{
|
||||
OpticalHeadTest.StartOptotestInputLoop(poseidonCfg,OptoReceivedHandler); // open opto port
|
||||
optoThread.Start();
|
||||
a.OptoListBox.Items.Clear();
|
||||
stopWorkerThread = false;
|
||||
optoThread = new Thread(OptoWorker);
|
||||
if (!optoThread.IsAlive)
|
||||
{
|
||||
OpticalHeadTest.StartOptotestInputLoop(poseidonCfg, OptoReceivedHandler);
|
||||
optoThread.Start();
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case Operations.SetTestModeOff:
|
||||
//Do stop thread
|
||||
@@ -133,4 +135,4 @@ namespace TBF.Rig.RegisterReaders.PoseidonReader.implementations
|
||||
this.stopWorkerThread = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using TBF.Rig.Generic;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.implementations;
|
||||
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader
|
||||
{
|
||||
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 SmartReader(); }
|
||||
|
||||
public IComponent GetComponent(IComponentCfg cfg, IList<IComponent> components) { return new SmartReader(cfg); }
|
||||
|
||||
public IComponentCfg DefaultConfig() { return new iPerlReaderUNI.IPerlCfg(this); } // TODO ????
|
||||
|
||||
public IComponentCfg CmpntCfgFromCmpntEntity(Config.Entities.Component component)
|
||||
{
|
||||
return ComponentCfgBase.CreateFromDbEntity(iPerlReaderUNI.IPerlCfg.Serializer, component, this); // TODO ????
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.CommonRR;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader
|
||||
{
|
||||
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 IPerlUniCfgCtrl();
|
||||
}
|
||||
|
||||
|
||||
|
||||
///
|
||||
/// 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,164 +0,0 @@
|
||||
///
|
||||
/// Copyright (c) 2015-2017 Sensus Metering Systems
|
||||
///
|
||||
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Windows.Forms;
|
||||
using Common;
|
||||
using TBF.Resources;
|
||||
using TBF.Rig.Generic;
|
||||
using TBF.Rig.RegisterReaders.CommonRR;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader
|
||||
{
|
||||
public partial class IPerlUniCfgCtrl : UserControl, IComponentCfgCtrl
|
||||
{
|
||||
public bool ShowMore { get { return false; } }
|
||||
|
||||
iPerlReaderUNI.IPerlCfg config;
|
||||
public IComponentCfg Config
|
||||
{
|
||||
get { return config as IComponentCfg; }
|
||||
set
|
||||
{
|
||||
config = value as iPerlReaderUNI.IPerlCfg;
|
||||
Redraw();
|
||||
}
|
||||
}
|
||||
|
||||
public IPerlUniCfgCtrl()
|
||||
{
|
||||
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 IperlASICUniHeadTestCtrl(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.iPerlASICReader
|
||||
{
|
||||
partial class IPerlUniCfgCtrl
|
||||
{
|
||||
/// <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 = "IPerlUniCfgCtrl";
|
||||
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>
|
||||
-137
@@ -1,137 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader
|
||||
{
|
||||
partial class IperlASICUniHeadTestCtrl
|
||||
{
|
||||
/// <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 = "IperlASICUniHeadTestCtrl";
|
||||
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,89 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
using TBF.Rig.RegisterReaders.CommonRR.IPerl.communication;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.implementations;
|
||||
using TBF.Rig.RegisterReaders.IPerlReader.implementations;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI.common;
|
||||
using TBF.Rig.Sequences;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader
|
||||
{
|
||||
public partial class IperlASICUniHeadTestCtrl : UserControl
|
||||
{
|
||||
private IUniHeadTestCtrl _ctrl;
|
||||
private IUniHeadTestCtrl Ctrl { get => _ctrl; }
|
||||
|
||||
|
||||
|
||||
|
||||
public IperlASICUniHeadTestCtrl(iPerlReaderUNI.IPerlCfg config)
|
||||
{
|
||||
this._ctrl = new IPerlASICImplHeadTestCtrl();
|
||||
Ctrl.config = config;
|
||||
InitializeComponent();
|
||||
if (config == null) return;
|
||||
|
||||
SmartCommunicationForm.TestMethodCfg = new TestMethodCfg(null); // default values for iPerlCommunication
|
||||
|
||||
foreach(var head in ProcessData.SmartHeadsUni)
|
||||
{
|
||||
if (head != null && head.Name == config.Name) { Ctrl.ISmartReader = head; }
|
||||
}
|
||||
|
||||
rfidCommandComboBox.DisplayMember = "Name";
|
||||
rfidCommandComboBox.ValueMember = "Value";
|
||||
var items = Ctrl.GetComboOperationsPairs();
|
||||
/*
|
||||
// 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.Select(i => i.Name).ToArray();
|
||||
|
||||
Ctrl.Initialize();
|
||||
|
||||
Ctrl.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)
|
||||
{
|
||||
Ctrl.CommandTestButtonClick(sender, e, new Arguments()
|
||||
{
|
||||
ISmartReader = Ctrl.ISmartReader,
|
||||
OptoListBox = optoListBox,
|
||||
RfidCommandComboBox = rfidCommandComboBox,
|
||||
RfidOutputListBox = rfidOutputListBox
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
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());
|
||||
Ctrl.Destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.IperlHatProtocol
|
||||
{
|
||||
public static class Constants
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.protocolCommons;
|
||||
using TBF.Rig.RegisterReaders.PoseidonReader.communication.C7;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 ? Constants.Write : Constants.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(Constants.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(
|
||||
Constants.Start,
|
||||
_direction,
|
||||
length,
|
||||
_commandBytes.ToArray(),
|
||||
_payload.ToArray(),
|
||||
Constants.End);
|
||||
}
|
||||
|
||||
public byte[] BuildBytes()
|
||||
{
|
||||
IperlHatFrame frame = BuildFrame();
|
||||
|
||||
if (frame.CommandInformation.Length > 0 && frame.CommandInformation[0] == Constants.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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
-133
@@ -1,133 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.hexLogger;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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] != Constants.Start)
|
||||
{
|
||||
//if version parse version
|
||||
if (data[0] == Constants.Question)
|
||||
{
|
||||
//Define Question answer
|
||||
var prefix = new List<byte>{ Constants.Question };
|
||||
var end = new List<byte>{ Constants.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>{ Constants.Question };
|
||||
byte[] payloadVersion = ExtractPayloadUsePrefix(data, prefix, end);
|
||||
return new IperlHatResponse(Constants.Question, payloadVersion.Length > 0 ? Constants.StatusOk : Constants.StatusNok, payloadVersion);
|
||||
}
|
||||
}
|
||||
|
||||
throw new FormatException("Invalid START byte.");
|
||||
}
|
||||
|
||||
if (data[1] != Constants.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>{ Constants.Start,direction,length,status };
|
||||
var endCommand = new List<byte>{ Constants.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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.IperlHatProtocol
|
||||
{
|
||||
public static class IperlHatProtocol
|
||||
{
|
||||
public const byte START = 0x0D;
|
||||
|
||||
// Control bits (CNTRL1)
|
||||
public const byte RESPONSE_FLAG = 0x08; // RF
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 == Constants.StatusOk;
|
||||
|
||||
public IperlHatResponse(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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
using System;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.parserer;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.protocolCommons;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.wiredProtocol;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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
|
||||
}
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 (two’s 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
|
||||
{
|
||||
|
||||
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 (two’s 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.
|
||||
/// </summary>
|
||||
public uint RawVolume { get; protected set; }
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 (two’s 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]);
|
||||
RawVolume = 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 (two’s 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 (0–4) ----
|
||||
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
|
||||
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
|
||||
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
|
||||
RawVolume = 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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 (two’s 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 (0–4) ----
|
||||
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
|
||||
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
|
||||
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
|
||||
RawVolume = 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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</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; }
|
||||
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 AsicState { get; }
|
||||
|
||||
public DiagnosticLedState4Data(string rawLine, string[] fields)
|
||||
: base(rawLine)
|
||||
{
|
||||
// ---- Common fields (0–4) ----
|
||||
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
|
||||
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
|
||||
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
|
||||
RawVolume = DiagnosticHex.ParseUInt24(fields[3]);
|
||||
CapacitorMv = DiagnosticHex.ParseUInt16(fields[4]);
|
||||
|
||||
// ---- State #4 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]);
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"DiagnosticLedState4Data: 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}";
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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]);
|
||||
RawVolume = 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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-152
@@ -1,152 +0,0 @@
|
||||
using System;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 (0–4) ----
|
||||
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
|
||||
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
|
||||
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
|
||||
RawVolume = 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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-155
@@ -1,155 +0,0 @@
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.utils;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 (0–4) ----
|
||||
Adc24 = DiagnosticHex.ParseInt24(fields[0]);
|
||||
FieldStrength = DiagnosticHex.ParseUInt16(fields[1]);
|
||||
RawFlow = DiagnosticHex.ParseInt16(fields[2]);
|
||||
RawVolume = 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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.parserer
|
||||
{
|
||||
public enum PipeStatus : byte
|
||||
{
|
||||
MetroLowFlowCut = 0,
|
||||
MetroFlowReverse = 1,
|
||||
MetroFlowForward = 2,
|
||||
MetroEmptyPipe = 3
|
||||
}
|
||||
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.parserer
|
||||
{
|
||||
public enum SpikeDetectionStatus : byte
|
||||
{
|
||||
NoSpike = 0,
|
||||
AdcSpike = 1,
|
||||
SpikeHoldOff = 2,
|
||||
SpikeHighFlow = 5
|
||||
}
|
||||
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.hexLogger
|
||||
{
|
||||
public static class HexFormatter
|
||||
{
|
||||
/// <summary>
|
||||
/// 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 0–9 -> 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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.hexLogger
|
||||
{
|
||||
public class IpelHatCommandDecoder
|
||||
{
|
||||
public static string DescribeCommand(byte command)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
public static string DescribeDirection(byte direction)
|
||||
{
|
||||
if (direction == IperlHatProtocol.Constants.Write)
|
||||
return "(WRITE - OUTGOING)";
|
||||
|
||||
if (direction == IperlHatProtocol.Constants.Read)
|
||||
return "(READ - INCOMING)";
|
||||
|
||||
return "INVALID CONTROL BITS (unsupported pattern)";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
using System;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.wiredProtocol;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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.Constants.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";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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)";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
using System;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.wiredProtocol;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.led
|
||||
{
|
||||
public interface ITouchReadLedParser
|
||||
{
|
||||
TouchReadLedData Parse(TouchReadLedMessage message);
|
||||
}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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(',');
|
||||
}
|
||||
}
|
||||
}
|
||||
-140
@@ -1,140 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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 0–12 byte ASCII string terminated by NULL.
|
||||
/// Response only if RF flag is set.
|
||||
/// </summary>
|
||||
ViewFactoryId = 0x01,
|
||||
|
||||
/// <summary>
|
||||
/// Set Factory ID (0–12 ASCII characters, NULL terminated).
|
||||
/// Protected by meter seal.
|
||||
/// </summary>
|
||||
SetFactoryId = 0x02,
|
||||
|
||||
/// <summary>
|
||||
/// View Customer Programmable ID (1–12 ASCII characters).
|
||||
/// </summary>
|
||||
ViewProgrammableId = 0x03,
|
||||
|
||||
/// <summary>
|
||||
/// Set Customer Programmable ID (1–12 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 (0–20 ASCII characters).
|
||||
/// </summary>
|
||||
ViewProgrammableText = 0x07,
|
||||
|
||||
/// <summary>
|
||||
/// Set Customer Programmable Text (0–20 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: 4–8, 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 (0–8 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,
|
||||
}
|
||||
}
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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="TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.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
|
||||
}
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.protocolCommons
|
||||
{
|
||||
public enum ProtocolStatuses : byte
|
||||
{
|
||||
Idle = 0x01,
|
||||
Active = 0x02,
|
||||
Inactive = 0x03,
|
||||
|
||||
}
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-125
@@ -1,125 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.protocolCommons;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.wiredProtocol
|
||||
{
|
||||
public static class TouchReadProtocol
|
||||
{
|
||||
public const byte START = 0x0D;
|
||||
|
||||
// Control bits (CNTRL1)
|
||||
public const byte RESPONSE_FLAG = 0x08; // RF
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using log4net;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication
|
||||
{
|
||||
public class OpthoHeadService
|
||||
{
|
||||
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using Common;
|
||||
using log4net;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.Utils;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.common;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication
|
||||
{
|
||||
public class OptoHeadTest : IDisposable
|
||||
{
|
||||
protected static readonly ILog rfidDataLogger = LogManager.GetLogger("RfidData");
|
||||
|
||||
private static SerialDriver serialDriver;
|
||||
|
||||
public static SerialDriver BuildConnection(ISmartReader iHead)
|
||||
{
|
||||
return new SerialDriverBuilder()
|
||||
.WithPort($"COM{iHead.RfidComPortNr}")
|
||||
.WithBaudRate(2400)
|
||||
.WithDataBits(8)
|
||||
.WithParity(Parity.None)
|
||||
.WithStopBits(StopBits.One)
|
||||
.WithTimeouts(4000, 2000)
|
||||
.BuildAndConnect();
|
||||
|
||||
}
|
||||
|
||||
public void CloseConnection()
|
||||
{
|
||||
if (serialDriver != null)
|
||||
serialDriver.CloseConnection();
|
||||
}
|
||||
|
||||
|
||||
public static string ReadRequest_PCB(ISmartReader iHead)
|
||||
{
|
||||
if (iHead.DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
return "-OK Simulated response-";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (iHead != null)
|
||||
{
|
||||
if (serialDriver == null)
|
||||
serialDriver = BuildConnection(iHead);
|
||||
|
||||
RadioService headService = new RadioService(serialDriver);
|
||||
string serialNo = headService.ReadRequest_PCB(iHead);
|
||||
return serialNo;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (ex.Message.ToString());
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
public static string SetTestMode(ISmartReader iHead)
|
||||
{
|
||||
if (iHead.DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
return "-OK Simulated response-";
|
||||
}
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
if (iHead != null)
|
||||
{
|
||||
if (serialDriver == null)
|
||||
serialDriver = BuildConnection(iHead);
|
||||
|
||||
RadioService headService = new RadioService(serialDriver);
|
||||
string answer = headService.SetTestMode(iHead);
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (ex.Message.ToString());
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
public static string SetActiveMode(ISmartReader iHead)
|
||||
{
|
||||
if (iHead.DebugLevel == DebugMode.Simulate)
|
||||
{
|
||||
return "-OK Simulated response-";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (iHead != null)
|
||||
{
|
||||
if (serialDriver == null)
|
||||
serialDriver = BuildConnection(iHead);
|
||||
|
||||
RadioService headService = new RadioService(serialDriver);
|
||||
string answer = headService.SetActiveMode(iHead);
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (ex.Message.ToString());
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
CloseConnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
using Common;
|
||||
using log4net;
|
||||
using TBF.Rig.Modbus.Meret.AdjustableScale;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.IperlHatProtocol;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.protocolCommons;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.wiredProtocol;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.Utils;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.common;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication
|
||||
{
|
||||
public class RadioService
|
||||
{
|
||||
|
||||
static string okResponse = "Command complete, no errors";
|
||||
static string errorResponse = "Unable to execute";
|
||||
|
||||
private SerialDriver serialDriver;
|
||||
public RadioService(SerialDriver serialDriver)
|
||||
{
|
||||
this.serialDriver = serialDriver;
|
||||
}
|
||||
|
||||
public string ReadRequest_PCB(ISmartReader 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)
|
||||
{
|
||||
return decoded.GetAsciiPayload();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public string SetTestMode(ISmartReader iHead)
|
||||
{
|
||||
if (!serialDriver.IsOpen())
|
||||
{
|
||||
serialDriver.Open();
|
||||
}
|
||||
|
||||
//Set LED to state 4
|
||||
byte[] request = new IperlHatFrameBuilder()
|
||||
.AddDiagnosticLedState(DiagnosticLedState.State4)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] rawData = serialDriver.SendAndWait(request, 1000);
|
||||
if (rawData == null)
|
||||
return null;
|
||||
|
||||
|
||||
// parse rawData
|
||||
var parser = new IperlHatFrameParser();
|
||||
IperlHatResponse decoded = parser.Parse(rawData);
|
||||
if (decoded.IsOk)
|
||||
{
|
||||
|
||||
|
||||
//correct or incorrect response
|
||||
//okResponse, errorResponse
|
||||
|
||||
return "Set Test Mode - OK";
|
||||
}
|
||||
|
||||
return "Set Test Mode - FAILED";
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// stop data streaming by LED
|
||||
/// </summary>
|
||||
/// <param name="iHead"></param>
|
||||
/// <returns></returns>
|
||||
public string SetActiveMode(ISmartReader iHead)
|
||||
{
|
||||
if (!serialDriver.IsOpen())
|
||||
{
|
||||
serialDriver.Open();
|
||||
}
|
||||
|
||||
//Set LED to state 1
|
||||
byte[] request = new IperlHatFrameBuilder()
|
||||
.AddDiagnosticLedState(DiagnosticLedState.StateOFF)
|
||||
.BuildBytes();
|
||||
|
||||
byte[] rawData = serialDriver.SendAndWait(request, 1000);
|
||||
if (rawData == null)
|
||||
return null;
|
||||
|
||||
|
||||
// parse rawData
|
||||
var parser = new IperlHatFrameParser();
|
||||
IperlHatResponse decoded = parser.Parse(rawData);
|
||||
if (decoded.IsOk)
|
||||
{
|
||||
|
||||
return "Set Active Mode - OK";
|
||||
}
|
||||
|
||||
return "Set Active Mode - FAILED";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,290 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO.Ports;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using FluentNHibernate.Conventions;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.hexLogger;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.communication.Utils
|
||||
{
|
||||
public class SerialDriver : IDisposable
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
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();
|
||||
_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.Constants.Start)
|
||||
{
|
||||
iWordCounter++;
|
||||
isStart = true;
|
||||
}
|
||||
// I have QUESTION
|
||||
if (readByte == C4.IperlHatProtocol.Constants.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)
|
||||
{
|
||||
break;
|
||||
}
|
||||
//if we read END
|
||||
if (isQuestion && readByte == C4.IperlHatProtocol.Constants.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");
|
||||
|
||||
PrepareReading();
|
||||
_serialPort.Write(data, 0, data.Length);
|
||||
|
||||
if (!_responseReceived.WaitOne(timeoutMs))
|
||||
{
|
||||
ErrorMessage = "COM error: response timeout";
|
||||
return null;
|
||||
}
|
||||
|
||||
return GetRawData();
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
CloseConnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Web.UI.WebControls;
|
||||
using System.Windows.Forms;
|
||||
using Common;
|
||||
using TBF.Rig.Generic;
|
||||
using TBF.Rig.RegisterReaders.CommonRR.IPerl.communication;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI.common;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI.test;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.common;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.implementations
|
||||
{
|
||||
public class IPerlASICImplHeadTestCtrl : IUniHeadTestCtrl
|
||||
{
|
||||
Thread optoThread;
|
||||
public ISmartReader ISmartReader { get; set; }
|
||||
public bool stopWorkerThread { get; set; }
|
||||
public event EventHandler<OptoReceivedEventArgs> OptoReceivedHandler;
|
||||
|
||||
public IComponentCfg
|
||||
|
||||
|
||||
config { get; set; }
|
||||
|
||||
public void Initialize()
|
||||
{
|
||||
stopWorkerThread = false;
|
||||
}
|
||||
|
||||
public void Destroy()
|
||||
{
|
||||
stopWorkerThread = true;
|
||||
if (optoThread != null)
|
||||
{
|
||||
optoThread.Abort();
|
||||
}
|
||||
}
|
||||
|
||||
private const string StrReadPcbCmd = "ReadPCB";
|
||||
private const string StrSetTestModeCmd = "SetTestMode";
|
||||
private const string StrSetActiveModeCmd = "SetActiveMode";
|
||||
private const string StrReadOptoDataCmd = "ReadOptoData";
|
||||
private const string StrStopReadOptoDataCmd = "StopReadOptoData";
|
||||
private const string StrResetNfcHeadCmd = "ResetNfcHead";
|
||||
private const string StrSetNfcHeadCmd = "SetNfcHead";
|
||||
private const string StrSetRfidHeadCmd = "SetRfidHead";
|
||||
private const string StrEmptyCmd = "";
|
||||
|
||||
public enum Operations
|
||||
{
|
||||
[Description(StrReadPcbCmd)]ReadPcbCmd,
|
||||
[Description(StrSetTestModeCmd)]SetTestModeCmd,
|
||||
[Description(StrSetActiveModeCmd)]SetActiveModeCmd,
|
||||
[Description(StrReadOptoDataCmd)]ReadOptoDataCmd,
|
||||
[Description(StrStopReadOptoDataCmd)]StopReadOptoDataCmd,
|
||||
[Description(StrResetNfcHeadCmd)]ResetNfcHeadCmd,
|
||||
[Description(StrSetNfcHeadCmd)]SetNfcHeadCmd,
|
||||
[Description(StrSetRfidHeadCmd)]SetRfidHeadCmd,
|
||||
[Description(StrEmptyCmd)]EmptyCmd
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static readonly Dictionary<string, Operations> ItemsForIperlOperations = new Dictionary<string, Operations>
|
||||
{
|
||||
{"Read PCB", Operations.ReadPcbCmd},
|
||||
{"Set Test Mode", Operations.SetTestModeCmd},
|
||||
{"Set Active Mode", Operations.SetActiveModeCmd},
|
||||
#if DEBUG
|
||||
{"Start Read Opto Data", Operations.ReadOptoDataCmd},
|
||||
{"Stop Read Opto Data", Operations.StopReadOptoDataCmd},
|
||||
#endif
|
||||
{" ", Operations.EmptyCmd},
|
||||
{"Reset NFC Head", Operations.ResetNfcHeadCmd},
|
||||
{"Set NFC Head Interface", Operations.SetNfcHeadCmd},
|
||||
{"Set RFID Head interface", Operations.SetRfidHeadCmd}
|
||||
};
|
||||
|
||||
public (string Name, string Value)[] GetComboOperationsPairs()
|
||||
{
|
||||
//return ItemsForIperlOperations.Select(kvp => (kvp.Key, kvp.Value)).ToArray();
|
||||
return ItemsForIperlOperations.Select(kvp => (kvp.Key, kvp.Value.ToDescription())).ToArray();
|
||||
}
|
||||
|
||||
public void CommandTestButtonClick(object sender, MouseEventArgs e, Arguments a)
|
||||
{
|
||||
a.RfidOutputListBox.Items.Clear();
|
||||
|
||||
using (Tools.LogChecker logChecker = new Tools.LogChecker("ASIC_RfidData", log4net.Core.Level.Debug))
|
||||
{
|
||||
ListItem rfidListItem = new ListItem();
|
||||
rfidListItem.Attributes.Add("style", "font-weight:bold");
|
||||
Operations selectedOperation;
|
||||
if(!ItemsForIperlOperations.TryGetValue((string)a.RfidCommandComboBox.SelectedValue, out selectedOperation))
|
||||
selectedOperation = Operations.EmptyCmd;
|
||||
|
||||
switch (selectedOperation)
|
||||
{
|
||||
case Operations.ReadPcbCmd:
|
||||
rfidListItem.Text = $"PCB: {OptoHeadTest.ReadRequest_PCB(a.ISmartReader)}";
|
||||
break;
|
||||
case Operations.SetTestModeCmd:
|
||||
rfidListItem.Text = OptoHeadTest.SetTestMode(a.ISmartReader);
|
||||
a.OptoListBox.Items.Clear();
|
||||
stopWorkerThread = false;
|
||||
optoThread = new Thread(OptoWorker);
|
||||
if (!optoThread.IsAlive)
|
||||
{
|
||||
a.ISmartReader.StartDataStreamProcessing(); // open opto port
|
||||
optoThread.Start();
|
||||
}
|
||||
|
||||
break;
|
||||
case Operations.SetActiveModeCmd:
|
||||
rfidListItem.Text = OptoHeadTest.SetActiveMode(a.ISmartReader);
|
||||
stopWorkerThread = true;
|
||||
a.ISmartReader.StopDataStreamProcessing(); // close opto port
|
||||
break;
|
||||
case Operations.ResetNfcHeadCmd:
|
||||
a.ISmartReader.ResetNfcInterface();
|
||||
break;
|
||||
case Operations.SetNfcHeadCmd:
|
||||
a.ISmartReader.SetNfcInterface();
|
||||
break;
|
||||
case Operations.SetRfidHeadCmd:
|
||||
a.ISmartReader.SetRfidInterface();
|
||||
break;
|
||||
case Operations.ReadOptoDataCmd:
|
||||
a.OptoListBox.Items.Clear();
|
||||
stopWorkerThread = false;
|
||||
optoThread = new Thread(OptoWorker);
|
||||
if (optoThread.IsAlive)
|
||||
{
|
||||
stopWorkerThread = true;
|
||||
a.ISmartReader.StopDataStreamProcessing(); // close opto port
|
||||
}
|
||||
|
||||
if (!optoThread.IsAlive)
|
||||
{
|
||||
a.ISmartReader.StartDataStreamProcessing(); // open opto port
|
||||
optoThread.Start();
|
||||
}
|
||||
|
||||
break;
|
||||
case Operations.StopReadOptoDataCmd:
|
||||
stopWorkerThread = true;
|
||||
a.ISmartReader.StopDataStreamProcessing(); // close opto port
|
||||
break;
|
||||
}
|
||||
|
||||
a.RfidOutputListBox.Items.Add(rfidListItem);
|
||||
a.RfidOutputListBox.Items.AddRange(logChecker.Messages.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
private void OptoWorker()
|
||||
{
|
||||
while (!this.stopWorkerThread)
|
||||
{
|
||||
Thread.Sleep(250);
|
||||
if (this.stopWorkerThread)
|
||||
break;
|
||||
|
||||
try
|
||||
{
|
||||
string buffer = ISmartReader.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)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using TBF.Rig.RegisterReaders.iPerlASICReader.communication.C4.diagnosticLed.parserer;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlASICReader.implementations
|
||||
{
|
||||
public enum OptoTelegramFlags : byte
|
||||
{
|
||||
OK = 0,
|
||||
OK_TestStart,
|
||||
OK_TestEnd,
|
||||
InvalidTelegram, /// Wrong telegram format of checksum error
|
||||
SyncError,
|
||||
}
|
||||
|
||||
public class OptoTelegramRaw
|
||||
{
|
||||
private DiagnosticLedState4Data data;
|
||||
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 Int16 FlowRaw;
|
||||
public UInt32 VolumeRaw;
|
||||
public Int64 VolumeRawExt;
|
||||
public UInt32 Timestamp;
|
||||
public Int64 TimestampExt;
|
||||
|
||||
|
||||
///
|
||||
/// Calculated values
|
||||
///
|
||||
public double Flow(double scalingFactor) { return 0.225 * scalingFactor * (double)FlowRaw; }
|
||||
public double Volume(double scalingFactor) { return 0.0000625 * scalingFactor * (double)VolumeRawExt; }
|
||||
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()
|
||||
{
|
||||
}
|
||||
|
||||
public void UpdateFromSmart(DiagnosticLedState4Data data,int counter, float refFlow, ref Int64 volumeRawExtLast, ref Int64 timestampExtLast)
|
||||
{
|
||||
|
||||
DateTime = DateTime.Now;
|
||||
Counter = counter;
|
||||
RefFlow = refFlow;
|
||||
|
||||
FlowRaw = data.RawFlow;
|
||||
VolumeRaw = data.RawVolume;
|
||||
Timestamp = data.AsicTimestamp;
|
||||
|
||||
|
||||
///
|
||||
/// 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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}",
|
||||
DateTime.Hour.ToString("D2"),
|
||||
DateTime.Minute.ToString("D2"),
|
||||
DateTime.Second.ToString("D2"),
|
||||
DateTime.Millisecond.ToString("D4"),
|
||||
Counter,
|
||||
FlowRaw.ToString("X4"),
|
||||
VolumeRaw.ToString("X6"),
|
||||
Timestamp.ToString("X8"),
|
||||
Flow(scalingFactor).ToString("F2", culture),
|
||||
Volume(scalingFactor).ToString("F4", 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -14,7 +14,7 @@ namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
|
||||
public override XmlSerializer GetSerializer() { return Serializer; }
|
||||
public IComponentCfgCtrl GetControl(IList<Component> cmpntEntities)
|
||||
{
|
||||
return new iPerlASICReader.IPerlUniCfgCtrl();
|
||||
return new IPerlReader.IPerlUniCfgCtrl();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
using System.Web.UI;
|
||||
using System.Windows.Forms;
|
||||
using TBF.Rig.RegisterReaders.iPerlReaderUNI.iCommon;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.IPerlS4
|
||||
{
|
||||
public class IperlHeadTestCtrl : UNIHeadTestCtrl
|
||||
{
|
||||
System.Windows.Forms.ListBox rfidOutputListBox;
|
||||
|
||||
public IperlHeadTestCtrl(ListBox rfidOutputListBox)
|
||||
{
|
||||
this.rfidOutputListBox = rfidOutputListBox;
|
||||
|
||||
var foo = 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" }
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
public 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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
|
||||
muxBoardNrTextBox.Text = config.MuxBoardNr.ToString();
|
||||
groupTextBox.Text = config.Group.ToString();
|
||||
comboBoxCommunicationInterface.SelectedItem = config.CommunicationInterface.ToString();
|
||||
tabPage2.Controls.Add(new iPerlASICReader.IperlASICUniHeadTestCtrl(config));
|
||||
tabPage2.Controls.Add(new IPerlReader.IperlUniHeadTestCtrl(config));
|
||||
}
|
||||
|
||||
public void Unlock()
|
||||
|
||||
@@ -11,7 +11,6 @@ using TBF.Rig.RegisterReaders.CommonRR.IPerl;
|
||||
using TBF.Rig.TestMethods.SmartTest;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
|
||||
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI
|
||||
{
|
||||
public class TestMethodCfg : ComponentCfgBase, ITestMethodCfg
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.iCommon
|
||||
{
|
||||
public interface UNIHeadTestCtrl
|
||||
{
|
||||
void CommandTestButtonClick(object sender, MouseEventArgs e);
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,6 @@ using log4net;
|
||||
using Sensus.iPerl.RfidCom.Helper;
|
||||
using System;
|
||||
using TBF.Rig.RegisterReaders.CommonRR;
|
||||
using TBF.Rig.RegisterReaders.CommonRR.IPerl;
|
||||
using TBF.Rig.TestMethods.iPerlCommunication;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.common;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication.implementations;
|
||||
@@ -27,18 +25,7 @@ namespace TBF.Rig.RegisterReaders.iPerlReaderUNI.test
|
||||
try
|
||||
{
|
||||
byte[] pcb = null;
|
||||
|
||||
ITestMethodCfg iTestMethodCfg = SmartCommunicationForm.TestMethodCfg;
|
||||
if (iTestMethodCfg == null)
|
||||
{
|
||||
//TODO find from components
|
||||
TestMethod testMethod = TbfComponents.FindFirstComponentImpl<TestMethod>() as TestMethod;
|
||||
if (testMethod != null)
|
||||
{
|
||||
iTestMethodCfg = testMethod.TestMethodCfg;
|
||||
}
|
||||
}
|
||||
int readRetVal = IPerlCorrections.ReadRequestPort(iTestMethodCfg, iHead, MessageID.Configuration, Sensus.iPerl.NfcHandler.MCI_Protocol.StructName.Configuration, 16, 5, out pcb);
|
||||
int readRetVal = IPerlCorrections.ReadRequestPort(SmartCommunicationForm.TestMethodCfg, 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();
|
||||
|
||||
@@ -18,7 +18,6 @@ using TBF.Rig.Network.RestAPI;
|
||||
using TBF.Rig.Network.RestAPI.facade;
|
||||
using TBF.Rig.Output.Printers.GroupPrinting.Single;
|
||||
using TBF.UiBridge;
|
||||
using SharedComponents;
|
||||
using System.Text;
|
||||
using TBF.Rig.RegisterReaders.CommonRR.IPerl;
|
||||
using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication;
|
||||
@@ -57,11 +56,7 @@ namespace TBF.Rig.Sequences
|
||||
try
|
||||
{
|
||||
/// 1nd argument
|
||||
ITestMethodCfg testMethodCfg = cfg as ITestMethodCfg;
|
||||
if (testMethodCfg == null)
|
||||
{
|
||||
|
||||
}
|
||||
ITestMethodCfg iPerlCfgIPerl = cfg as ITestMethodCfg;
|
||||
|
||||
/// 2rd argument: as is
|
||||
|
||||
@@ -72,7 +67,8 @@ namespace TBF.Rig.Sequences
|
||||
/*myRef.modelessDlg = new TestMethods.iPerlCommunication.iPerlCommunicationForm(iPerlCfg, tests, iPerlCommParams);
|
||||
myRef.modelessDlg.Show();*/
|
||||
|
||||
myRef.modelessDlg = new SmartCommunicationForm( testMethod , tests, iPerlCommParams);
|
||||
myRef.modelessDlg = new SmartCommunicationForm(
|
||||
testMethod , tests, iPerlCommParams);
|
||||
myRef.modelessDlg.Show();
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -1551,7 +1547,7 @@ namespace TBF.Rig.Sequences
|
||||
}
|
||||
|
||||
// ✍️ Uloženie do vlastného logu
|
||||
LiveLogCache.Instance.AddLog(logBuilder.ToString());
|
||||
//LiveLogCache.Instance.AddLog(logBuilder.ToString());
|
||||
|
||||
Bridge.OnError(this, "Chyba pri aktualizácii výsledkov v MySQL.");
|
||||
goto error;
|
||||
|
||||
@@ -9,7 +9,6 @@ using log4net;
|
||||
using log4net.Repository.Hierarchy;
|
||||
using TBF.Rig.Generic;
|
||||
using TBF.Rig.Sequences;
|
||||
using TBF.Rig.TestMethods.SmartTest;
|
||||
|
||||
namespace TBF.Rig
|
||||
{
|
||||
@@ -135,8 +134,7 @@ namespace TBF.Rig
|
||||
new RegisterReaders.FrequencyMeterFromUniCB.Factory(), ///
|
||||
//new RegisterReaders.iPerlReaderUNI.Factory(), /// 'UNI RegisterReader for Smart Meters'
|
||||
new RegisterReaders.PoseidonReader.Factory(),
|
||||
new RegisterReaders.IPerlReader.Factory(), /// the same functionality as TestMethods.iPerlCommunication.iPerlHead.Factory(),
|
||||
new RegisterReaders.iPerlASICReader.Factory(), /// ASIC IPerl, C4 communication
|
||||
new RegisterReaders.IPerlReader.Factory(), /// the same functionality as TestMethods.iPerlCommunication.iPerlHead.Factory(),
|
||||
new RegisterReaders.PulsesFromUniCB.Factory(), /// 'RegisterReader'
|
||||
new RegisterReaders.StandingStartStop.Factory(), /// 'RegisterReader for standing start/stop'
|
||||
new TestMethods.iPerlCommunication.iPerlHead.Factory(), /// 'RegisterReader for iPerl'
|
||||
@@ -192,7 +190,6 @@ namespace TBF.Rig
|
||||
new TestMethods.FlyingStartTankCollection.Compound.Factory(),
|
||||
new TestMethods.GrabImage.Factory(),
|
||||
new TestMethods.iPerlCommunication.TestMethodFactory(), /// iPerlCommunication
|
||||
new TestMethods.SmartTest.TestMethodFactory(), /// Smart Meter Tests
|
||||
new TestMethods.LeakTest.Factory(),
|
||||
new TestMethods.LiveStream.Factory(),
|
||||
new TestMethods.ManualEntry.Factory(),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user