diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 00000000..4799dec1
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "LaaProductionWeb/LaaPackages"]
+ path = LaaProductionWeb/LaaPackages
+ url = https://slm.sms-esaap.com/la_operations/laapackages.git
diff --git a/Common/.shared/SharedAssemblyInfo.cs b/Common/.shared/SharedAssemblyInfo.cs
index 2c53cf85..ae1a5838 100644
--- a/Common/.shared/SharedAssemblyInfo.cs
+++ b/Common/.shared/SharedAssemblyInfo.cs
@@ -15,4 +15,3 @@ using System.Reflection;
[assembly: AssemblyVersion("2.6.10.*")]
-[assembly: AssemblyFileVersion("2.6.10.0")]
\ No newline at end of file
diff --git a/Common/Common.sln b/Common/Common.sln
index d0f714ff..21dceb97 100644
--- a/Common/Common.sln
+++ b/Common/Common.sln
@@ -149,8 +149,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MagFlux", "MagFlux", "{C939
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Protocols", "Protocols", "{94579693-7AC6-4FF0-B540-1F3780E1BCFA}"
EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MjkControlledCodeRef", "MjkControlledCodeRef", "{B4F8545B-F379-42A5-BDE9-763FD7B79598}"
-EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagFluxToolBox", "Ui\MagFluxToolBox\MagFluxToolBox.csproj", "{A5E7CE52-3101-4E9B-B896-C2C0FADE4812}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MagFluxConfig", "Hardware\WaterMeter\MagFlux\MagFluxConfig\MagFluxConfig.csproj", "{70398B99-B134-4BBD-968B-7399B70C3CE2}"
@@ -169,8 +167,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LaaProduction", "LaaProduct
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommonConsole", "CommonConsole\CommonConsole.csproj", "{AFC428F5-0141-4A3F-BEF2-470A89D972F6}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "modbus_master_csharp", "modbus_master_csharp\modbus_master_csharp.csproj", "{F14940F8-3C86-4BB7-A915-B021E4B3052D}"
-EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OmniPlus", "OmniPlus", "{68323534-4337-4E3A-89BC-11D8BB55343A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniPlus", "OmniPlus\OmniPlus\OmniPlus.csproj", "{F8D84B9A-0FCF-4083-B067-8C39B7314152}"
@@ -203,8 +199,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InspectionUI.RemoteControl"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Hardware.Interfaces.Ports", "Hardware\Interfaces\Ports\Common.Hardware.Interfaces.Ports\Common.Hardware.Interfaces.Ports.csproj", "{9AE071C0-DB12-4E09-A3C7-43F6DCD518D6}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.UI.SIRTBroadcaster", "Ui\Common.UI.SIRTBroadcaster\Common.UI.SIRTBroadcaster.csproj", "{8D3B1C46-B23E-46CC-9B59-24E34DE60510}"
-EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.UI.VFM", "Ui\Common.UI.VFM\Common.UI.VFM.csproj", "{9C1C5522-E986-4FD6-8F2F-19821D704A88}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OmniPlus", "OmniPlus", "{68A1B84B-B38F-4BD1-94A8-DB18600457FF}"
@@ -227,10 +221,26 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Hardware.WaterMeter.
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Utils.Extensions", "Utils\Common.Utils.Extensions\Common.Utils.Extensions.csproj", "{05F0CCAF-9F2B-45F9-A7F8-12F29AD182F3}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.UI.WPFConnector", "Ui\Common.UI.WPFConnector\Common.UI.WPFConnector.csproj", "{37E4BF89-44AE-4133-BE0B-8355F791A79D}"
-EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.UI.WPF", "Ui\Common.UI.WPF\Common.UI.WPF.csproj", "{F7316525-FF8E-4651-BA67-3C9B948D1E91}"
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "MagFluxApi-MJK controlled Code", "MagFluxApi-MJK controlled Code", "{56768A27-D0E4-430E-8E75-AFC7319F189A}"
+ ProjectSection(SolutionItems) = preProject
+ Hardware\WaterMeter\MagFlux\MagFluxApi\magflux_api.dll = Hardware\WaterMeter\MagFlux\MagFluxApi\magflux_api.dll
+ Hardware\WaterMeter\MagFlux\MagFluxApi\shared_code.dll = Hardware\WaterMeter\MagFlux\MagFluxApi\shared_code.dll
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "api_doc", "api_doc", "{E6081C0A-8452-44B4-8EB4-E0CAE9119830}"
+ ProjectSection(SolutionItems) = preProject
+ Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\CalibrationPoint.cs = Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\CalibrationPoint.cs
+ Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\CalibrationPoints.cs = Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\CalibrationPoints.cs
+ Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\IMagFlux.cs = Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\IMagFlux.cs
+ Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\IMagFluxAPI.cs = Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\IMagFluxAPI.cs
+ Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\IMagFluxRequestProtocol.cs = Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\IMagFluxRequestProtocol.cs
+ Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\SensorInfo.cs = Hardware\WaterMeter\MagFlux\MagFluxApi\api_doc\SensorInfo.cs
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common.Hardware.Interfaces.Ports.SirtBroadcaster", "Hardware\Interfaces\Ports\Common.Hardware.Interfaces.Ports.SirtBroadcaster\Common.Hardware.Interfaces.Ports.SirtBroadcaster.csproj", "{F408DE9E-01E6-4CFF-AE79-B572B0674FA2}"
+EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
Utils\DateTimeServerShared\DateTimeServerShared.projitems*{4806d89a-fbfb-41bc-aaa7-2242444bf55a}*SharedItemsImports = 4
@@ -3913,70 +3923,6 @@ Global
{AFC428F5-0141-4A3F-BEF2-470A89D972F6}.XP32bit|x64.Build.0 = Release|Any CPU
{AFC428F5-0141-4A3F-BEF2-470A89D972F6}.XP32bit|x86.ActiveCfg = Release|Any CPU
{AFC428F5-0141-4A3F-BEF2-470A89D972F6}.XP32bit|x86.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}._MANUAL_CONTROL|Any CPU.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}._MANUAL_CONTROL|Any CPU.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}._MANUAL_CONTROL|Mixed Platforms.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}._MANUAL_CONTROL|Mixed Platforms.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}._MANUAL_CONTROL|x64.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}._MANUAL_CONTROL|x64.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}._MANUAL_CONTROL|x86.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}._MANUAL_CONTROL|x86.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.COM|Any CPU.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.COM|Any CPU.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.COM|Mixed Platforms.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.COM|Mixed Platforms.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.COM|x64.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.COM|x64.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.COM|x86.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.COM|x86.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|x64.ActiveCfg = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|x64.Build.0 = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|x86.ActiveCfg = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|x86.Build.0 = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.GenesisDisplayTool_V01|Any CPU.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.GenesisDisplayTool_V01|Any CPU.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.GenesisDisplayTool_V01|Mixed Platforms.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.GenesisDisplayTool_V01|Mixed Platforms.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.GenesisDisplayTool_V01|x64.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.GenesisDisplayTool_V01|x64.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.GenesisDisplayTool_V01|x86.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.GenesisDisplayTool_V01|x86.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.PerformTest|Any CPU.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.PerformTest|Any CPU.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.PerformTest|Mixed Platforms.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.PerformTest|Mixed Platforms.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.PerformTest|x64.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.PerformTest|x64.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.PerformTest|x86.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.PerformTest|x86.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|Any CPU.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|x64.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|x64.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|x86.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|x86.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.ReleaseTest|Any CPU.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.ReleaseTest|Any CPU.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.ReleaseTest|Mixed Platforms.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.ReleaseTest|Mixed Platforms.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.ReleaseTest|x64.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.ReleaseTest|x64.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.ReleaseTest|x86.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.ReleaseTest|x86.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.XP32bit|Any CPU.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.XP32bit|Any CPU.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.XP32bit|Mixed Platforms.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.XP32bit|Mixed Platforms.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.XP32bit|x64.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.XP32bit|x64.Build.0 = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.XP32bit|x86.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.XP32bit|x86.Build.0 = Release|Any CPU
{F8D84B9A-0FCF-4083-B067-8C39B7314152}._MANUAL_CONTROL|Any CPU.ActiveCfg = Release|Any CPU
{F8D84B9A-0FCF-4083-B067-8C39B7314152}._MANUAL_CONTROL|Any CPU.Build.0 = Release|Any CPU
{F8D84B9A-0FCF-4083-B067-8C39B7314152}._MANUAL_CONTROL|Mixed Platforms.ActiveCfg = Release|Any CPU
@@ -4809,70 +4755,6 @@ Global
{9AE071C0-DB12-4E09-A3C7-43F6DCD518D6}.XP32bit|x64.Build.0 = Release|Any CPU
{9AE071C0-DB12-4E09-A3C7-43F6DCD518D6}.XP32bit|x86.ActiveCfg = Release|Any CPU
{9AE071C0-DB12-4E09-A3C7-43F6DCD518D6}.XP32bit|x86.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}._MANUAL_CONTROL|Any CPU.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}._MANUAL_CONTROL|Any CPU.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}._MANUAL_CONTROL|Mixed Platforms.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}._MANUAL_CONTROL|Mixed Platforms.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}._MANUAL_CONTROL|x64.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}._MANUAL_CONTROL|x64.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}._MANUAL_CONTROL|x86.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}._MANUAL_CONTROL|x86.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.COM|Any CPU.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.COM|Any CPU.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.COM|Mixed Platforms.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.COM|Mixed Platforms.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.COM|x64.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.COM|x64.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.COM|x86.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.COM|x86.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Debug|x64.ActiveCfg = Debug|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Debug|x64.Build.0 = Debug|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Debug|x86.ActiveCfg = Debug|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Debug|x86.Build.0 = Debug|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.GenesisDisplayTool_V01|Any CPU.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.GenesisDisplayTool_V01|Any CPU.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.GenesisDisplayTool_V01|Mixed Platforms.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.GenesisDisplayTool_V01|Mixed Platforms.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.GenesisDisplayTool_V01|x64.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.GenesisDisplayTool_V01|x64.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.GenesisDisplayTool_V01|x86.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.GenesisDisplayTool_V01|x86.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.PerformTest|Any CPU.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.PerformTest|Any CPU.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.PerformTest|Mixed Platforms.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.PerformTest|Mixed Platforms.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.PerformTest|x64.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.PerformTest|x64.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.PerformTest|x86.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.PerformTest|x86.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Release|Any CPU.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Release|x64.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Release|x64.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Release|x86.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.Release|x86.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.ReleaseTest|Any CPU.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.ReleaseTest|Any CPU.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.ReleaseTest|Mixed Platforms.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.ReleaseTest|Mixed Platforms.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.ReleaseTest|x64.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.ReleaseTest|x64.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.ReleaseTest|x86.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.ReleaseTest|x86.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.XP32bit|Any CPU.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.XP32bit|Any CPU.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.XP32bit|Mixed Platforms.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.XP32bit|Mixed Platforms.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.XP32bit|x64.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.XP32bit|x64.Build.0 = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.XP32bit|x86.ActiveCfg = Release|Any CPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}.XP32bit|x86.Build.0 = Release|Any CPU
{9C1C5522-E986-4FD6-8F2F-19821D704A88}._MANUAL_CONTROL|Any CPU.ActiveCfg = Release|Any CPU
{9C1C5522-E986-4FD6-8F2F-19821D704A88}._MANUAL_CONTROL|Any CPU.Build.0 = Release|Any CPU
{9C1C5522-E986-4FD6-8F2F-19821D704A88}._MANUAL_CONTROL|Mixed Platforms.ActiveCfg = Release|Any CPU
@@ -5513,70 +5395,6 @@ Global
{05F0CCAF-9F2B-45F9-A7F8-12F29AD182F3}.XP32bit|x64.Build.0 = Release|Any CPU
{05F0CCAF-9F2B-45F9-A7F8-12F29AD182F3}.XP32bit|x86.ActiveCfg = Release|Any CPU
{05F0CCAF-9F2B-45F9-A7F8-12F29AD182F3}.XP32bit|x86.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}._MANUAL_CONTROL|Any CPU.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}._MANUAL_CONTROL|Any CPU.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}._MANUAL_CONTROL|Mixed Platforms.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}._MANUAL_CONTROL|Mixed Platforms.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}._MANUAL_CONTROL|x64.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}._MANUAL_CONTROL|x64.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}._MANUAL_CONTROL|x86.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}._MANUAL_CONTROL|x86.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.COM|Any CPU.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.COM|Any CPU.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.COM|Mixed Platforms.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.COM|Mixed Platforms.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.COM|x64.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.COM|x64.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.COM|x86.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.COM|x86.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Debug|x64.ActiveCfg = Debug|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Debug|x64.Build.0 = Debug|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Debug|x86.ActiveCfg = Debug|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Debug|x86.Build.0 = Debug|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.GenesisDisplayTool_V01|Any CPU.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.GenesisDisplayTool_V01|Any CPU.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.GenesisDisplayTool_V01|Mixed Platforms.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.GenesisDisplayTool_V01|Mixed Platforms.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.GenesisDisplayTool_V01|x64.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.GenesisDisplayTool_V01|x64.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.GenesisDisplayTool_V01|x86.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.GenesisDisplayTool_V01|x86.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.PerformTest|Any CPU.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.PerformTest|Any CPU.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.PerformTest|Mixed Platforms.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.PerformTest|Mixed Platforms.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.PerformTest|x64.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.PerformTest|x64.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.PerformTest|x86.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.PerformTest|x86.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Release|Any CPU.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Release|Mixed Platforms.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Release|x64.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Release|x64.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Release|x86.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.Release|x86.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.ReleaseTest|Any CPU.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.ReleaseTest|Any CPU.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.ReleaseTest|Mixed Platforms.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.ReleaseTest|Mixed Platforms.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.ReleaseTest|x64.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.ReleaseTest|x64.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.ReleaseTest|x86.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.ReleaseTest|x86.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.XP32bit|Any CPU.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.XP32bit|Any CPU.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.XP32bit|Mixed Platforms.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.XP32bit|Mixed Platforms.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.XP32bit|x64.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.XP32bit|x64.Build.0 = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.XP32bit|x86.ActiveCfg = Release|Any CPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}.XP32bit|x86.Build.0 = Release|Any CPU
{F7316525-FF8E-4651-BA67-3C9B948D1E91}._MANUAL_CONTROL|Any CPU.ActiveCfg = Release|Any CPU
{F7316525-FF8E-4651-BA67-3C9B948D1E91}._MANUAL_CONTROL|Any CPU.Build.0 = Release|Any CPU
{F7316525-FF8E-4651-BA67-3C9B948D1E91}._MANUAL_CONTROL|Mixed Platforms.ActiveCfg = Release|Any CPU
@@ -5641,6 +5459,70 @@ Global
{F7316525-FF8E-4651-BA67-3C9B948D1E91}.XP32bit|x64.Build.0 = Release|Any CPU
{F7316525-FF8E-4651-BA67-3C9B948D1E91}.XP32bit|x86.ActiveCfg = Release|Any CPU
{F7316525-FF8E-4651-BA67-3C9B948D1E91}.XP32bit|x86.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}._MANUAL_CONTROL|Any CPU.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}._MANUAL_CONTROL|Any CPU.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}._MANUAL_CONTROL|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}._MANUAL_CONTROL|Mixed Platforms.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}._MANUAL_CONTROL|x64.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}._MANUAL_CONTROL|x64.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}._MANUAL_CONTROL|x86.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}._MANUAL_CONTROL|x86.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.COM|Any CPU.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.COM|Any CPU.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.COM|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.COM|Mixed Platforms.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.COM|x64.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.COM|x64.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.COM|x86.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.COM|x86.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Debug|x64.Build.0 = Debug|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Debug|x86.Build.0 = Debug|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.GenesisDisplayTool_V01|Any CPU.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.GenesisDisplayTool_V01|Any CPU.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.GenesisDisplayTool_V01|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.GenesisDisplayTool_V01|Mixed Platforms.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.GenesisDisplayTool_V01|x64.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.GenesisDisplayTool_V01|x64.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.GenesisDisplayTool_V01|x86.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.GenesisDisplayTool_V01|x86.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.PerformTest|Any CPU.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.PerformTest|Any CPU.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.PerformTest|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.PerformTest|Mixed Platforms.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.PerformTest|x64.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.PerformTest|x64.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.PerformTest|x86.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.PerformTest|x86.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Release|x64.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Release|x64.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Release|x86.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.Release|x86.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.ReleaseTest|Any CPU.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.ReleaseTest|Any CPU.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.ReleaseTest|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.ReleaseTest|Mixed Platforms.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.ReleaseTest|x64.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.ReleaseTest|x64.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.ReleaseTest|x86.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.ReleaseTest|x86.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.XP32bit|Any CPU.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.XP32bit|Any CPU.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.XP32bit|Mixed Platforms.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.XP32bit|Mixed Platforms.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.XP32bit|x64.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.XP32bit|x64.Build.0 = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.XP32bit|x86.ActiveCfg = Release|Any CPU
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}.XP32bit|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -5707,7 +5589,6 @@ Global
{35726BCF-975C-4B49-BEFA-C00D90394F1D} = {696A94BE-7237-4AE2-9E36-6059DE519971}
{C9393A97-C0BB-4D59-A879-B572BE04CE15} = {5563DD3B-2287-4BED-97BF-F0389FF505AF}
{94579693-7AC6-4FF0-B540-1F3780E1BCFA} = {C9393A97-C0BB-4D59-A879-B572BE04CE15}
- {B4F8545B-F379-42A5-BDE9-763FD7B79598} = {C9393A97-C0BB-4D59-A879-B572BE04CE15}
{A5E7CE52-3101-4E9B-B896-C2C0FADE4812} = {03D4F23E-7E4A-4091-BC96-036C996D351A}
{70398B99-B134-4BBD-968B-7399B70C3CE2} = {C9393A97-C0BB-4D59-A879-B572BE04CE15}
{B5DA260C-71CC-45CA-B79E-D1B376AF718C} = {C9393A97-C0BB-4D59-A879-B572BE04CE15}
@@ -5717,7 +5598,6 @@ Global
{8BDD2789-96D4-43EA-AAD7-0F49D0347998} = {EC10DAFE-88CF-42D5-99E7-D247938B6430}
{FD30EB7A-7809-4E62-9374-791D31877D6D} = {696A94BE-7237-4AE2-9E36-6059DE519971}
{AFC428F5-0141-4A3F-BEF2-470A89D972F6} = {C17363DF-A043-4F25-8EBA-2B3B078227DC}
- {F14940F8-3C86-4BB7-A915-B021E4B3052D} = {B4F8545B-F379-42A5-BDE9-763FD7B79598}
{F8D84B9A-0FCF-4083-B067-8C39B7314152} = {68323534-4337-4E3A-89BC-11D8BB55343A}
{01A28A70-D5E6-4898-8C22-E64400A3B80F} = {68323534-4337-4E3A-89BC-11D8BB55343A}
{4806D89A-FBFB-41BC-AAA7-2242444BF55A} = {FA3B769A-E83E-40F0-923A-DFA124AF0C2C}
@@ -5732,7 +5612,6 @@ Global
{C6BFAC88-5647-4131-90B1-4D6265E08348} = {68323534-4337-4E3A-89BC-11D8BB55343A}
{41E949AD-FBF6-47A3-AC1D-7E17AB7F1252} = {68323534-4337-4E3A-89BC-11D8BB55343A}
{9AE071C0-DB12-4E09-A3C7-43F6DCD518D6} = {B9444AB7-1EB1-484A-8DE6-4EEE03498CD7}
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510} = {03D4F23E-7E4A-4091-BC96-036C996D351A}
{9C1C5522-E986-4FD6-8F2F-19821D704A88} = {03D4F23E-7E4A-4091-BC96-036C996D351A}
{68A1B84B-B38F-4BD1-94A8-DB18600457FF} = {5563DD3B-2287-4BED-97BF-F0389FF505AF}
{9D89FA2A-1217-4CE9-B217-E7602B974EA9} = {68A1B84B-B38F-4BD1-94A8-DB18600457FF}
@@ -5744,8 +5623,10 @@ Global
{28FD69D1-B2DA-485D-9571-711BF3917350} = {696A94BE-7237-4AE2-9E36-6059DE519971}
{4E8BB839-D40A-488C-88CE-F21811F1F476} = {43B54F41-6F09-4BCB-9F82-77621275831B}
{05F0CCAF-9F2B-45F9-A7F8-12F29AD182F3} = {7A0EE7B8-6B7E-41E9-B679-319C8CA48CF1}
- {37E4BF89-44AE-4133-BE0B-8355F791A79D} = {03D4F23E-7E4A-4091-BC96-036C996D351A}
{F7316525-FF8E-4651-BA67-3C9B948D1E91} = {03D4F23E-7E4A-4091-BC96-036C996D351A}
+ {56768A27-D0E4-430E-8E75-AFC7319F189A} = {C9393A97-C0BB-4D59-A879-B572BE04CE15}
+ {E6081C0A-8452-44B4-8EB4-E0CAE9119830} = {56768A27-D0E4-430E-8E75-AFC7319F189A}
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2} = {B9444AB7-1EB1-484A-8DE6-4EEE03498CD7}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4BCB7B69-696C-436A-86F7-C91EA5588164}
diff --git a/Common/CommonConsole/CommonConsole.csproj b/Common/CommonConsole/CommonConsole.csproj
index bf303d6d..77be462a 100644
--- a/Common/CommonConsole/CommonConsole.csproj
+++ b/Common/CommonConsole/CommonConsole.csproj
@@ -55,6 +55,14 @@
+
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}
+ Common.Hardware.Interfaces.Ports.SirtBroadcaster
+
+
+ {B23BFAF9-08AE-4311-8C08-FB2BB49EA2AD}
+ Common.Hardware.Interfaces.Ports.Sirt
+
{9ae071c0-db12-4e09-a3c7-43f6dcd518d6}
Common.Hardware.Interfaces.Ports
@@ -87,21 +95,10 @@
{F8D84B9A-0FCF-4083-B067-8C39B7314152}
OmniPlus
-
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}
- Common.UI.SIRTBroadcaster
-
-
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}
- Common.UI.WPFConnector
-
{05f0ccaf-9f2b-45f9-a7f8-12f29ad182f3}
Common.Utils.Extensions
-
-
-
\ No newline at end of file
diff --git a/Common/CommonConsole/Program.cs b/Common/CommonConsole/Program.cs
index 4bcf5fff..4d24daf1 100644
--- a/Common/CommonConsole/Program.cs
+++ b/Common/CommonConsole/Program.cs
@@ -1,40 +1,518 @@
namespace CommonConsole
{
- using Common.Hardware.WaterMeter.eRegister;
- using Common.UI.WPFConnector;
-
using System;
public class Program
{
public static void Main()
{
- //var connector = EregisterConnector.CreateNew("COM6", 1000);
+ int value = 333333333;
+ var bytes1 = BitConverter.GetBytes(value);
- //connector.Add(1, 0319020415, 0319020415);//433
- //connector.AddHexCommand(1, "00-00");
- //connector.Add(2, 0319020441, 0319020441);//433
- //connector.AddHexCommand(2, "00-00");
- //connector.Add(3, 4291317405, 4291317405);//433
- //connector.AddHexCommand(3, "00-00");
+ Array.Reverse(bytes1);
- //connector.RunCommands();
+ Console.WriteLine(BitConverter.ToString(bytes1).Replace('-', ' '));
+ var hex = string.Empty;
- var connector = EregisterConnector.CreateNew("COM6", 1000);
+ while (value > 0)
+ {
+ hex = $"{value % 256:X2}{hex}";
+ value /= 256;
+ }
- connector.Add(1, 0319020415, 0319020415);//433
- connector.AddHexCommand(1, "00-00");
- connector.Add(2, 0319020441, 0319020441);//433
- connector.AddHexCommand(2, "00-00");
- connector.Add(3, 4291317405, 4291317405);//433
- connector.AddHexCommand(3, "00-00");
-
- connector.InitInspection();
+ Console.WriteLine(hex);
}
+
+
+ ///
+ /// 0B
+ /// D0
+ /// FF C6 25 F3
+ /// 00
+ /// 0A
+ /// 11 08
+ /// 11 08
+ ///
+ /// 04 01 C7 47 9F 77 17 00 6A 00 08 08 00 00 00 00 05 68 46 89 02 01 01 16 00 0A 00 00 02 71 02 71 00 00 00 00 00 00 00 08
+ ///
+ //var bytes = new[] { 0x08, 0x11 };
+ //var bits = new Byte[16];
+ //var x = 0;
+
+ //foreach (var @byte in bytes)
+ //{
+ // for (var i = 0; i< 8; i++, x++)
+ // {
+ // bits[x] = (Byte) ((@byte >> i) & 1);
+ // }
+ //}
+
+ //Array.Reverse(bits);
+
+ //var type = bits[15] == 0 ? 'B' : 'R';
+
+ //var majorBits = new Byte[8];
+ //majorBits[0] = bits[14];
+ //majorBits[1] = bits[13];
+ //majorBits[2] = bits[12];
+
+ //var major = 0;
+
+ //for (var i = 0; i< 8; i++)
+ //{
+ // major |= majorBits[i] << i;
+ //}
+
+ //var minorBits = new Byte[8];
+ //majorBits[0] = bits[11];
+ //majorBits[1] = bits[10];
+ //majorBits[2] = bits[9];
+ //majorBits[2] = bits[8];
+
+ //var minor = 0;
+
+ //for (var i = 0; i< 8; i++)
+ //{
+ // minor |= minorBits[i] << i;
+ //}
+
+ //Console.WriteLine($"{type}{major}.{minor}.{0x08}");
+
+
+ //var programmingBatch = new JusteRegisterProgrammingBatch();
+
+ //if (programmingBatch.StartOnCOMPort("COM6"))
+ //{
+ // var task = new JusteRegisterProgrammingTask
+ // {
+ // Cmd = JustSirtMessage.W_PAM,
+ // P1 = new P811
+ // {
+ // DelPamSemi = true
+ // },
+ // Address = 319020415,
+ // Data = new Byte[]
+ // {
+ // // Metrology parameters
+ // 0x92, 0x10, 0x71, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x71, 0x02, 0x00, 0x00,
+
+ // // Provide Pin Auth Level III
+ // 0x43, 0x03, 0x63, 0x93, 0x73, 0x22,
+ // }
+ // };
+ // programmingBatch.Run(task);
+
+ // Console.ReadKey();
+
+ // programmingBatch.Stop();
+ //}
+ //else
+ //{
+ // Console.WriteLine("Not connected!");
+ //}
+
+
+ // 01020304050607081112131415161718
+ // E6C88800DEB868C0D6A84880CE982840
+ //var encryptionKey = new Byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 };
+ //var task = new JusteRegisterProgrammingTask
+ //{
+ // Cmd = JustSirtMessage.W_PAM,
+ // P1 = new P811
+ // {
+ // DelPamSemi = true,
+ // WakeUpCmd = true
+ // },
+ // Address = 4291305226,
+ // // Address = 319020415,
+ // Data = new Byte[]
+ // {
+ // // Change Key
+ // // 0x6C, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
+
+ // // LED on
+ // // 0x1F, 0x01, 0x08,
+
+ // // Reboot
+ // 0x0E, 0x00,
+
+ // // Provide Pin Auth Level I
+ // // 0x43, 0x01, 0x14, 0x30, 0x68, 0xD0,
+
+ // // Provide Pin Auth Level II
+ // // 0x43, 0x02, 0x14, 0x0E, 0x80, 0x40,
+
+ // // Provide Pin Auth Level III
+ // 0x43, 0x03, 0x63, 0x93, 0x73, 0x22,
+
+ // // Reset credits
+ // // 0x1F, 0x01, 0x03,
+ // },
+ // EncryptionKey = encryptionKey
+ //};
+ //programmingBatch.Run(task);
+ //task.Wait();
+
+ // 55 81 14 00 FF C8 1F 0A 0B 07 FA E3 AA EA 8A 7B 7B D9 A7 D7 D5 B8 16
+ // 55 81 14 00 FF C8 1F 0A 0B 07 FA E3 AA EA 8A 7B 7B D9 A7 D7 D5 B8 16
+
+ //var task = new JusteRegisterTask
+ //{
+ // Cmd = JustSirtMessage.W_PAM,
+ // P1 = new P811
+ // {
+ // DelPamSemi = true
+ // },
+ // Address = 319020415,
+ // Data = new Byte[]
+ // {
+ // // WUP stay awake
+ // 0x00, 0x00,
+
+ // // LAT
+ // 0x02, 0x00,
+
+ // // MBUS 7
+ // 0x05, 0x07,
+
+ // // TX
+ // 0x10, 0x00, 0x03,
+
+ // // Provide Pin Auth Level I
+ // // 0x43, 0x01, 0x14, 0x30, 0x68, 0xD0,
+
+ // // Provide Pin Auth Level II
+ // 0x43, 0x02, 0x14, 0x0E, 0x80, 0x40,
+
+ // // Provide Pin Auth Level III
+ // // 0x43, 0x03, 0x63, 0x93, 0x73, 0x22,
+
+ // // Reset credits
+ // // 0x1F, 0x01, 0x03,
+ // }
+ //};
+ //programmingBatch.Run(task);
+ //task.Wait();
+
+ //task = new JusteRegisterTask
+ //{
+ // Cmd = JustSirtMessage.W_PAM,
+ // P1 = new P811
+ // {
+ // DelPamSemi = true
+ // },
+ // Address = 319020415,
+ // Data = new Byte[]
+ // {
+ // // Parametersatz
+
+
+ // // Provide Pin Auth Level I
+ // // 0x43, 0x01, 0x14, 0x30, 0x68, 0xD0,
+
+ // // Provide Pin Auth Level II
+ // 0x43, 0x02, 0x14, 0x0E, 0x80, 0x40,
+
+ // // Provide Pin Auth Level III
+ // // 0x43, 0x03, 0x63, 0x93, 0x73, 0x22,
+
+ // // Reset credits
+ // // 0x1F, 0x01, 0x03,
+ // }
+ //};
+ //programmingBatch.Run(task);
+ //task.Wait();
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ //public static byte[] Decrypt(Byte[] key, params Byte[] message)
+ //{
+ // var decryptLength = message.Length;
+ // var decryptedBytes = new Byte[decryptLength];
+
+ // for (int i = 0; i < decryptLength; i++)
+ // {
+ // decryptedBytes[i] = message[i];
+ // }
+
+ // var start = 14;
+ // var end = start + decryptedBytes[7] 6;
+ // var token = decryptedBytes[9];
+
+ // for (var i = start; i < end; i++)
+ // {
+ // token += (Byte)(decryptedBytes[i (token & 0x3) 1] >> ((token >> 6) & 0x1));
+
+ // decryptedBytes[i] ^= key[(token >> 2) & 0x0F];
+
+ // if (token > 127)
+ // {
+ // decryptedBytes[i] = (Byte)~decryptedBytes[i];
+ // }
+ // }
+
+ // return decryptedBytes;
+ //}
+
+ //public static byte[] Encrypt(Byte[] key, UInt32 address, params Byte[] telegramBytes)
+ //{
+ // Console.WriteLine(address);
+ // Console.WriteLine(BitConverter.ToString(key));
+ // Console.WriteLine(BitConverter.ToString(telegramBytes));
+
+ // var telegramLength = telegramBytes.Length;
+ // var telegramIndex = 0;
+
+ // var encryptedBytes = new Byte[telegramLength + 6];
+ // var encryptLength = encryptedBytes.Length;
+ // var index = 0;
+
+ // encryptedBytes[index++] = (Byte)(address >> 24);
+ // encryptedBytes[index++] = (Byte)(address >> 16);
+ // encryptedBytes[index++] = (Byte)(address >> 8);
+ // encryptedBytes[index++] = (Byte)(address >> 0);
+
+ // foreach (var _byte in telegramBytes)
+ // {
+ // encryptedBytes[index++] = telegramBytes[telegramIndex++];
+ // }
+
+ // var telegramCRC = CalculateCrc(encryptedBytes, 1, (UInt16)(encryptLength 3));
+
+ // encryptedBytes[index++] = (Byte)(telegramCRC >> 8);
+ // encryptedBytes[index++] = (Byte)(telegramCRC >> 0);
+
+ // Console.WriteLine(BitConverter.ToString(encryptedBytes));
+
+ // var token = (Byte)0xFF;
+ // var reference = address;
+
+ // for (var i = 0; i < encryptLength; i++)
+ // {
+ // // Update pKeyDefinition for this byte
+ // token += (Byte)(((reference >> ((token & 0x3) << 3)) & 0xFF) >> ((token >> 6) & 1));
+
+ // // Update the unencrypted reference before the byte gets encrypted
+ // reference = (reference << 8);
+ // reference += encryptedBytes[i];
+
+ // // Encrypt the data by applying the resepective key
+ // encryptedBytes[i] ^= key[((token >> 2) & 0x0F)];
+
+ // // Check if data has to be inverted
+ // if (token > 127)
+ // {
+ // encryptedBytes[i] = (Byte)~encryptedBytes[i];
+ // }
+ // }
+
+ // Console.WriteLine(BitConverter.ToString(encryptedBytes));
+ // Console.WriteLine();
+
+ // return encryptedBytes;
+ //}
+
+ //public static ushort CalculateCrc(byte[] data, ushort start, ushort length)
+ //{
+ // byte zeichen, test;
+ // ushort crc_result;
+ // ushort ui_index;
+ // byte h;
+
+ // crc_result = 0xFFFF;
+ // ui_index = start;
+
+ // if (data.Length >= length + start)
+ // {
+ // while (ui_index < length + start)
+ // {
+ // zeichen = data[ui_index];
+ // ui_index++;
+
+ // for (h = 0; h < 8; h++)
+ // {
+ // test = 0;
+
+ // if ((crc_result & 0x8000) != 0)
+ // {
+ // test = 0x80;
+ // }
+
+ // crc_result <<= 1;
+
+ // if (((zeichen & 0x80) ^ test) != 0)
+ // {
+ // crc_result ^= 0x1021;
+ // }
+ // zeichen <<= 1;
+ // }
+ // }
+ // }
+
+ // return crc_result;
+ //}
}
}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+//var connector = EregisterConnector.CreateNew("COM6", 1000);
+
+//connector.Add(1, 0319020415, 0319020415);//433
+//connector.AddHexCommand(1, "00 00");
+
+//connector.Add(2, 0319020441, "4291317405", "4291317405", null, false); // 433
+//connector.InitInspection();
+
+//connector.Add(3, 4291317405, 4291317405);//433
+//connector.AddHexCommand(3, "00 00");
+
+// connector.RunCommands();
+
+
+//var connector = EregisterConnector.CreateNew("COM6", 1000);
+
+//connector.Add(1, 0319020415, 0319020415);//433
+//connector.AddHexCommand(1, "00 00");
+//connector.Add(2, 0319020441, 0319020441);//433
+//connector.AddHexCommand(2, "00 00");
+//connector.Add(3, 4291317405, 4291317405);//433
+//connector.AddHexCommand(3, "00 00");
+
+//connector.InitInspection();
+
+//var connection = new OmniConnection();
+//connection.UseUniPro("COM16");
+
+//var system = connection.ViewSystemParameters();
+
+//connection.Disconnect();
// 0x08, 0x0E, 0x13, 0x03, 0xEE, 0xAC, 0x00, 0x00, 0x01, 0xF4, 0x00, 0x00, 0x92, 0x0A, 0x00, 0x0F, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x13, 0x13, 0x03, 0xEE, 0xAC, 0x07, 0x0E, 0x10, 0xA0, 0x57, 0x4E, 0xDA, 0xC0, 0x00, 0x00, 0x7F, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x03, 0x05, 0xA0, 0x0C, 0x03, 0x01, 0x2E, 0x46, 0x7C, 0x76, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x25, 0x14, 0x3B
// 0x0B, 0x10, 0x13, 0x03, 0xEE, 0xAC, 0x00, 0x0A, 0x11, 0x0B, 0x11, 0x08, 0x04, 0x02, 0xC8, 0xF4, 0xFB, 0xA7, 0x18, 0x00, 0x65, 0x00, 0x35, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0xEE, 0x34, 0x02, 0x01, 0x01, 0x16, 0x00, 0x25, 0x02, 0x71, 0x00, 0x00, 0x82, 0x71, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x08, 0xC3
diff --git a/Common/CommonCore.Configuration/ServiceUrls.cs b/Common/CommonCore.Configuration/ServiceUrls.cs
index df18db27..a446a236 100644
--- a/Common/CommonCore.Configuration/ServiceUrls.cs
+++ b/Common/CommonCore.Configuration/ServiceUrls.cs
@@ -9,6 +9,11 @@ namespace Xylem.Common.CommonCore.Configuration
///
public static class ServiceUrls
{
+
+ // return code: 404 not found, 400 Error with text, 200 okay
+ private const String DefaultEolDataForSentinelServiceUrl =
+ "http://sla12iis01.emea.sensus.net/LaaProductionWeb/api/cordonel/eolprogress/";
+
private const String DefaultGetPcbIdsFromSafeServiceUrl =
"http://sla12iis01.emea.sensus.net/MeterProcessState/GetPcbIdsFromSafe?ContainerDbId=";
@@ -33,11 +38,10 @@ namespace Xylem.Common.CommonCore.Configuration
private const String DefaultSetCordonelAppVersionServiceUrl =
"http://sla12iis01.emea.sensus.net/MeterProcessState/api/ProccesState/SetCordonelProgress?PcbId=";
- private const String DefaultGetProductionSkipAndLifeTimeInfoUrl =
- "http://sla12iis01.emea.sensus.net/MeterProcessState/api/ProccesState/GetProductionSkipAndLifeTimeInfo?PcbId=";
+ private const String DefaultGetCordonelRequirementInfoUrl =
+ "http://sla12iis01.emea.sensus.net/LaaProductionWeb/api/cordonel/requirements/pcbid/";
private const String DefaultGetCordonelAppVersionServiceUrl =
- //"http://localhost:56011/api/ProccesState/GetCordonelAppVersion?PcbId=";
"http://sla12iis01.emea.sensus.net/MeterProcessState/api/ProccesState/GetCordonelAppVersion?PcbId=";
private const String DefaultListAllCordonelCustomersWithFilterServiceUrl =
@@ -205,13 +209,14 @@ namespace Xylem.Common.CommonCore.Configuration
private const String PressureSensorTestURL_GetTestResults
= "http://sla12iis01.emea.sensus.net/MeterProcessState/api/CordonelPressureSensorTest/GetTestResults/{0}";
- public const string LaaProductionAPI
+ public const String LaaProductionAPI
#if DEBUG == false // when false uses always the production url.
= "http://localhost:52822";
#else
= "http://sla12iis01.emea.sensus.net";
#endif
+
///
/// GET: test specification for water meter with pressure sensor.
///
@@ -325,6 +330,16 @@ namespace Xylem.Common.CommonCore.Configuration
return ConfigurationManager.AppSettings["DownloadDbDataAtEolServiceUrl"] ??
DefaultDbDataAtEolServiceUrl;
}
+ ///
+ /// Get EOL data for sentinel
+ ///
+ ///
+ public static String EolDataForSentinelServiceUrl()
+ {
+ return ConfigurationManager.AppSettings["EolDataForSentinelServiceUrl"] ??
+ DefaultEolDataForSentinelServiceUrl;
+ }
+
///
/// Get all Cordonel safes description files.
///
@@ -383,10 +398,10 @@ namespace Xylem.Common.CommonCore.Configuration
/// - Required life time for shipping line.
///
///
- public static String GetProductionSkipAndLifeTimeInfoServiceUrl()
+ public static String GetCordonelRequirementInfoServiceUrl()
{
- return ConfigurationManager.AppSettings["GetProductionSkipAndLifeTimeInfoUrl"] ??
- DefaultGetProductionSkipAndLifeTimeInfoUrl;
+ return ConfigurationManager.AppSettings["GetCordonelRequirementInfoServiceUrl"] ??
+ DefaultGetCordonelRequirementInfoUrl;
}
///
@@ -462,7 +477,7 @@ namespace Xylem.Common.CommonCore.Configuration
///
- /// FW-Update report doanload as string
+ /// FW-Update report download as string
///
///
public static String DownloadFwUpdateReportServiceUrl()
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Common.Hardware.Interfaces.Ports.SIRT.csproj b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Common.Hardware.Interfaces.Ports.SIRT.csproj
index 260e2b49..f9f5ff7f 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Common.Hardware.Interfaces.Ports.SIRT.csproj
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Common.Hardware.Interfaces.Ports.SIRT.csproj
@@ -7,8 +7,8 @@
{B23BFAF9-08AE-4311-8C08-FB2BB49EA2AD}
Library
Properties
- Common.Hardware.Interfaces.Ports.SIRT
- Common.Hardware.Interfaces.Ports.SIRT
+ Common.Hardware.Interfaces.Ports.Sirt
+ Common.Hardware.Interfaces.Ports.Sirt
v4.0
512
true
@@ -41,6 +41,8 @@
+
+
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/JustSirtMessage.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/JustSirtMessage.cs
new file mode 100644
index 00000000..60dc011b
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/JustSirtMessage.cs
@@ -0,0 +1,166 @@
+namespace Common.Hardware.Interfaces.Ports.Sirt
+{
+ using System;
+
+ public class JustSirtMessage
+ {
+ public const Byte MIN_LEN = 12;
+ public const Byte PC2SIRT = 0x55;
+ public const Byte SIRT2PC = 0xFF;
+ public const Byte W_PAM = 0x81;
+ public const Byte R_PAM = 0x82;
+ public const Byte W_REG = 0x84;
+ public const Byte R_REG = 0x87;
+ public const Byte FROMAIR = 0x11;
+ public const Byte ACKNANSW = 0x12;
+ public const Byte STOP = 0x16;
+ public const Byte BUP = 0x00;
+ public const Byte LAT = 0x01;
+ public const Byte DEBUG = 0x0B;
+ public const Byte SEMI = 0x08;
+
+ private readonly DateTime timestamp;
+
+ private Byte[] bytes;
+
+ public JustSirtMessage(DateTime? timestamp = null)
+ {
+ this.timestamp = timestamp ?? DateTime.Now;
+ this.bytes = new Byte[MIN_LEN];
+ this.bytes[0] = PC2SIRT;
+ }
+
+ public JustSirtMessage(Byte[] bytes, DateTime? timestamp = null)
+ {
+ this.timestamp = timestamp ?? DateTime.Now;
+ this.bytes = bytes;
+ }
+
+ public Byte Cmd
+ {
+ get => this.bytes[1];
+ set => this.bytes[1] = value;
+ }
+
+ public Byte P1
+ {
+ get => this.bytes[2];
+ set => this.bytes[2] = value;
+ }
+
+ public Byte P2
+ {
+ get => this.bytes[3];
+ set => this.bytes[3] = value;
+ }
+
+ public UInt32 Address
+ {
+ get
+ {
+ var address = 0U;
+
+ address ^= (UInt32)this.bytes[4] << 24;
+ address ^= (UInt32)this.bytes[5] << 16;
+ address ^= (UInt32)this.bytes[6] << 8;
+ address ^= (UInt32)this.bytes[7] << 0;
+
+ return address;
+ }
+ set
+ {
+ this.bytes[4] = (Byte)(value >> 24);
+ this.bytes[5] = (Byte)(value >> 16);
+ this.bytes[6] = (Byte)(value >> 8);
+ this.bytes[7] = (Byte)(value >> 0);
+ }
+ }
+
+ public Byte Length => this.bytes[8];
+
+ public Byte[] Data
+ {
+ get
+ {
+ var data = new Byte[this.Length];
+
+ Array.Copy(this.bytes, 9, data, 0, this.Length);
+
+ return data;
+ }
+ set
+ {
+ if (value is null)
+ {
+ value = new Byte[0];
+ }
+
+ this.bytes[8] = (Byte)value.Length;
+
+ Array.Resize(ref this.bytes, MIN_LEN + this.Length);
+ Array.Clear(this.bytes, 9, this.bytes.Length - 9);
+ Array.Copy(value, 0, this.bytes, 9, this.Length);
+ }
+ }
+
+ public UInt16 CRC
+ {
+ get
+ {
+ var length = this.bytes.Length;
+ var crc = default(UInt16);
+
+ crc ^= (UInt16)(this.bytes[length - 3] << 8);
+ crc ^= (UInt16)(this.bytes[length - 2] << 0);
+
+ return crc;
+ }
+ }
+
+ public Byte[] ToByteArray()
+ {
+ var length = this.bytes.Length;
+ var crc = this.CRCCCITT(1, length - 3);
+
+ this.bytes[length - 3] = (Byte)(crc >> 8);
+ this.bytes[length - 2] = (Byte)(crc >> 0);
+ this.bytes[length - 1] = STOP;
+
+ return this.bytes;
+ }
+
+ public override String ToString()
+ => BitConverter.ToString(this.ToByteArray());
+
+ public static implicit operator Byte[](JustSirtMessage message)
+ => message.ToByteArray() ?? new Byte[0];
+
+ private UInt16 CRCCCITT(Int32 start, Int32 length)
+ {
+ var crc = (UInt16)0xFFFF;
+
+ for (var b = start; b < length; b++)
+ {
+ var _byte = this.bytes[b];
+ var token = (UInt16)((_byte << 8) & 0xFF00);
+
+ for (var i = 0; i < 8; i++)
+ {
+ if (0x8000 == ((crc ^ token) & 0x8000))
+ {
+ crc <<= 1;
+ crc ^= 0x1021;
+ }
+ else
+ {
+ crc <<= 1;
+ }
+
+ token <<= 1;
+ }
+ }
+
+ return crc;
+ }
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/JustSirtProxy.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/JustSirtProxy.cs
new file mode 100644
index 00000000..5b3ba0a5
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/JustSirtProxy.cs
@@ -0,0 +1,135 @@
+namespace Common.Hardware.Interfaces.Ports.Sirt
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Timers;
+
+ public class JustSirtProxy
+ {
+ private readonly JustSerialPort serialPort;
+ private readonly List buffer;
+ private readonly Timer timer;
+
+ public JustSirtProxy(String portName)
+ {
+ var settings = new SerialPortSettings
+ {
+ BaudRate = SerialPortBaudRate.X115200,
+ DataBits = SerialPortDataBits.X8,
+ Parity = SerialPortParity.None,
+ PortName = portName,
+ StopBits = SerialPortStopBits.One
+ };
+ this.serialPort = new JustSerialPort(settings);
+ this.buffer = new List();
+ this.timer = new Timer();
+ }
+
+ public event Action MessageReceived;
+
+ public Boolean IsOpen => this.serialPort.IsOpen;
+
+ public event Action Logging
+ {
+ add => this.serialPort.Logging += value;
+ remove => this.serialPort.Logging -= value;
+ }
+
+ public void Log(Object value) => this.serialPort.Log(value);
+
+ public Boolean TryClose()
+ {
+ var closed = false;
+
+ try
+ {
+ this.timer.Stop();
+ this.serialPort.TryClose();
+
+ closed = true;
+ }
+ catch (Exception e)
+ {
+ this.Log(e);
+ }
+
+ return closed;
+ }
+
+ public Boolean TryOpen()
+ {
+ var opened = this.serialPort.TryOpen();
+
+ if (opened)
+ {
+ this.timer.Elapsed += this.Timer_Elapsed;
+ this.timer.AutoReset = true;
+ this.timer.Interval = 50;
+ this.timer.Start();
+
+ opened = true;
+ }
+
+ return opened;
+ }
+
+ public void WriteBytes(params Byte[] bytes)
+ => this.serialPort.WriteBytes(bytes);
+
+ private Byte[] bytes;
+ private Int32 bytesLength;
+ private Int32 bufferLength;
+ private Int32 start;
+ private Int32 lengthIX;
+ private Byte length;
+ private Int32 stopIX;
+
+ private void Timer_Elapsed(Object sender, ElapsedEventArgs _1)
+ {
+ this.bytes = this.serialPort.ReadBytes();
+ this.bytesLength = this.bytes.Length;
+
+ if (this.bytesLength > 0)
+ {
+ this.buffer.AddRange(this.bytes);
+ }
+
+ this.bufferLength = this.buffer.Count;
+ this.start = this.buffer.IndexOf(JustSirtMessage.SIRT2PC);
+
+ if (this.start < 0)
+ {
+ this.buffer.Clear();
+
+ return;
+ }
+
+ this.lengthIX = this.start + 8;
+
+ if (this.lengthIX >= this.bufferLength)
+ {
+ return;
+ }
+
+ this.length = this.buffer[this.lengthIX];
+ this.stopIX = this.lengthIX + this.length + 3;
+
+ if (this.stopIX >= this.bufferLength)
+ {
+ return;
+ }
+ else if (this.buffer[this.stopIX] != JustSirtMessage.STOP)
+ {
+ return;
+ }
+
+ this.bytesLength = this.stopIX - this.start + 1;
+ this.bytes = new Byte[this.bytesLength];
+
+ this.buffer.CopyTo(this.start, this.bytes, 0, this.bytesLength);
+ this.buffer.RemoveRange(0, this.start + this.bytesLength);
+ this.MessageReceived?.Invoke(new JustSirtMessage(this.bytes));
+ }
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/AuthLevel.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/AuthLevel.cs
index 773aba4d..b44d72cb 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/AuthLevel.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/AuthLevel.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/BluetoothOperating.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/BluetoothOperating.cs
index 08dc29bd..99808a1e 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/BluetoothOperating.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/BluetoothOperating.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/ByteExtensions.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/ByteExtensions.cs
index 7998ddce..126d2107 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/ByteExtensions.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/ByteExtensions.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/OperatingModes.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/OperatingModes.cs
index 40e3c564..d3f71913 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/OperatingModes.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/OperatingModes.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
public enum OperatingModes
{
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P11.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P11.cs
index 8db46bc4..5190ae48 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P11.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P11.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P12.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P12.cs
index a08d608b..84df10ad 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P12.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P12.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P811.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P811.cs
index b75e6f3e..1560ca73 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P811.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/P811.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/PamTimeout.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/PamTimeout.cs
index 82439494..c4de0a52 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/PamTimeout.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/PamTimeout.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/RFModuleOperating.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/RFModuleOperating.cs
index 1bd570b9..46e6ab45 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/RFModuleOperating.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/RFModuleOperating.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/SirtOperating.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/SirtOperating.cs
index 0ca06941..3f1ae2c3 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/SirtOperating.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Parameters/SirtOperating.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Parameters
+namespace Common.Hardware.Interfaces.Ports.Sirt.Parameters
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/ReadPamRequest.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/ReadPamRequest.cs
index 1286ac80..163d86b0 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/ReadPamRequest.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/ReadPamRequest.cs
@@ -1,6 +1,6 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Requests
+namespace Common.Hardware.Interfaces.Ports.Sirt.Requests
{
- using Common.Hardware.Interfaces.Ports.SIRT;
+ using Common.Hardware.Interfaces.Ports.Sirt;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/ReadRegRequest.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/ReadRegRequest.cs
index 63204a19..ffa8a30c 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/ReadRegRequest.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/ReadRegRequest.cs
@@ -1,6 +1,6 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Requests
+namespace Common.Hardware.Interfaces.Ports.Sirt.Requests
{
- using Common.Hardware.Interfaces.Ports.SIRT;
+ using Common.Hardware.Interfaces.Ports.Sirt;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/WritePamRequest.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/WritePamRequest.cs
index 6ee93778..4a8ad6de 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/WritePamRequest.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/WritePamRequest.cs
@@ -1,7 +1,7 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Requests
+namespace Common.Hardware.Interfaces.Ports.Sirt.Requests
{
- using Common.Hardware.Interfaces.Ports.SIRT;
- using Common.Hardware.Interfaces.Ports.SIRT.Parameters;
+ using Common.Hardware.Interfaces.Ports.Sirt;
+ using Common.Hardware.Interfaces.Ports.Sirt.Parameters;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/WriteRegRequest.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/WriteRegRequest.cs
index 6bb31c25..2884faef 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/WriteRegRequest.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Requests/WriteRegRequest.cs
@@ -1,6 +1,6 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Requests
+namespace Common.Hardware.Interfaces.Ports.Sirt.Requests
{
- using Common.Hardware.Interfaces.Ports.SIRT;
+ using Common.Hardware.Interfaces.Ports.Sirt;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Responses/AcknOrAnswerResponse.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Responses/AcknOrAnswerResponse.cs
index 694d24b9..85edc932 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Responses/AcknOrAnswerResponse.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Responses/AcknOrAnswerResponse.cs
@@ -1,6 +1,6 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Responses
+namespace Common.Hardware.Interfaces.Ports.Sirt.Responses
{
- using Common.Hardware.Interfaces.Ports.SIRT.Parameters;
+ using Common.Hardware.Interfaces.Ports.Sirt.Parameters;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Responses/FromAirResponse.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Responses/FromAirResponse.cs
index 0e2fe379..f047291f 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Responses/FromAirResponse.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Responses/FromAirResponse.cs
@@ -1,6 +1,6 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Responses
+namespace Common.Hardware.Interfaces.Ports.Sirt.Responses
{
- using Common.Hardware.Interfaces.Ports.SIRT.Parameters;
+ using Common.Hardware.Interfaces.Ports.Sirt.Parameters;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTRequest.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTRequest.cs
index 3d5dad0d..f69f0a82 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTRequest.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTRequest.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT
+namespace Common.Hardware.Interfaces.Ports.Sirt
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTResponse.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTResponse.cs
index 9639b92a..9f6183e9 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTResponse.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTResponse.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT
+namespace Common.Hardware.Interfaces.Ports.Sirt
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTTask[TRequest].cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTTask[TRequest].cs
index 3a2aaee5..0df55bcc 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTTask[TRequest].cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SIRTTask[TRequest].cs
@@ -1,6 +1,6 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT
+namespace Common.Hardware.Interfaces.Ports.Sirt
{
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
+ using Common.Hardware.Interfaces.Ports.Sirt.Responses;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtBroadcaster.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtBroadcaster.cs
index 95ba8780..81a5dd56 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtBroadcaster.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtBroadcaster.cs
@@ -1,7 +1,7 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT
+namespace Common.Hardware.Interfaces.Ports.Sirt
{
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
- using Common.Hardware.Interfaces.Ports.SIRT.Tasks;
+ using Common.Hardware.Interfaces.Ports.Sirt.Responses;
+ using Common.Hardware.Interfaces.Ports.Sirt.Tasks;
using System;
using System.Collections.Concurrent;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtConstants.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtConstants.cs
index a65dd005..b32094de 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtConstants.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtConstants.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT
+namespace Common.Hardware.Interfaces.Ports.Sirt
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtMessage.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtMessage.cs
index fb65ac63..84efb828 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtMessage.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtMessage.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT
+namespace Common.Hardware.Interfaces.Ports.Sirt
{
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtTask.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtTask.cs
index 65c9ddaa..ef5eb16e 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtTask.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/SirtTask.cs
@@ -1,7 +1,7 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT
+namespace Common.Hardware.Interfaces.Ports.Sirt
{
- using Common.Hardware.Interfaces.Ports.SIRT.Requests;
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
+ using Common.Hardware.Interfaces.Ports.Sirt.Requests;
+ using Common.Hardware.Interfaces.Ports.Sirt.Responses;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/ActivateSIRTTask.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/ActivateSIRTTask.cs
index 3edcd315..90e854ed 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/ActivateSIRTTask.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/ActivateSIRTTask.cs
@@ -1,8 +1,8 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Tasks
+namespace Common.Hardware.Interfaces.Ports.Sirt.Tasks
{
- using Common.Hardware.Interfaces.Ports.SIRT.Parameters;
- using Common.Hardware.Interfaces.Ports.SIRT.Requests;
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
+ using Common.Hardware.Interfaces.Ports.Sirt.Parameters;
+ using Common.Hardware.Interfaces.Ports.Sirt.Requests;
+ using Common.Hardware.Interfaces.Ports.Sirt.Responses;
using System;
@@ -20,7 +20,7 @@
new BluetoothOperating { BtOff = true },
new RFModuleOperating { RfOff = true },
new RFModuleOperating { OpMode = OperatingModes.ReceiveF1TransmitSensusRFF3 },
- // new PamTimeout { Minutes = 1 }
+ new PamTimeout { Minutes = 1 }
};
}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/DeleteFromPamPoolTask.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/DeleteFromPamPoolTask.cs
index 2d6f52f4..ecaacb53 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/DeleteFromPamPoolTask.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/DeleteFromPamPoolTask.cs
@@ -1,8 +1,8 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Tasks
+namespace Common.Hardware.Interfaces.Ports.Sirt.Tasks
{
using System;
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
+ using Common.Hardware.Interfaces.Ports.Sirt.Responses;
public class DeleteFromPamPoolTask : WritePamTask
{
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/IdentifySIRTTask.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/IdentifySIRTTask.cs
index 18f0e7c5..21cf0319 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/IdentifySIRTTask.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/IdentifySIRTTask.cs
@@ -1,7 +1,7 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Tasks
+namespace Common.Hardware.Interfaces.Ports.Sirt.Tasks
{
- using Common.Hardware.Interfaces.Ports.SIRT.Requests;
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
+ using Common.Hardware.Interfaces.Ports.Sirt.Requests;
+ using Common.Hardware.Interfaces.Ports.Sirt.Responses;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/ReadPamPoolTask.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/ReadPamPoolTask.cs
index b88b4d94..d4c24c25 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/ReadPamPoolTask.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/ReadPamPoolTask.cs
@@ -1,7 +1,7 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT.Tasks
+namespace Common.Hardware.Interfaces.Ports.Sirt.Tasks
{
- using Common.Hardware.Interfaces.Ports.SIRT.Requests;
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
+ using Common.Hardware.Interfaces.Ports.Sirt.Requests;
+ using Common.Hardware.Interfaces.Ports.Sirt.Responses;
using System;
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/WritePamTask.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/WritePamTask.cs
index fedde649..2fce37d7 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/WritePamTask.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SIRT/Tasks/WritePamTask.cs
@@ -1,6 +1,6 @@
-namespace Common.Hardware.Interfaces.Ports.SIRT
+namespace Common.Hardware.Interfaces.Ports.Sirt
{
- using Common.Hardware.Interfaces.Ports.SIRT.Requests;
+ using Common.Hardware.Interfaces.Ports.Sirt.Requests;
using System;
diff --git a/Common/Ui/Common.UI.WPFConnector/Common.UI.WPFConnector.csproj b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Common.Hardware.Interfaces.Ports.SirtBroadcaster.csproj
similarity index 55%
rename from Common/Ui/Common.UI.WPFConnector/Common.UI.WPFConnector.csproj
rename to Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Common.Hardware.Interfaces.Ports.SirtBroadcaster.csproj
index ba3a3fb7..27f8de1f 100644
--- a/Common/Ui/Common.UI.WPFConnector/Common.UI.WPFConnector.csproj
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Common.Hardware.Interfaces.Ports.SirtBroadcaster.csproj
@@ -4,16 +4,18 @@
Debug
AnyCPU
- {37E4BF89-44AE-4133-BE0B-8355F791A79D}
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}
Library
- Properties
- Common.UI.WPFConnector
- Common.UI.WPFConnector
+ Common.Hardware.Interfaces.Ports.SirtBroadcaster
+ Common.Hardware.Interfaces.Ports.SirtBroadcaster
v4.0
512
+ true
true
+
+ AnyCPU
true
full
false
@@ -24,6 +26,7 @@
IDE0003;IDE0049;
+ AnyCPU
pdbonly
true
bin\Release\
@@ -31,8 +34,10 @@
prompt
4
+
+
+
-
@@ -40,20 +45,31 @@
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
- {4E8BB839-D40A-488C-88CE-F21811F1F476}
- Common.Hardware.WaterMeter.eRegister
+
+ {05F0CCAF-9F2B-45F9-A7F8-12F29AD182F3}
+ Common.Utils.Extensions
-
- {f7316525-ff8e-4651-ba67-3c9b948d1e91}
- Common.UI.WPF
+
+ {B23BFAF9-08AE-4311-8C08-FB2BB49EA2AD}
+ Common.Hardware.Interfaces.Ports.Sirt
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustSirtBroadcaster.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustSirtBroadcaster.cs
new file mode 100644
index 00000000..d65f0d8f
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustSirtBroadcaster.cs
@@ -0,0 +1,168 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster
+{
+ using Common.Hardware.Interfaces.Ports.Sirt;
+
+ using System;
+ using System.Collections.Concurrent;
+ using System.Threading;
+
+ public class JustSirtBroadcaster
+ {
+ private static readonly ConcurrentDictionary runningTasks
+ = new ConcurrentDictionary();
+ private readonly JustSirtProxy proxy;
+
+ public JustSirtBroadcaster(String portName)
+ {
+ this.proxy = new JustSirtProxy(portName);
+ this.proxy.MessageReceived += this.Proxy_MessageReceived;
+ }
+
+ public event Action Logging
+ {
+ add => this.proxy.Logging += value;
+ remove => this.proxy.Logging -= value;
+ }
+
+ public String SirtId { get; private set; }
+
+ public Int32 MHz { get; private set; }
+
+ public void Log(Object value) => this.proxy.Log(value);
+
+ public Boolean TryActivate()
+ {
+ var activated = this.proxy.TryOpen();
+
+ if (activated)
+ {
+ runningTasks.Clear();
+ }
+
+ var awaiter = new ManualResetEventSlim();
+
+ var task = JustSirtTask.ActivateSIRT;
+ task.Cancelled += _ => awaiter.Set();
+ task.Completed += _task =>
+ {
+ activated = _task.TaskStatus == JustTaskStatus.Completed;
+
+ if (activated)
+ {
+ awaiter.Set();
+ }
+ };
+ task = runningTasks.AddOrUpdate(task.Address, task, (a, t) => task);
+
+ task.PrepareForRun();
+ this.proxy.WriteBytes(task);
+ this.Log(task);
+ awaiter.Wait();
+ awaiter.Reset();
+
+ if (activated)
+ {
+ task = JustSirtTask.IdentifySIRT;
+ task.Cancelled += _ => awaiter.Set();
+ task.Completed += _task =>
+ {
+ activated = _task.TaskStatus == JustTaskStatus.Completed;
+
+ if (activated)
+ {
+ awaiter.Set();
+ }
+ };
+ task = runningTasks.AddOrUpdate(task.Address, task, (a, t) => task);
+
+ task.PrepareForRun();
+ this.proxy.WriteBytes(task);
+ this.Log(task);
+ awaiter.Wait();
+ awaiter.Reset();
+
+ if (activated)
+ {
+ this.SirtId = BitConverter.ToString(task.LastPayload);
+ this.MHz = this.SirtId[10] == '0' ? 868 : 433;
+ }
+ }
+
+ return activated;
+ }
+
+ public Boolean TryDeactivate()
+ {
+ this.proxy.MessageReceived -= this.Proxy_MessageReceived;
+
+ return this.proxy.TryClose();
+ }
+
+ public JustTaskStatus TryRun(JustSirtTask task)
+ {
+ if (!this.proxy.IsOpen)
+ {
+ return JustTaskStatus.ProxyNotOpen;
+ }
+
+ var address = task.Address;
+
+ if (runningTasks.TryGetValue(address, out var runningTask) && runningTask != null)
+ {
+ return JustTaskStatus.InRunningTasks;
+ }
+
+ var countInPamPool = 0;
+
+ foreach (var _task in runningTasks.Values)
+ {
+ if (_task != null && _task.Cmd == JustSirtMessage.W_PAM)
+ {
+ countInPamPool++;
+ }
+ }
+
+ if (countInPamPool >= 5)
+ {
+ return JustTaskStatus.PamPoolIsFull;
+ }
+
+ task = runningTasks.AddOrUpdate(address, task, (a, t) => task);
+
+ if (task.TaskStatus == JustTaskStatus.Completed)
+ {
+ this.Task_DismissFromRunningTasks(task);
+
+ return JustTaskStatus.Completed;
+ }
+
+ task.Cancelled += this.Task_DismissFromRunningTasks;
+ task.Completed += this.Task_DismissFromRunningTasks;
+
+ task.PrepareForRun();
+ this.proxy.WriteBytes(task);
+ this.Log($"{task.Address}|{BitConverter.ToString(task)}");
+
+ return JustTaskStatus.Sent;
+ }
+
+ private void Proxy_MessageReceived(JustSirtMessage message)
+ {
+ var address = message.Address;
+
+ if (runningTasks.TryGetValue(address, out var task) && task != null)
+ {
+ task.ReceiveMessage(message, this.MHz);
+ this.Log($"{address}|{message}");
+ }
+ }
+
+ private void Task_DismissFromRunningTasks(JustSirtTask task)
+ {
+ task.Cancelled -= this.Task_DismissFromRunningTasks;
+ task.Completed -= this.Task_DismissFromRunningTasks;
+
+ runningTasks.TryRemove(task.Address, out var _);
+ }
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustSirtTask.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustSirtTask.cs
new file mode 100644
index 00000000..ab12f286
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustSirtTask.cs
@@ -0,0 +1,143 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster
+{
+ using Common.Hardware.Interfaces.Ports.Sirt;
+ using Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters;
+
+ using System;
+ using System.Collections.Concurrent;
+ using System.Timers;
+
+ public class JustSirtTask
+ {
+ private readonly Timer timer = new Timer();
+ private readonly JustSirtMessage request = new JustSirtMessage();
+ private readonly ConcurrentStack responses = new ConcurrentStack();
+
+ public event Action Completed;
+ public event Action Cancelled;
+
+ public Byte Cmd
+ {
+ get => this.request.Cmd;
+ set => this.request.Cmd = value;
+ }
+
+ public Byte P1
+ {
+ get => this.request.P1;
+ set => this.request.P1 = value;
+ }
+
+ public Byte P2
+ {
+ get => this.request.P2;
+ set => this.request.P2 = value;
+ }
+
+ public UInt32 Address
+ {
+ get => this.request.Address;
+ set => this.request.Address = value;
+ }
+
+ public Byte[] Data
+ {
+ get => this.request.Data;
+ set => this.request.Data = value;
+ }
+
+ public JustTaskStatus TaskStatus { get; protected set; }
+
+ public Byte[] LastPayload
+ => this.responses.TryPeek(out var response)
+ ? response.Data
+ : default(Byte[]);
+
+ public virtual void ReceiveMessage(JustSirtMessage response, Int32 mhz)
+ {
+ this.responses.Push(response);
+
+ if (this.TaskStatus != JustTaskStatus.Completed)
+ {
+ this.TaskStatus = JustTaskStatus.Running;
+
+ if (this.request.Cmd == JustSirtMessage.W_PAM)
+ {
+ if (response.Cmd == JustSirtMessage.FROMAIR && response.Data[0] == JustSirtMessage.SEMI)
+ {
+ this.TaskStatus = JustTaskStatus.Completed;
+ }
+ }
+ else if (response.Cmd == JustSirtMessage.ACKNANSW)
+ {
+ this.TaskStatus = JustTaskStatus.Completed;
+ }
+ }
+
+ if (this.TaskStatus == JustTaskStatus.Completed)
+ {
+ this.Completed?.Invoke(this);
+ this.timer.Stop();
+ }
+ }
+
+ public virtual void PrepareForRun()
+ {
+ this.responses.Clear();
+ this.TaskStatus = JustTaskStatus.Pending;
+ this.timer.AutoReset = false;
+ this.timer.Interval = 10_000;
+ this.timer.Elapsed += (sender, _1) =>
+ {
+ this.TaskStatus = JustTaskStatus.Cancelled;
+
+ this.Cancelled?.Invoke(this);
+ };
+ this.timer.Start();
+ }
+
+ public virtual Byte[] ToByteArray()
+ => this.request.ToByteArray();
+
+ public override String ToString()
+ => BitConverter.ToString(this.ToByteArray());
+
+ public static implicit operator Byte[] (JustSirtTask task)
+ => task?.ToByteArray() ?? new Byte[] { };
+
+ public static readonly JustSirtTask ActivateSIRT = new JustSirtTask
+ {
+ Cmd = JustSirtMessage.W_REG,
+ Address = 0x20000000,
+ P2 = 0x05,
+ Data = new Byte[]
+ {
+ new SirtOperating { /* default */ },
+ new BluetoothOperating { BtOff = true },
+ new RFModuleOperating { RfOff = true },
+ new RFModuleOperating { OpMode = OperatingModes.ReceiveF1TransmitSensusRFF3 },
+ new PamTimeout { Minutes = 1 }
+ }
+ };
+
+ public static readonly JustSirtTask IdentifySIRT = new JustSirtTask
+ {
+ Cmd = JustSirtMessage.R_REG,
+ Address = 0x11001820,
+ P2 = 0x08
+ };
+
+ public static readonly JustSirtTask ReadPamPool = new JustSirtTask
+ {
+ Cmd = JustSirtMessage.R_PAM,
+ Address = 0xFFFFFFFF
+ };
+
+ public static JustSirtTask DeleteFromPamPool(UInt32 address) => new JustSirtTask
+ {
+ Cmd = JustSirtMessage.W_PAM,
+ P1 = new P811 { DelPamAdr = true },
+ Address = address
+ };
+}
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustTaskStatus.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustTaskStatus.cs
new file mode 100644
index 00000000..d554b507
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/JustTaskStatus.cs
@@ -0,0 +1,15 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster
+{
+ public enum JustTaskStatus
+ {
+ Pending = 0,
+ Running = 1,
+ Completed = 2,
+ Cancelled = 3,
+ InRunningTasks = 4,
+ PamPoolIsFull = 5,
+ InPamPool = 6,
+ Sent = 7,
+ ProxyNotOpen = 8,
+ }
+}
\ No newline at end of file
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/BluetoothOperating.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/BluetoothOperating.cs
new file mode 100644
index 00000000..b06d1b6e
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/BluetoothOperating.cs
@@ -0,0 +1,63 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ using System;
+
+ public class BluetoothOperating
+ {
+ private readonly Byte[] bits;
+
+ public BluetoothOperating() => this.bits = new Byte[8];
+
+ private BluetoothOperating(Byte[] bits) => this.bits = bits;
+
+ ///
+ /// 0 -> Transparent Mode at 115k2 Baud 8,n,1
+ ///
+ public Boolean BtOpMode
+ {
+ get => this.bits[0] == 1;
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// after "TIME_OFF" is elapsed without any command via Bluetooth, Bluetooth interface will be switched off
+ ///
+ /// -
+ /// false
+ /// normal operation
+ ///
+ ///
+ ///
+ public Boolean BtPwrSave
+ {
+ get => this.bits[6] == 1;
+ set => this.bits[6] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// BT module will be switched off
+ ///
+ /// -
+ /// false
+ /// normal operation
+ ///
+ ///
+ ///
+ public Boolean BtOff
+ {
+ get => this.bits[7] == 1;
+ set => this.bits[7] = (Byte)(value ? 1 : 0);
+ }
+
+ public static implicit operator Byte(BluetoothOperating param)
+ => param.bits.GetByte();
+
+ public static implicit operator BluetoothOperating(Byte _byte)
+ => new BluetoothOperating(_byte.GetBits());
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/ByteExtensions.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/ByteExtensions.cs
new file mode 100644
index 00000000..1eea4a9b
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/ByteExtensions.cs
@@ -0,0 +1,31 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ using System;
+
+ public static class ByteExtensions
+ {
+ public static Byte[] GetBits(this Byte @byte)
+ {
+ var bits = new Byte[8];
+
+ for (int i = 0; i < 8; i++)
+ {
+ bits[i] = (Byte)((@byte >> i) & 1);
+ }
+
+ return bits;
+ }
+
+ public static Byte GetByte(this Byte[] bits)
+ {
+ var @byte = default(int);
+
+ for (int i = 0; i < 8; i++)
+ {
+ @byte |= bits[i] << i;
+ }
+
+ return (Byte)@byte;
+ }
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/OperatingModes.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/OperatingModes.cs
new file mode 100644
index 00000000..2611e461
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/OperatingModes.cs
@@ -0,0 +1,14 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ public enum OperatingModes
+ {
+ Off = 0,
+ ReceiveF1TransmitSensusRFF3 = 1,
+ ReceiveF2TransmitSensusRFF2 = 2,
+ ReceiveWirelessMbusT1CMode = 3,
+ ReceiveWirelessMbusS1Mode = 4,
+ Receive = 5,
+ TestMode = 8,
+ Undefined = 15
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P11.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P11.cs
new file mode 100644
index 00000000..6d6f1b1b
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P11.cs
@@ -0,0 +1,178 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ using System;
+
+ ///
+ /// Parameter P11 is given at third position of "Telegram from Air" telegram and give more detailed information about the
+ /// received packets from radio section of SIRT.The bits of Parameter 11 are decoded as following, where Bit 0 is the least
+ /// significant bit:
+ ///
+ public class P11
+ {
+ private readonly Byte[] bits;
+
+ public P11() => this.bits = new Byte[8];
+
+ private P11(Byte[] bits) => this.bits = bits;
+
+ ///
+ ///
+ /// -
+ /// true
+ /// RF-Module2 is source
+ ///
+ /// -
+ /// false
+ /// RF-Module1 is source
+ ///
+ ///
+ /// only valid if both RF-Module programmed for Sensus RF
+ ///
+ public Boolean SrcChannel
+ {
+ get => this.bits[0] == 1;
+ set => this.bits[0] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// both RF module data are valid
+ ///
+ /// -
+ /// false
+ /// only one RF module data is valid
+ ///
+ ///
+ /// only valid if both RF-Module programmed for Sensus RF
+ ///
+ public Boolean BothValid
+ {
+ get => this.bits[1] == 1;
+ set => this.bits[1] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// RF-Module1 data is invalid
+ ///
+ /// -
+ /// false
+ /// RF-Module1 data is valid
+ ///
+ ///
+ /// i.e. radio checksum is wrong ...
+ ///
+ public Boolean InvalidMod1
+ {
+ get => this.bits[2] == 1;
+ set => this.bits[2] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// RF-Module2 data is invalid
+ ///
+ /// -
+ /// false
+ /// RF-Module2 data is valid
+ ///
+ ///
+ /// i.e. radio checksum is wrong ...
+ ///
+ public Boolean InvalidMod2
+ {
+ get => this.bits[3] == 1;
+ set => this.bits[3] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// invalid -> module detects length > 128
+ ///
+ /// -
+ /// false
+ /// all ok
+ ///
+ ///
+ ///
+ public Boolean LenOverflow
+ {
+ get => this.bits[4] == 1;
+ set => this.bits[4] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// will look at PAM / RAC Pool
+ ///
+ /// -
+ /// false
+ /// no attention for PAM / RAC
+ ///
+ ///
+ ///
+ public Boolean Attention
+ {
+ get => this.bits[5] == 1;
+ set => this.bits[5] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ ///
+ /// If .modeSensus = 0 wireless M-busMode -> T1 - Mode
+ /// If .modeSensus = 1 SensusRF -> receive at f2
+ ///
+ ///
+ /// -
+ /// false
+ ///
+ /// If .modeSensus = 0 wireless M-busMode -> S1 - Mode
+ /// If .modeSensus = 1 SensusRF -> receive at f1
+ ///
+ ///
+ ///
+ ///
+ public Boolean ModeRF
+ {
+ get => this.bits[6] == 1;
+ set => this.bits[6] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// Sensus RF Mode
+ ///
+ /// -
+ /// false
+ /// wireless M-Bus Mode
+ ///
+ ///
+ ///
+ public Boolean ModeSensus
+ {
+ get => this.bits[7] == 1;
+ set => this.bits[7] = (Byte)(value ? 1 : 0);
+ }
+
+ public static implicit operator Byte(P11 param)
+ => param.bits.GetByte();
+
+ public static implicit operator P11(Byte _byte)
+ => new P11(_byte.GetBits());
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P12.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P12.cs
new file mode 100644
index 00000000..6e435376
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P12.cs
@@ -0,0 +1,170 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ using System;
+
+ ///
+ /// P12 is the parameter of "Acknowledge or Answer" message and is placed at third position,
+ /// if telegram from SIRT-> PC begins with {0xFF, 0x12}.
+ /// This parameter gives more detailed information about the last command or request which
+ /// was send to SIRT.
+ /// Parameter 12 is given at third position of acknowledge- or answer telegram from SIRT.
+ ///
+ public class P12
+ {
+ private readonly Byte[] bits;
+
+ public P12() => this.bits = new Byte[8];
+
+ private P12(Byte[] bits) => this.bits = bits;
+
+ ///
+ ///
+ /// -
+ /// true
+ /// requested buffer is full or not available
+ ///
+ /// -
+ /// false
+ /// Ok
+ ///
+ ///
+ ///
+ public Boolean BufFull
+ {
+ get => this.bits[0] == 1;
+ set => this.bits[0] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// operating system is busy
+ ///
+ /// -
+ /// false
+ /// Ok
+ ///
+ ///
+ ///
+ public Boolean OsBusy
+ {
+ get => this.bits[1] == 1;
+ set => this.bits[1] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// wrong CRC recognized
+ ///
+ /// -
+ /// false
+ /// Ok
+ ///
+ ///
+ ///
+ public Boolean WrongCRC
+ {
+ get => this.bits[2] == 1;
+ set => this.bits[2] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// command cannot be executed
+ ///
+ /// -
+ /// false
+ /// Ok
+ ///
+ ///
+ ///
+ public Boolean CmdNotExecuted
+ {
+ get => this.bits[3] == 1;
+ set => this.bits[3] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// telegram or command Byte unknown
+ ///
+ /// -
+ /// false
+ /// Ok
+ ///
+ ///
+ ///
+ public Boolean CmdUnknown
+ {
+ get => this.bits[4] == 1;
+ set => this.bits[4] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// no such entry found
+ ///
+ /// -
+ /// false
+ /// Ok
+ ///
+ ///
+ ///
+ public Boolean NoEntry
+ {
+ get => this.bits[5] == 1;
+ set => this.bits[5] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// unknown fixed byte
+ ///
+ /// -
+ /// false
+ /// Ok
+ ///
+ ///
+ ///
+ public Boolean ByteUnknown
+ {
+ get => this.bits[6] == 1;
+ set => this.bits[6] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// address was 0xFFFFFFFF
+ ///
+ /// -
+ /// false
+ /// normal address
+ ///
+ ///
+ ///
+ public Boolean WildCardAddr
+ {
+ get => this.bits[7] == 1;
+ set => this.bits[7] = (Byte)(value ? 1 : 0);
+ }
+
+ public static implicit operator Byte(P12 param)
+ => param.bits.GetByte();
+
+ public static implicit operator P12(Byte _byte)
+ => new P12(_byte.GetBits());
+ }
+}
\ No newline at end of file
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P811.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P811.cs
new file mode 100644
index 00000000..bafefbac
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/P811.cs
@@ -0,0 +1,241 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ using System;
+
+ ///
+ /// Parameter P81-1 is the first modifier of "Write to PAM Pool" command and is placed at third position,
+ /// if telegram from PC -> SIRT begins with {0x55, 0x81}.
+ /// This Byte describe in detailed what PAM message should do in detail.
+ /// There is an public priority within the bits which are described at next table:
+ ///
+ ///
+ /// 7
+ /// 6
+ /// 5
+ /// 4
+ /// 3
+ /// 2
+ /// 1
+ /// 0
+ /// Description
+ ///
+ /// -
+ /// 1
+ /// X
+ /// X
+ /// X
+ /// X
+ /// X
+ /// X
+ /// X
+ /// delete all entries from pool, regardless of address
+ ///
+ /// -
+ /// 0
+ /// 1
+ /// X
+ /// X
+ /// X
+ /// X
+ /// X
+ /// X
+ /// delete entry with this radio address from pool
+ ///
+ /// -
+ /// 0
+ /// 0
+ /// 1
+ /// X
+ /// X
+ /// X
+ /// X
+ /// X
+ /// write entry with this radio address to pool and delete after transmit
+ ///
+ /// -
+ /// 0
+ /// 0
+ /// 0
+ /// 1
+ /// X
+ /// X
+ /// X
+ /// X
+ /// write entry with this radio address to pool and delete after SEMI received
+ ///
+ /// -
+ /// 0
+ /// 0
+ /// 0
+ /// 0
+ /// 1
+ /// X
+ /// X
+ /// X
+ /// write entry with this radio address to pool and leave entry at pool
+ ///
+ /// -
+ /// 0
+ /// 0
+ /// 0
+ /// 0
+ /// 0
+ /// 1
+ /// X
+ /// 0/1
+ /// write entry with this radio address to pool, create Wake Up sequence and send out PAM after receive a BUP(LAT) from this address and delete after timeOutPam is elapsed
+ ///
+ /// -
+ /// 0
+ /// 0
+ /// 0
+ /// 0
+ /// 0
+ /// 0
+ /// X
+ /// X
+ /// write entry with this radio address to pool and delete after timeOutPam is elapsed
+ ///
+ ///
+ ///
+ public class P811
+ {
+ private readonly Byte[] bits;
+
+ public P811() => this.bits = new Byte[8];
+
+ private P811(Byte[] bits) => this.bits = bits;
+
+ ///
+ ///
+ /// -
+ /// true
+ /// module 2 is Wakeup Transmitter
+ ///
+ /// -
+ /// false
+ /// module 1 is Wakeup Transmitter
+ ///
+ ///
+ ///
+ public Boolean WakeUpModul
+ {
+ get => this.bits[0] == 1;
+ set => this.bits[0] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// first transmit Wakeup Sequence and afterwards normal PAM
+ ///
+ /// -
+ /// false
+ /// normal PAM
+ ///
+ ///
+ ///
+ public Boolean WakeUpCmd
+ {
+ get => this.bits[2] == 1;
+ set => this.bits[2] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// ignore timeout register for automatic delete of PAM
+ ///
+ /// -
+ /// false
+ /// do nothing special
+ ///
+ ///
+ ///
+ public Boolean IgnoreTimeout
+ {
+ get => this.bits[3] == 1;
+ set => this.bits[3] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// delete entry from PAM pool after SEMI receipt
+ ///
+ /// -
+ /// false
+ /// do nothing after SEMI receipt
+ ///
+ ///
+ ///
+ public Boolean DelPamSemi
+ {
+ get => this.bits[4] == 1;
+ set => this.bits[4] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// delete entry from PAM pool after PAM transmit
+ ///
+ /// -
+ /// false
+ /// do nothing after PAM transmit
+ ///
+ ///
+ ///
+ public Boolean DelPamTx
+ {
+ get => this.bits[5] == 1;
+ set => this.bits[5] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// delete from PAM pool
+ ///
+ /// -
+ /// false
+ /// write to PAM pool
+ ///
+ ///
+ ///
+ public Boolean DelPamAdr
+ {
+ get => this.bits[6] == 1;
+ set => this.bits[6] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// delete all entries from PAM pool
+ ///
+ /// -
+ /// false
+ /// do nothing special
+ ///
+ ///
+ ///
+ public Boolean DelPamAll
+ {
+ get => this.bits[7] == 1;
+ set => this.bits[7] = (Byte)(value ? 1 : 0);
+ }
+
+ public static implicit operator Byte(P811 param)
+ => param.bits.GetByte();
+
+ public static implicit operator P811(Byte _byte)
+ => new P811(_byte.GetBits());
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/PAMStatus.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/PAMStatus.cs
new file mode 100644
index 00000000..d1a20132
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/PAMStatus.cs
@@ -0,0 +1,65 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster
+{
+ using Common.Utils.Extensions;
+
+ using System;
+
+ public class PAMStatus
+ {
+ private readonly Byte[] bits;
+
+ public PAMStatus(Byte _byte)
+ => this.bits = _byte.GetBits();
+
+ public Boolean CMD_UNKNOWN => this.bits[0] == 1;
+
+ public Boolean WRONG_AUTH => this.bits[1] == 1;
+
+ public Boolean EXPIRED_AUTH => this.bits[2] == 1;
+
+ public Boolean MIXED_TYPES => this.bits[3] == 1;
+
+ public Boolean OUT_OF_RANGE => this.bits[4] == 1;
+
+ public override String ToString()
+ {
+ var status = nameof(OK);
+ var value = this.bits.ToByte();
+
+ if ((value & 1) == 1)
+ {
+ status = nameof(CMD_UNKNOWN);
+ }
+
+ if ((value & 2) == 2)
+ {
+ status = nameof(WRONG_AUTH);
+ }
+
+ if ((value & 4) == 4)
+ {
+ status = nameof(EXPIRED_AUTH);
+ }
+
+ if ((value & 8) == 8)
+ {
+ status = nameof(MIXED_TYPES);
+ }
+
+ if ((value & 16) == 16)
+ {
+ status = nameof(OUT_OF_RANGE);
+ }
+
+ return status;
+ }
+
+ public static Byte OK = 0;
+
+ public static implicit operator Byte(PAMStatus status)
+ => status?.bits?.ToByte() ?? 0xFF;
+
+ public static implicit operator String(PAMStatus status)
+ => status?.ToString();
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/PamTimeout.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/PamTimeout.cs
new file mode 100644
index 00000000..70b95d7f
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/PamTimeout.cs
@@ -0,0 +1,32 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ using System;
+
+ public class PamTimeout
+ {
+ public PamTimeout() => this.Minutes = 0;
+
+ private PamTimeout(Byte minutes) => this.Minutes = minutes;
+
+ ///
+ ///
+ /// -
+ /// value == 0
+ /// PAM will never automatically deleted
+ ///
+ /// -
+ /// value != 0
+ /// duration after a PAM will be automatically deleted out of PAM-Pool, if no other rule deletes entry before
+ ///
+ ///
+ /// Several bits at parameter P81-1 or P81-2 may delete entry at PAM-Pool before 5 minutes elapsed.
+ ///
+ public Byte Minutes { get; set; }
+
+ public static implicit operator Byte(PamTimeout param)
+ => param.Minutes;
+
+ public static implicit operator PamTimeout(Byte _byte)
+ => new PamTimeout(_byte);
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/RFModuleOperating.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/RFModuleOperating.cs
new file mode 100644
index 00000000..37c5fe33
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/RFModuleOperating.cs
@@ -0,0 +1,76 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ using System;
+
+ public class RFModuleOperating
+ {
+ private readonly Byte[] bits;
+
+ public RFModuleOperating() => this.bits = new Byte[8];
+
+ private RFModuleOperating(Byte[] bits) => this.bits = bits;
+
+ ///
+ /// 0 -> Transparent Mode at 115k2 Baud 8,n,1
+ ///
+ public OperatingModes OpMode
+ {
+ get
+ {
+ var bits = new Byte[8];
+
+ Array.Copy(this.bits, 0, bits, 0, 4);
+
+ return (OperatingModes)bits.GetByte();
+ }
+ set
+ {
+ var bits = ((Byte)value).GetBits();
+
+ Array.Copy(bits, 0, this.bits, 0, 4);
+ }
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// external antenna
+ ///
+ /// -
+ /// false
+ /// internal antenna
+ ///
+ ///
+ ///
+ public Boolean Antenna
+ {
+ get => this.bits[4] == 1;
+ set => this.bits[4] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// Module not powered
+ ///
+ /// -
+ /// false
+ /// Module powered
+ ///
+ ///
+ ///
+ public Boolean RfOff
+ {
+ get => this.bits[7] == 1;
+ set => this.bits[7] = (Byte)(value ? 1 : 0);
+ }
+
+ public static implicit operator Byte(RFModuleOperating param)
+ => param.bits.GetByte();
+
+ public static implicit operator RFModuleOperating(Byte _byte)
+ => new RFModuleOperating(_byte.GetBits());
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/SirtOperating.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/SirtOperating.cs
new file mode 100644
index 00000000..93446ba5
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Parameters/SirtOperating.cs
@@ -0,0 +1,136 @@
+namespace Common.Hardware.Interfaces.Ports.SirtBroadcaster.Parameters
+{
+ using System;
+
+ public class SirtOperating
+ {
+ private readonly Byte[] bits;
+
+ public SirtOperating() => this.bits = new Byte[8];
+
+ private SirtOperating(Byte[] bits) => this.bits = bits;
+
+ ///
+ ///
+ /// -
+ /// true
+ /// Bluetooth is output for non-requested messages
+ ///
+ /// -
+ /// false
+ /// USB port is output for non-requested messages
+ ///
+ ///
+ /// non requested messages are received radio payloads if a radio module is switched on
+ ///
+ public Boolean DataBtOut
+ {
+ get => this.bits[0] == 1;
+ set => this.bits[0] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// : if both RF-Modules are set to SensusRF Mode, both payloads of RF-Modules will be send out
+ ///
+ /// -
+ /// false
+ /// if both RF-Modules are set to SensusRF Mode, the channel with higher RSSI Level will be send out
+ ///
+ ///
+ /// for test purposes both receiver outputs can be shown - but remember Double traffic rate on Bluetoothor USB-output
+ ///
+ public Boolean BothChsOut
+ {
+ get => this.bits[1] == 1;
+ set => this.bits[1] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// also payloads with incorrect radio-CRC will send out!
+ ///
+ /// -
+ /// false
+ /// normal operation
+ ///
+ ///
+ /// may be only interesting for test purposes
+ ///
+ public Boolean IgnoreCRC
+ {
+ get => this.bits[2] == 1;
+ set => this.bits[2] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// don't switch Power path off if going to USB Suspend and drawing more current as allowed
+ ///
+ /// -
+ /// false
+ /// switch Power path off if going to USB Suspend
+ ///
+ ///
+ /// New at Version 1.0.0.6
+ ///
+ public Boolean IgnoreUSBrules
+ {
+ get => this.bits[3] == 1;
+ set => this.bits[3] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// after "TIME_OFF" is elapsed without any command to SIRT, SIRT will be switched off
+ ///
+ /// -
+ /// false
+ /// normal operation
+ ///
+ ///
+ /// timeout starts at beginning, if any command or communication to and from SIRT is initiated
+ ///
+ public Boolean SirtPwrSave
+ {
+ get => this.bits[6] == 1;
+ set => this.bits[6] = (Byte)(value ? 1 : 0);
+ }
+
+ ///
+ ///
+ /// -
+ /// true
+ /// SIRT will be switched off {like push off button}
+ ///
+ /// -
+ /// false
+ /// normal operation
+ ///
+ ///
+ ///
+ /// SIRT can be switched off per command, but no answer will send if this bit was set.SIRT can not be switched
+ /// on per command only by pushing green button for a second
+ ///
+ ///
+ public Boolean SirtOff
+ {
+ get => this.bits[7] == 1;
+ set => this.bits[7] = (Byte)(value ? 1 : 0);
+ }
+
+ public static implicit operator Byte(SirtOperating param)
+ => param.bits.GetByte();
+
+ public static implicit operator SirtOperating(Byte _byte)
+ => new SirtOperating(_byte.GetBits());
+ }
+}
diff --git a/Common/Ui/Common.UI.WPFConnector/Properties/AssemblyInfo.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Properties/AssemblyInfo.cs
similarity index 85%
rename from Common/Ui/Common.UI.WPFConnector/Properties/AssemblyInfo.cs
rename to Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Properties/AssemblyInfo.cs
index ece2b4ee..b18a3667 100644
--- a/Common/Ui/Common.UI.WPFConnector/Properties/AssemblyInfo.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports.SirtBroadcaster/Properties/AssemblyInfo.cs
@@ -5,11 +5,11 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
-[assembly: AssemblyTitle("WPFConnector")]
+[assembly: AssemblyTitle("Common.Hardware.Interfaces.Ports.SirtBroadcaster")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("WPFConnector")]
+[assembly: AssemblyProduct("Common.Hardware.Interfaces.Ports.SirtBroadcaster")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@@ -20,7 +20,7 @@ using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("37e4bf89-44ae-4133-be0b-8355f791a79d")]
+[assembly: Guid("f408de9e-01e6-4cff-ae79-b572b0674fa2")]
// Version information for an assembly consists of the following four values:
//
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/Common.Hardware.Interfaces.Ports.csproj b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/Common.Hardware.Interfaces.Ports.csproj
index b94e8bae..d98df42c 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/Common.Hardware.Interfaces.Ports.csproj
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/Common.Hardware.Interfaces.Ports.csproj
@@ -42,6 +42,7 @@
+
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/JustSerialPort.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/JustSerialPort.cs
new file mode 100644
index 00000000..47254b14
--- /dev/null
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/JustSerialPort.cs
@@ -0,0 +1,135 @@
+namespace Common.Hardware.Interfaces.Ports
+{
+ using System;
+ using System.Collections.Concurrent;
+ using System.IO.Ports;
+
+ public class JustSerialPort
+ {
+ private static readonly ConcurrentDictionary serialPorts
+ = new ConcurrentDictionary();
+ private readonly SerialPortSettings serialPortSettings;
+ private readonly String portName;
+ private Int32 readBufferSize;
+ private Byte[] buffer;
+
+ public Boolean IsOpen
+ {
+ get => serialPorts.TryGetValue(this.portName, out var serialPort)
+ && serialPort.IsOpen;
+ }
+
+ public JustSerialPort(SerialPortSettings serialPortSettings)
+ {
+
+ this.serialPortSettings = serialPortSettings;
+ this.portName = this.serialPortSettings.PortName;
+ }
+
+ public event Action Logging;
+
+ public void Log(Object message)
+ => this.Logging?.Invoke($"{this.portName}|{message}");
+
+ public Boolean TryClose()
+ {
+ var closed = false;
+
+ try
+ {
+ if (serialPorts.TryRemove(this.portName, out var serialPort))
+ {
+ serialPort.Close();
+ serialPort = null;
+ closed = true;
+ }
+ }
+ catch (Exception e)
+ {
+ this.Log(e);
+ }
+
+ return closed;
+ }
+
+ public Boolean TryOpen()
+ {
+ var opened = false;
+
+ _ = this.TryClose();
+
+ try
+ {
+ var serialPort = new SerialPort
+ {
+ BaudRate = this.serialPortSettings.BaudRate,
+ DataBits = this.serialPortSettings.DataBits,
+ Parity = this.serialPortSettings.Parity,
+ PortName = this.serialPortSettings.PortName,
+ StopBits = this.serialPortSettings.StopBits,
+ WriteTimeout = 100,
+ ReadTimeout = 100,
+ };
+
+ if (serialPorts.TryAdd(this.portName, serialPort))
+ {
+ serialPort.Open();
+
+ this.readBufferSize = serialPort.ReadBufferSize;
+ this.buffer = new Byte[this.readBufferSize];
+ opened = serialPort.IsOpen;
+ }
+ }
+ catch (Exception e)
+ {
+ this.Log(e);
+ }
+
+ return opened;
+ }
+
+ public Byte[] ReadBytes()
+ {
+ var length = 0;
+ var bytes = new Byte[length];
+
+ if (serialPorts.TryGetValue(this.portName, out var serialPort))
+ {
+ if (serialPort.IsOpen && serialPort.BytesToRead > 0)
+ {
+ Array.Clear(this.buffer, 0, this.readBufferSize);
+
+ length = serialPort.Read(this.buffer, 0, this.readBufferSize);
+ bytes = new Byte[length];
+
+ Array.Copy(this.buffer, 0, bytes, 0, length);
+ }
+ }
+
+ return bytes;
+ }
+
+ public override String ToString()
+ => $"{this.serialPortSettings.PortName}, "
+ + $"{this.serialPortSettings.BaudRate}, "
+ + $"{this.serialPortSettings.DataBits}, "
+ + $"{this.serialPortSettings.Parity}, "
+ + $"{this.serialPortSettings.StopBits}";
+
+ public void WriteBytes(params Byte[] bytes)
+ {
+ if (bytes != null)
+ {
+ var bytesLength = bytes.Length;
+
+ if (bytes.Length > 0 && serialPorts.TryGetValue(this.portName, out var serialPort))
+ {
+ if (serialPort.IsOpen)
+ {
+ serialPort.Write(bytes, 0, bytes.Length);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/SerialPortBase.cs b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/SerialPortBase.cs
index 71143b4c..5da34d03 100644
--- a/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/SerialPortBase.cs
+++ b/Common/Hardware/Interfaces/Ports/Common.Hardware.Interfaces.Ports/SerialPortBase.cs
@@ -105,7 +105,7 @@
}
else
{
- this.LogMessage($"{this.PortName} cann't be addedd!");
+ this.LogMessage($"{this.PortName} can not be addedd!");
}
}
catch (Exception e)
@@ -116,16 +116,16 @@
public override String ToString()
=> serialPorts.TryGetValue(this.PortName, out var serialPort)
- ? $"{serialPort.PortName}, " +
- $"{serialPort.BaudRate}, " +
- $"{serialPort.DataBits}, " +
- $"{serialPort.Parity}, " +
- $"{serialPort.StopBits}"
- : $"{this.settings.PortName}, " +
- $"{this.settings.BaudRate}, " +
- $"{this.settings.DataBits}, " +
- $"{this.settings.Parity}, " +
- $"{this.settings.StopBits}";
+ ? $"{serialPort.PortName}, "
+ + $"{serialPort.BaudRate}, "
+ + $"{serialPort.DataBits}, "
+ + $"{serialPort.Parity}, "
+ + $"{serialPort.StopBits}"
+ : $"{this.settings.PortName}, "
+ + $"{this.settings.BaudRate}, "
+ + $"{this.settings.DataBits}, "
+ + $"{this.settings.Parity}, "
+ + $"{this.settings.StopBits}";
public virtual Byte[] Write(params Byte[] data)
{
diff --git a/Common/Hardware/WaterMeter/Genesis/GenesisCore/RegisterRestorer.cs b/Common/Hardware/WaterMeter/Genesis/GenesisCore/RegisterRestorer.cs
index 30583d81..b0e2ea9f 100644
--- a/Common/Hardware/WaterMeter/Genesis/GenesisCore/RegisterRestorer.cs
+++ b/Common/Hardware/WaterMeter/Genesis/GenesisCore/RegisterRestorer.cs
@@ -88,8 +88,10 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
///
private static readonly List _excludedFromCompareParameters = new List
{
- "SYSTEM_UpgradePermissions", // Once set to deviating from 0xFF it will maintain this after reboot,
- // it only can be overwritten temporary in RAM!
+ //THW 15-Aug-2024 reactivated "SYSTEM_UpgradePermissions",
+ //// Once set to deviating from 0xFF it will maintain this after reboot,
+ //// it only can be overwritten temporary in RAM!
+
"CUSTOMER_AlarmVisualMask", // Will be cyclically overwritten by SENSUSRADIO
"SENSUSRADIO_UpgFWVersion" // After a FW-Update the FW version has changed
};
diff --git a/Common/Hardware/WaterMeter/Genesis/GenesisStatus/GenesisStatusHandler.cs b/Common/Hardware/WaterMeter/Genesis/GenesisStatus/GenesisStatusHandler.cs
index 76190452..59227a53 100644
--- a/Common/Hardware/WaterMeter/Genesis/GenesisStatus/GenesisStatusHandler.cs
+++ b/Common/Hardware/WaterMeter/Genesis/GenesisStatus/GenesisStatusHandler.cs
@@ -41,9 +41,10 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus
}
GenesisStatus status;
+
try
{
- var url = ServiceUrls.GetProductionSkipAndLifeTimeInfoServiceUrl();
+ var url = ""; // ServiceUrls.GetProductionSkipAndLifeTimeInfoServiceUrl();
url += $"{pcbId}&orderNumber={orderNumber}";
var response = LocalWebRequest.GetRequest(url, 2000);
status = JsonConvert.DeserializeObject(response);
@@ -58,6 +59,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus
}
var type = typeof(GenesisStatus);
+
foreach (var prop in type.GetProperties())
{
try
@@ -86,6 +88,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus
public static Boolean BuildLifeTimeInformation(GenesisMeter currentGenesis, GenesisStatus status)
{
Boolean retVal;
+
if (currentGenesis == null || status == null) return false;
// read information from genesis
diff --git a/Common/Hardware/WaterMeter/MagFlux/DataPackages/DataPackages.csproj b/Common/Hardware/WaterMeter/MagFlux/DataPackages/DataPackages.csproj
index d6cac487..b1eddd98 100644
--- a/Common/Hardware/WaterMeter/MagFlux/DataPackages/DataPackages.csproj
+++ b/Common/Hardware/WaterMeter/MagFlux/DataPackages/DataPackages.csproj
@@ -212,9 +212,6 @@
MinimumRecommendedRules.ruleset
-
- Properties\SharedAssemblyInfo.cs
-
diff --git a/Common/Hardware/WaterMeter/MagFlux/DataPackages/DataTypes/Calibration.cs b/Common/Hardware/WaterMeter/MagFlux/DataPackages/DataTypes/Calibration.cs
index 7a982ea8..af42c27a 100644
--- a/Common/Hardware/WaterMeter/MagFlux/DataPackages/DataTypes/Calibration.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/DataPackages/DataTypes/Calibration.cs
@@ -1,7 +1,4 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
namespace Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.DataTypes
{
diff --git a/Common/Hardware/WaterMeter/MagFlux/DataPackages/MeasurementRecords/MagFluxRecord.cs b/Common/Hardware/WaterMeter/MagFlux/DataPackages/MeasurementRecords/MagFluxRecord.cs
index 575d0cff..0d8a3097 100644
--- a/Common/Hardware/WaterMeter/MagFlux/DataPackages/MeasurementRecords/MagFluxRecord.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/DataPackages/MeasurementRecords/MagFluxRecord.cs
@@ -14,17 +14,17 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.MeasurementRecor
///
/// Sensor Id of MagFlux
///
- public String SensorId;
+ public String SensorId { set; get; }
///
/// Serial number of MagFlux
///
- public String UniqueId;
+ public String UniqueId { set; get; }
///
/// Status of sensor and electronics
///
- public UInt32 StatusBits;
+ public UInt32 StatusBits { set; get; }
///
/// String delimiter to separate elements in ToString() routine
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Device/CalibrationPoint.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/CalibrationPoint.cs
similarity index 89%
rename from Common/modbus_master_csharp/src/modbus_master_csharp/Device/CalibrationPoint.cs
rename to Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/CalibrationPoint.cs
index 8048e942..3d3fcf63 100644
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Device/CalibrationPoint.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/CalibrationPoint.cs
@@ -1,7 +1,9 @@
-using System;
-using System.Xml;
+// Ignore Spelling: lps
-namespace XYLEM.Device
+using System;
+using XYLEM.Base;
+
+namespace XYLEM
{
///
/// A single calibration point
@@ -64,6 +66,19 @@ namespace XYLEM.Device
return this.CompareTo(other) == 0;
}
+ public override bool Equals(object obj)
+ {
+ if (!(obj is CalibrationPoint)) return false;
+
+ CalibrationPoint p = (CalibrationPoint)obj;
+ return this == p;
+ }
+
+ public override int GetHashCode()
+ {
+ return HashTools.ShiftAndWrap(ReferenceFlowRate_lps.GetHashCode(), 2) ^ ReportedFlowRate_lps.GetHashCode();
+ }
+
#region Operator == > < ! ..
public static bool operator ==(CalibrationPoint a, CalibrationPoint b)
{
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Device/CalibrationPoints.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/CalibrationPoints.cs
similarity index 89%
rename from Common/modbus_master_csharp/src/modbus_master_csharp/Device/CalibrationPoints.cs
rename to Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/CalibrationPoints.cs
index fa33eb6e..1fcffee1 100644
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Device/CalibrationPoints.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/CalibrationPoints.cs
@@ -1,12 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Xml;
+using XYLEM.Base;
using XYLEM.Base.XML;
-namespace XYLEM.Device
+namespace XYLEM
{
[Serializable]
public class CalibrationPoints : IComparable, IEquatable
@@ -143,6 +141,31 @@ namespace XYLEM.Device
return this.CompareTo(other) == 0;
}
+ public override bool Equals(object obj)
+ {
+ if (!(obj is CalibrationPoints)) return false;
+
+ CalibrationPoints p = (CalibrationPoints)obj;
+ return this == p;
+ }
+
+ public override int GetHashCode()
+ {
+ if (calibrations == null)
+ {
+ return base.GetHashCode();
+ }
+ else
+ {
+ int hash = 0;
+ foreach (var calibration in calibrations)
+ {
+ hash = HashTools.ShiftAndWrap(hash.GetHashCode(), 2) ^ calibration.GetHashCode();
+ }
+ return hash;
+ }
+ }
+
#region Operator == > < ! ..
public static bool operator ==(CalibrationPoints a, CalibrationPoints b)
{
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFlux.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFlux.cs
new file mode 100644
index 00000000..900a6477
--- /dev/null
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFlux.cs
@@ -0,0 +1,67 @@
+using System;
+using System.IO.Ports;
+using XYLEM.Base.Config;
+using XYLEM.Communication;
+
+namespace XYLEM
+{
+ ///
+ /// Command interface for MagFlux 6200
+ /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7112855120/Command+Interface+Draft
+ ///
+ internal interface IMagFlux : IMagFluxRequestProtocol
+ {
+ #region When sharing same serial port
+
+ ///
+ /// Connect when using same serial port
+ ///
+ ///
+ ///
+ ///
+ Boolean Connect(UInt16 id, ModbusCom md_com);
+
+ ///
+ /// Get current device com settings
+ ///
+ ///
+ SerialPortSettingClass GetComSetting();
+
+ ///
+ /// Current modbus device device ID / address
+ ///
+ UInt16 Device_ID { get; }
+
+ #endregion
+
+
+ #region For stand alone use without sharing same serial port
+
+ #endregion
+ ///
+ /// Make communication connection to Meter
+ /// !!NOTE!! Only one meter is supported for each com port
+ ///
+ /// Like "COM1"
+ /// >Device modbus address / ID 1..247 (default 1) Warning!! use 247 with single device connected, most MJK devices replay no matter it's id setting
+ /// true on okay or false on error
+ Boolean Connect(string comport, UInt16 id = 1);
+
+ ///
+ /// Make communication connection to Meter with a specific communication setup
+ /// !!NOTE!! Only one meter is supported for each com port
+ ///
+ /// >Like "COM1"
+ /// >Device modbus address / ID 1..247 (default 1) Warning!! use 247 with single device connected, most MJK devices replay no matter it's id setting
+ /// Like 9600 (default on RS485)
+ /// Like Parity.Even (default on RS485)
+ ///
+ Boolean Connect(string comport, UInt16 id, UInt32 baudRate, Parity parity);
+
+ ///
+ /// Close communication connection to Meter
+ ///
+ /// true on okay or false on error
+ Boolean CloseConnection();
+ }
+}
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFluxAPI.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFluxAPI.cs
new file mode 100644
index 00000000..b6c16d95
--- /dev/null
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFluxAPI.cs
@@ -0,0 +1,40 @@
+using System.IO.Ports;
+using XYLEM.Device;
+
+namespace XYLEM
+{
+ public interface IMagFluxAPI
+ {
+
+ ///
+ /// Make communication connection to Meter
+ ///
+ /// Imported note: Devices placed on same serial connection, must have same communication settings.
+ /// Ex. All devices on same serial connection must be configured to same baudrate, parity
+ ///
+ ///
+ /// Like "COM1"
+ /// Device modbus address / ID 1..247 (default 1) Warning!! use 247 with single device connected, most MJK devices replay no matter it's id setting
+ /// folder path for where to log file should be saved
+ /// RUN_TYPE.Normal with connection to serial port, if not set
+ /// Return a MagFlux device or "null" if failing connect
+ IMagFluxRequestProtocol Connect(string comport, ushort id = 1, string log_path = null, RUN_TYPE runAs = RUN_TYPE.Normal);
+
+ ///
+ /// Make communication connection to Meter with a specific communication setup
+ ///
+ /// Imported note: Devices placed on same serial connection, must have same communication settings.
+ /// Ex. All devices on serial connection must be configured to same baudrate, parity
+ ///
+ ///
+ /// >Like "COM1"
+ /// Device modbus address / ID 1..247 (default 1) Warning!! use 247 with single device connected, most MJK devices replay no matter it's id setting
+ /// Like 9600 (default on RS485)
+ /// Like Parity.Even (default on RS485)
+ /// folder path for where to log file should be saved
+ /// RUN_TYPE.Normal with connection to serial port, if not set
+ /// Return a MagFlux device or "null" if failing connect
+ /// if the configuration is not valid
+ IMagFluxRequestProtocol Connect(string comport, ushort id, uint baudRate, Parity parity, string log_path = null, RUN_TYPE runAs = RUN_TYPE.Normal);
+ }
+}
\ No newline at end of file
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFluxRequestProtocol.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFluxRequestProtocol.cs
new file mode 100644
index 00000000..0e48929e
--- /dev/null
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/IMagFluxRequestProtocol.cs
@@ -0,0 +1,374 @@
+using System;
+using System.Collections.Generic;
+using XYLEM.Base;
+
+namespace XYLEM
+{
+ ///
+ /// Command interface for MagFlux
+ /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7112855120/Command+Interface+Draft
+ ///
+ public interface IMagFluxRequestProtocol
+ {
+ ///
+ /// Is connected
+ ///
+ /// true if yes
+ Boolean IsConnected();
+
+ ///
+ /// Get current device Modbus ID / Device Address
+ ///
+ /// 1-246
+ /// true on okay or false on error
+ Boolean GetDeviceID(out int value_out);
+
+ ///
+ /// Simple Check if a device ID is Free or responding
+ /// Reads address 0 to check on any device response
+ /// Is used in SetDeviceID() before attempting change ID
+ ///
+ ///
+ /// Return True if no device was responding on ID
+ Boolean IsDeviceID_Free(uint id_to_check);
+
+ ///
+ /// Set current device Modbus ID / Device Address
+ ///
+ /// 1-246 (Don't use device ID 247, it is a MJK broad cast)
+ /// true on okay or false on error
+ /// Notes:
+ /// There is a simple check on new device id is free (read address 0 check on)
+ /// Change of device ID is instantly and may loose any communication if not able to function on this ID.
+ /// Troubleshooting on failing:
+ /// * Power off and remove optional USBC cable on MagFlux.
+ /// * Remove all other devices on RS485 and retry connection.
+ /// * Check Device ID manually on LCD other program like 840126 with USBC connection.
+ Boolean SetDeviceID(UInt16 new_id);
+
+ ///
+ /// Get printout of communication counters
+ ///
+ ///
+ string GetComCounters();
+
+ ///
+ /// Set location for where log data can saved.
+ ///
+ /// path for where to log file should be saved
+ /// set a custom log file name without extension (ex. "UserCustomLogFile") or null if use default
+ /// true on okay or false on error
+ Boolean SetLogLocation(String path, string filename = null);
+
+ ///
+ /// Open saved log file
+ ///
+ void OpenLogFile();
+
+ ///
+ /// Get latest log added to log file while this program was running
+ ///
+ /// How long to go back after log messages, if Null then standard 1 minute
+ /// "Lasted" Log messages Queue After last connection
+ List GetLatestLogs(DateTime? from = null);
+
+ ///
+ /// Unique-ID for the MagFlux electronics
+ ///
+ /// a hex decimal string 0x1234ABCDEF or NULL at error
+ /// true on okay or false on error
+ Boolean GetUniqueId(out string value_out);
+
+ ///
+ /// MagFlux metrology board serial number
+ /// More info on:
+ /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7648215086/Metrology+and+Application+serial+numbers
+ ///
+ /// a serial number ex. 510360.00000105W46Y23 or NULL at error
+ /// true on okay or false on error
+ Boolean GetBoardSerialNo(out string value_out);
+
+ ///
+ /// MagFlux metrology board serial number
+ /// More info on:
+ /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7648215086/Metrology+and+Application+serial+numbers
+ ///
+ /// a serial number ex. 510360.00000105W46Y23
+ /// true on okay or false on error
+ Boolean SetBoardSerialNo(string new_serial_number);
+
+ ///
+ /// Get the firmware version
+ ///
+ /// like 1.2.4 (MAJOR.MINOR.REVISION)
+ /// true on okay or false on error
+ Boolean GetFirmwareVersion(out string value_out);
+
+ ///
+ /// Get Current device register version
+ ///
+ /// like "51" or on connecting error "?", "0", "-1"
+ /// true on okay or false on error
+ Boolean GetRegisterVersion(out string value_out);
+
+ ///
+ /// Get Current communication register version used by the interface
+ ///
+ /// like "51" or on error "?", "0", "-1"
+ /// true on okay or false on error
+ Boolean GetAPIRegisterVersion(out string value_out);
+
+ ///
+ /// Get the firmware build date
+ ///
+ /// like 2022/12/24 13:00:00 or 2022-12-24 13:45:10
+ /// true on okay or false on error
+ Boolean GetFwBuildDate(out string value_out);
+
+ ///
+ /// Git Hash to Unique identify firmware
+ ///
+ /// like 0xABCDE123
+ /// true on okay or false on error
+ Boolean GetFwGitHash(out string value_out);
+
+
+ ///
+ /// Get Device runtime after Last reset
+ ///
+ /// Time since last device reset in seconds
+ ///
+ Boolean GetRuntimeAfterLastReset_sec(out UInt32 value_out);
+
+ ///
+ /// Flow rate calibrated
+ ///
+ /// Actual flow rate [l/s]
+ /// true on okay or false on error
+ Boolean GetFlowRate_lps(out Single value_out);
+
+ ///
+ /// !!! Warning make sure to turn off simulation, when calibration off sensor is done !!!
+ /// ----
+ /// Set a fixed test flow to force MagFlux, for check of digital output pulse etc.
+ /// ----
+ /// Will also activate and start fixed simulated flow in device
+ /// Used for getting a fixed simulated flow before sensor calibration from MagFlux
+ /// Note on limitation:
+ /// The actual resulting flow is depended on sensor calibration and MagFlux conversion from m/s to flow.
+ /// Always check resulting flow with GetFlowRate_lps() to verify if the same as expected
+ /// With a calibration of all 0 (equal no calibration 1:1) normally produce same GetFlowRate_lps() down to 3 digit precision.
+ ///
+ /// The fixed flow to force MagFlux to output [l/s]
+ /// true on okay or false on error
+ Boolean SetSimulatedFlow_lps(double value_lps);
+
+ ///
+ /// Get the correction factor from board "1.0000" is default none calibration board
+ ///
+ ///
+ /// true on okay or false on error
+ Boolean GetElectrodeBoardCorrectionFactor(out Single value_out);
+
+ ///
+ /// Get Empty pipe control bits
+ /// Bit0="EPD disabled", 1="Enabled w. Flags only", 2="EPD enabled full"
+ ///
+ /// empty pipe control bits
+ /// true on okay or false on error
+ Boolean GetEmptyPipeControl(out Int32 epd_cntl_bits);
+
+ ///
+ /// Ignore Empty pipe flag on Healthy, because it is not yet working correct
+ /// Note: Not 100% secure all test is working during empty pipe, metrology board firmware may not allow running during detection of empty pipe
+ ///
+ /// Default is currently True and will be set True on each connect (In the future when Empty pipe works it will be default false)
+ Boolean GetIgnoreFailOnEmptyPipeOnHealthy();
+
+
+ ///
+ /// Ignore Empty pipe flag on Healthy, because it is not yet working correct
+ /// Note: Not 100% secure all test is working during empty pipe, metrology board firmware may not allow running during detection of empty pipe
+ ///
+ /// True to ignore empty pipe warning
+ void SetIgnoreFailOnEmptyPipeOnHealthy(Boolean doIgnore);
+
+ ///
+ /// !!! Warning don't use this feature on already correct calibrated and configured boards !!!
+ /// Can only be used for demo and not for real sensor customer calibration measurement
+ /// ----
+ /// Set a uncalibrated blank board to defaults, that allow using it for testing
+ /// ----
+ /// Note:
+ /// Limitations will take up to a minute to exit, if all configs needs to be set in a blank device
+ /// * If "1.00" and device Healthy not, then rewrite "ElectrodeBoardCorrectionFactor" as "1.00" to remove PDS Invalid system calibration error
+ /// * If Sensor serial number is "0", it will be changed to "2"
+ /// * If Flange type is "0", It will be changed to "1" equal "EN-1092-1"
+ /// * If board PCB SN is blank "", then to "Demo [Date on change]"
+ /// * if Empty Pipe Control bits is all "0", then turn on "Enable w. flags only"
+ /// * Prepare with a default calibration that is 1:1
+ ///
+ /// true on okay or false on error
+ Boolean SetPCBToDemoDefaults();
+
+ ///
+ /// Is the fixed test flow active
+ /// Used for getting a fixed simulated flow from MagFlux
+ ///
+ /// true if ON
+ Boolean IsSimulatedFlowActive();
+
+ ///
+ /// Turn on/off fixed test flow output from MagFlux
+ /// Used for getting a fixed simulated flow from MagFlux
+ ///
+ ///
+ /// true on okay or false on error
+ Boolean SetSimulatedFlowActive(Boolean testFlowOn);
+
+ ///
+ /// Total forward volume (Positive flow volume totalizator)
+ ///
+ /// volume in in liter [l]
+ /// true on okay or false on error
+ Boolean GetForwardVolume_l(out Double value_out);
+
+ ///
+ /// Total backward volume (Reversed or negative flow volume totalizator)
+ ///
+ ///
+ /// true on okay or false on error
+ Boolean GetBackwardVolume_l(out Double value_out);
+
+ ///
+ /// Get the general sensor information
+ ///
+ /// sensor information
+ /// true on okay or false on error
+ Boolean GetSensorInfo(out SensorInfo value_out);
+
+ ///
+ /// MagFlux Sensor serial number
+ ///
+ /// a decimal serial number ex. 12345678 or NULL at error
+ /// true on okay or false on error
+ Boolean GetSensorSerialNo(out string value_out);
+
+ ///
+ /// Set MagFlux Sensor serial number
+ ///
+ ///
+ /// true on okay or false on error
+ Boolean SetSensorSerialNo(UInt64 new_serial_number);
+
+ ///
+ /// MagFlux Sensor nominal DN size in millimeters
+ ///
+ /// DN size in [mm] is -1 on error
+ /// true on okay or false on error
+ Boolean GetDn_mm(out Int32 dn_mm_out);
+
+ ///
+ /// Set Sensor nominal DN size in millimeters
+ ///
+ /// DN size in [mm] ex 50 is 50mm or DN50
+ /// true on okay or false on error
+ Boolean SetDn_mm(UInt16 new_dn_mm);
+
+ ///
+ /// Get Sensor Flange Type
+ /// 0 = Unknown, 1="EN-1092-1", 2=AS 4087-2004 or AS 2129-2000", 3="ANSI or ASME B16.5", 4="AWWA C207"
+ ///
+ /// Flange type number
+ /// true on okay or false on error
+ Boolean GetFlangeType(out Int32 flangeType_out);
+
+ ///
+ /// Set Sensor Flange Type
+ /// 0 = Unknown, 1="EN-1092-1", 2=AS 4087-2004 or AS 2129-2000", 3="ANSI or ASME B16.5", 4="AWWA C207"
+ ///
+ /// Flange type number
+ /// true on okay or false on error
+ Boolean SetFlangeType(UInt16 new_flangeType);
+
+ ///
+ /// get what volume per pulse for both forward and reverse counter is
+ /// Note: will return only forward pulse volume if both settings is not the same.
+ ///
+ /// A pulse volume in [ml] (milliliter)
+ /// true on okay or false on error
+ Boolean GetVolumePerPulse_ml(out UInt32 pls_vol_ml);
+
+ ///
+ /// Set what volume per pulse for both forward and reverse counter is
+ ///
+ /// A pulse volume in [ml] (milliliter)
+ /// true on okay or false on error
+ Boolean SetVolumePerPulse_ml(UInt32 pls_vol_ml);
+
+ ///
+ /// Get what pulse turn on time for both forward and reverse counter is
+ /// Note: will return only forward turn on time if both settings is not the same.
+ ///
+ /// A pulse turn on time in ms (millisecond) Note setting to 0 will result in pulse time be as fast as device support
+ /// true on okay or false on error
+ Boolean GetPulseOutput_Ton_ms(out UInt16 pls_Ton_ms);
+
+ ///
+ /// Set what pulse turn on time for both forward and reverse counter is
+ ///
+ /// A pulse turn on time in ms (millisecond)
+ /// true on okay or false on error
+ Boolean SetPulseOutput_Ton_ms(UInt16 pls_Ton_ms);
+
+ ///
+ /// Check if there is problem with the DUT
+ /// use " to get a list of error messages for debug problems
+ ///
+ /// >true if device operates correctly
+ Boolean GetDeviceHealthy();
+
+ ///
+ /// get a list of error messages for debug problem
+ ///
+ /// Will return a empty list if there is no messages to return
+ /// true on okay or false on error
+ Boolean GetDeviceErrorMessages(out List status_list_out);
+
+ ///
+ /// This function prepares the DUT for the calibration.
+ ///
+ /// ATTENTION:
+ /// This function needs to be called before the calibration process starts any flow of water.
+ ///
+ /// true on okay or false on error
+ Boolean PrepareDeviceForCalibration();
+
+ ///
+ /// This function will abort started or failed calibration to bring DUT back to normal calibration state
+ ///
+ /// true on okay or false on error
+ Boolean AbortDeviceForCalibration();
+
+ ///
+ /// The maximum calibration points that is supported by the device
+ ///
+ /// number of points possible to get and set in device
+ int GetCalibrationPointsMax();
+
+ ///
+ /// Get list of calibration points saved in DUT
+ ///
+ /// The calibrations points from device
+ /// true on okay or false on error
+ Boolean GetCalibrationPoints(out CalibrationPoints values_read);
+
+ ///
+ /// set calibration in DUT.
+ /// Remember to run before the calibration process is started.
+ ///
+ /// A list of calibration points to write to DUT
+ /// true on okay or false on error
+ Boolean SetCalibrationPoints(CalibrationPoints new_calibration_points);
+ }
+}
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/SensorInfo.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/SensorInfo.cs
new file mode 100644
index 00000000..7a8b4451
--- /dev/null
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/api_doc/SensorInfo.cs
@@ -0,0 +1,90 @@
+using System;
+
+namespace XYLEM
+{
+ public class SensorInfo
+ {
+ ///
+ ///Sensor serial number ex. 0x1234ABCDEF or 0 as unknown / not defined
+ ///
+ public UInt64 SerialNumber { get; private set; }
+
+ ///
+ /// MagFlux Sensor nominal DN size in millimeters
+ ///
+ public Int32 DN_mm { get; private set; }
+
+ ///
+ /// MagFlux Sensor Flange Type
+ /// 0 = Unknown, 1="EN-1092-1", 2=AS 4087-2004 or AS 2129-2000", 3="ANSI or ASME B16.5", 4="AWWA C207"
+ ///
+ public Int32 FlangeType { get; private set; }
+
+ ///
+ /// Calibration method was used. 0 is default, for calibration on flow rig for 5 min per point
+ ///
+ public Int32 CalibrationVersion { get; private set; }
+
+ ///
+ /// Sampling scheme code used by front end measurement. //NL// 0=32/40, 1=20/40
+ ///
+ public Int32 SamplingSchemeCode { get; private set; }
+
+ ///
+ /// Coil driver frequency, 0 = 0.625Hz, 1= 1.25Hz, 2 = 2.5Hz, 3 = 5Hz, 4 = 10Hz,
+ ///
+ public Int32 CoilDriverFrequencyConfig { get; private set; }
+
+ ///
+ /// Number of calibration points
+ /// The same as calling "Calibration.Get_number_of_calibrations()"
+ ///
+ public Int32 NumberOfCalibrations { get; private set; }
+
+ ///
+ /// List of calibration points saved in DUT
+ ///
+ public CalibrationPoints Calibration { get; private set; }
+
+
+ public SensorInfo(
+ UInt64 SerialNumber,
+ Int32 DN_mm,
+ Int32 FlangeType,
+ Int32 CalibrationVersion,
+ Int32 SamplingSchemeCode,
+ Int32 CoilDriverFrequencyConfig,
+ CalibrationPoints Calibration)
+ {
+ this.SerialNumber = SerialNumber;
+ this.DN_mm = DN_mm;
+ this.FlangeType = FlangeType;
+ this.CalibrationVersion = CalibrationVersion;
+ this.SamplingSchemeCode = SamplingSchemeCode;
+ this.CoilDriverFrequencyConfig = CoilDriverFrequencyConfig;
+ this.Calibration = Calibration;
+ if (null == this.Calibration)
+ {
+ this.NumberOfCalibrations = 0;
+ }
+ else
+ {
+ this.NumberOfCalibrations = this.Calibration.Get_number_of_calibrations();
+ }
+ }
+
+ public override String ToString()
+ {
+ String strReturn = "";
+ strReturn += $"SN: {SerialNumber}" + Environment.NewLine;
+ strReturn += $"DN{DN_mm} [mm]" + Environment.NewLine;
+ strReturn += $"Flange: {FlangeType}" + Environment.NewLine;
+ strReturn += $"Cal. Ver: {CalibrationVersion}" + Environment.NewLine;
+ strReturn += $"Sampling Scheme: {SamplingSchemeCode}" + Environment.NewLine;
+ strReturn += $"Coil Freq.: {CoilDriverFrequencyConfig}" + Environment.NewLine;
+ strReturn += $"Number of Cal.points: {NumberOfCalibrations}" + Environment.NewLine;
+ strReturn += $"Cal.points:" + Environment.NewLine + Calibration.ToString();
+ return strReturn;
+ }
+ }
+}
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/magflux_api.dll b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/magflux_api.dll
new file mode 100644
index 00000000..b60e13aa
Binary files /dev/null and b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/magflux_api.dll differ
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/shared_code.dll b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/shared_code.dll
new file mode 100644
index 00000000..61ae455b
Binary files /dev/null and b/Common/Hardware/WaterMeter/MagFlux/MagFluxApi/shared_code.dll differ
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/CommunicationConfig.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/CommunicationConfig.cs
index 11ae3929..2dd69031 100644
--- a/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/CommunicationConfig.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/CommunicationConfig.cs
@@ -1,4 +1,6 @@
using System;
+using Xylem.Common.Hardware.Interfaces.Ports.PortCore;
+using Xylem.Common.Hardware.Interfaces.Protocols.TransmitProtocol;
namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxConfig
{
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/MagFluxConfig.csproj b/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/MagFluxConfig.csproj
index f51296f0..7df7d4b8 100644
--- a/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/MagFluxConfig.csproj
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/MagFluxConfig.csproj
@@ -57,5 +57,15 @@
+
+
+ {2E139F63-B6FE-4EA9-A098-85364FE9B26C}
+ PortCore
+
+
+ {63E0AC5E-B7C8-4363-A2FE-BE489E648FF0}
+ TransmitProtocol
+
+
\ No newline at end of file
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/Properties/AssemblyInfo.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/Properties/AssemblyInfo.cs
index 04865a04..4c287db8 100644
--- a/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/Properties/AssemblyInfo.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/Properties/AssemblyInfo.cs
@@ -1,5 +1,4 @@
using System.Reflection;
-using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
@@ -10,7 +9,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xylem")]
[assembly: AssemblyProduct("MagFluxConfig")]
-[assembly: AssemblyCopyright("Copyright © Xylem 2023")]
+[assembly: AssemblyCopyright("Copyright © Xylem 2023..2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@@ -33,4 +32,3 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Consts/StateDef.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Consts/StateDef.cs
index 7ea856a0..63f8fda1 100644
--- a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Consts/StateDef.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Consts/StateDef.cs
@@ -38,7 +38,7 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore.Consts
new StateStruct(State.FlowOutOfRange, "Flow above calibrated region"),
new StateStruct(State.FlowNewStart, "Flow calculation new start"),
new StateStruct(State.TemperatureOutOfRange, "Temperature out of range"),
- new StateStruct(State.EmptyPipe, "Empty pipe detected"),
+ new StateStruct(State.EmptyPipe, "Empty Pipe Detected"),
new StateStruct(State.DisconnectedOrHwFault, "Disconnected or hardware fault")
};
}
@@ -74,7 +74,7 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore.Consts
public static List GetInfoOfAllErrorStates()
{
var errorStateInfos = (from state in _stateContainer where state.State
- != State.Okay select state.Info).ToList();
+ != State.Okay select state.Info).ToList();
return errorStateInfos;
}
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Consts/StateStruct.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Consts/StateStruct.cs
index 4bb8e795..8f9409b2 100644
--- a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Consts/StateStruct.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Consts/StateStruct.cs
@@ -5,7 +5,7 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore.Consts
///
/// Concatenation between final test state and text
///
- struct StateStruct
+ internal struct StateStruct
{
///
/// Assign state information tas text for state
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxMeter.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxMeter.cs
index c39d1be9..9eee69f4 100644
--- a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxMeter.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxMeter.cs
@@ -106,7 +106,42 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore
} = "?";
///
- /// Represent pcb serial number
+ /// Represent MagFlux API Version
+ ///
+ public String MagFluxRegisterApiVersion
+ {
+ get;
+ private set;
+ } = "?";
+
+
+ ///
+ /// Represent sensor serial number
+ ///
+ public String SensorSerialNo
+ {
+ get; private set;
+ }
+
+ ///
+ /// Represents Empty Pipe Detection control bits
+ /// Bit0="EPD disabled", 1="Enabled w. Flags only", 2="EPD enabled full"
+ ///
+ public Int32 EpdControlBits
+ {
+ get; private set;
+ }
+
+ ///
+ /// Represent pcb calibration
+ ///
+ public Single BoardCalib
+ {
+ get; private set;
+ }
+
+ ///
+ /// Represent pcb identification
///
public String PcbId
{
@@ -800,18 +835,33 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore
{
FwGitHash = gitHash;
}
+ if (RequestProtocol.GetApiRegisterVersion(out var apiRegisterVersion))
+ {
+ MagFluxRegisterApiVersion = apiRegisterVersion;
+ }
if (RequestProtocol.GetUniqueId(out var uniqueId))
{
UniqueId = uniqueId;
}
- // The PcbId will be named as SensorSerialNo by MJK
+ if (RequestProtocol.GetSensorSerialNo(out var sensorSerialNo))
+ {
+ SensorSerialNo = sensorSerialNo;
+ }
if (RequestProtocol.GetPcbId(out var pcbId))
{
PcbId = pcbId;
}
+ if (RequestProtocol.GetElectrodeBoardCorrectionFactor(out var boardCalib))
+ {
+ BoardCalib = boardCalib;
+ }
+ if (RequestProtocol.GetEmptyPipeControl(out var epd_cntl_bits))
+ {
+ EpdControlBits = epd_cntl_bits;
+ }
RequestProtocol?.GetCalibrationPoints(out _);
- StreamingProtocol?.SetDecodingMask(pcbId, uniqueId);
+ StreamingProtocol?.SetDecodingMask(SensorSerialNo, uniqueId);
return IsLoggedOn;
}
@@ -981,7 +1031,7 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore
}
}
}
- return ret.HasValue ? ret.Value : false;
+ return ret ?? false;
}
@@ -1017,6 +1067,42 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore
RequestProtocol?.CloseConnection();
}
+ /////
+ ///// Turn on/off fixed test flow output from MagFlux
+ ///// Used for getting a fixed simulated flow from MagFlux
+ /////
+ /////
+ ///// true on okay or false on error
+ //public Boolean SetSimulatedFlowActive(Boolean testFlowOn)
+ //{
+ // _logger.Info($"Slot:{Slot} - Set test flow");
+ // return RequestProtocol.SetSimulatedFlowActive(on);
+ //}
+
+ /////
+ ///// Is the fixed test flow active
+ ///// Used for getting a fixed simulated flow from MagFlux
+ /////
+ ///// true if ON
+ //public Boolean IsSimulatedFlowActive()
+ //{
+ // _logger.Info($"Slot:{Slot} - Get test flow setting");
+ // return RequestProtocol.IsSimulatedFlowActive();
+ //};
+
+ ///
+ /// Set PCB settings and PCB calibrations to default.
+ ///
+ public Boolean SetPCBToDemoDefaults()
+ {
+ _logger.Info($"Slot:{Slot} - Set PCB settings and PCB calibrations to default");
+ if (RequestProtocol == null)
+ return false;
+ var retVal = RequestProtocol.SetPCBToDemoDefaults();
+ RequestProtocol?.CloseConnection();
+ return retVal;
+ }
+
///
/// Set a new meter size to MagFlux
///
@@ -1031,14 +1117,14 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore
}
///
- /// Set a new pcbId to MagFlux
+ /// Set a new sensor serial number to MagFlux
///
- public Boolean SetPcbId(UInt32 pcbId)
+ public Boolean SetSensorSerialNo(UInt32 sensorSerialNo)
{
- _logger.Info($"Slot:{Slot} - Set meter PCB ID (Sensor serial no.)");
+ _logger.Info($"Slot:{Slot} - Set sensor serial no.");
if (RequestProtocol == null)
return false;
- var retVal = RequestProtocol.SetPcbId(pcbId);
+ var retVal = RequestProtocol.SetSensorSerialNo(sensorSerialNo);
RequestProtocol?.CloseConnection();
return retVal;
}
@@ -1086,7 +1172,7 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore
throw new NotImplementedException();
}
- ///
+ ///
public void SetLcdText(Boolean release, Byte[] textInHex)
{
throw new NotImplementedException();
diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Properties/AssemblyInfo.cs b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Properties/AssemblyInfo.cs
index 4155a811..ecda56d2 100644
--- a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Properties/AssemblyInfo.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/Properties/AssemblyInfo.cs
@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xylem")]
[assembly: AssemblyProduct("MagFluxCore")]
-[assembly: AssemblyCopyright("Copyright © Xylem 2023")]
+[assembly: AssemblyCopyright("Copyright © Xylem 2023..2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@@ -33,4 +33,3 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/Properties/AssemblyInfo.cs b/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/Properties/AssemblyInfo.cs
index d4f9d6ab..c23e017c 100644
--- a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/Properties/AssemblyInfo.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/Properties/AssemblyInfo.cs
@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xylem")]
[assembly: AssemblyProduct("")]
-[assembly: AssemblyCopyright("Copyright © Xylem 2023")]
+[assembly: AssemblyCopyright("Copyright © Xylem 2023..2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@@ -33,4 +33,3 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.cs b/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.cs
index 0bf07ae7..3c7562f7 100644
--- a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.cs
@@ -3,12 +3,12 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NLog;
+using XYLEM;
using Xylem.Common.Hardware.Interfaces.Ports.PortCore.EventArguments;
using Xylem.Common.Hardware.Interfaces.Protocols.ProtocolCore;
using Xylem.Common.Hardware.Interfaces.Protocols.ProtocolCore.EventArguments;
using Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.DataTypes;
using Xylem.Common.Utils.Logging;
-using XYLEM.Device;
namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
{
@@ -18,28 +18,37 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
public class RequestProtocol : BaseProtocol
{
private readonly String _ident;
- private readonly ILogger _logger;
+ private readonly ILogger _logger;
private IMagFluxRequestProtocol _magFluxRequestProtocol;
+ private IMagFluxAPI _magFluxApi;
// calibration point in cubic meters per hour
private List _calibPointsCmPerH;
///
+ ///
+ /// - MagFluxApi
+ ///
public RequestProtocol(String ident) : base(ident)
{
_ident = ident;
- _magFluxRequestProtocol = new MagFlux6200();
+ _magFluxApi = new MagFluxAPI();
_calibPointsCmPerH = new List();
- _logger = NLogHelper.CreateOrGetMultiLogger(_ident, "", "RequestProtocol", "MeterBase", "MeterBase");
+ _logger = NLogHelper.CreateOrGetMultiLogger(_ident, "", "RequestProtocol", "MeterBase",
+ "MeterBase");
}
/// >
+ ///
+ /// - MagFluxApi
+ ///
public override void Dispose()
{
_calibPointsCmPerH.Clear();
_calibPointsCmPerH = null;
- _magFluxRequestProtocol?.CloseConnection();
+ CloseConnection();
_magFluxRequestProtocol = null;
+ _magFluxApi = null;
base.Dispose();
}
@@ -54,21 +63,6 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
throw new NotImplementedException();
}
- ///
- /// Wrapper to connect MagFlux
- ///
- ///
- ///
- /// - Initial
- ///
- public Boolean IsConnected()
- {
- if (_magFluxRequestProtocol == null) return false;
- var retVal = _magFluxRequestProtocol.IsConnected();
- _logger.Debug(retVal ? $"{_ident} Connection established: true" : $"{_ident} Connection check request failed!");
- return retVal;
- }
-
///
/// Wrapper to connect MagFlux
///
@@ -77,13 +71,23 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
///
/// - Initial
///
+ ///
+ /// - MagFluxApi
+ ///
public Boolean Connect(String portName)
{
- if (_magFluxRequestProtocol == null) return false;
- var retVal = _magFluxRequestProtocol.Connect(portName);
- _logger.Debug(retVal ? $"{_ident} Connection established to {portName}" :
- $"{_ident} Connection to {portName} failed!");
+ if (_magFluxApi == null) return false;
+ _magFluxRequestProtocol = _magFluxApi.Connect(portName);
+ if (_magFluxRequestProtocol == null)
+ {
+ _logger.Debug($"{_ident} Connection to {portName} failed! Object reference returned null");
+ return false;
+ }
+
Thread.Sleep(100);
+ var retVal = _magFluxRequestProtocol.IsConnected();
+ _logger.Debug(retVal ? $"{_ident} Connection established to {portName}" :
+ $"{_ident} Connection to {portName} failed!");
return retVal;
}
@@ -106,7 +110,8 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
if (_magFluxRequestProtocol == null) return false;
var retVal = _magFluxRequestProtocol.SetLogLocation(path, fileName);
if (string.IsNullOrEmpty(fileName)) fileName = "?";
- _logger.Debug(retVal ? $"{_ident} Logging set to: {path}\\{fileName}" : $"{_ident} Logging path setup failed!");
+ _logger.Debug(retVal ? $"{_ident} Logging set to: {path}\\{fileName}" :
+ $"{_ident} Logging path setup failed!");
return retVal;
}
@@ -116,38 +121,177 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
}
///
- /// Wrapper to get the PcbId which equals the sensor serial number
+ /// Wrapper to set experimental boards to defaults regarding board serial number
+ /// and board calibration values
+ ///
+ ///
+ ///
+ /// - Initial
+ ///
+ public Boolean SetPCBToDemoDefaults()
+ {
+ if (_magFluxRequestProtocol == null) return false;
+ var retVal = _magFluxRequestProtocol.SetPCBToDemoDefaults();
+ _logger.Debug(retVal ? $"{_ident} Successfully set PCB settings and PCB calibrations to default" :
+ $"{_ident} PCB settings and PCB calibrations setup to default failed!");
+ return retVal;
+ }
+
+ /////
+ ///// Wrapper to get the simulated flow setting
+ /////
+ /////
+ /////
+ ///// - Initial
+ /////
+ //public Boolean GetSimulatedFlowOn()
+ //{
+ // if (_magFluxRequestProtocol == null) return false;
+ // var retVal = _magFluxRequestProtocol.IsSimulatedFlowActive();
+ // _logger.Debug(retVal ? $"{_ident} Simulated flow active read back returns: true" :
+ // $"{_ident} Read back simulated flow status failed!");
+ // return retVal;
+ //}
+
+ /////
+ ///// Wrapper to set the simulated flow setting
+ /////
+ ///// true to ignore state
+ /////
+ /////
+ ///// - Initial
+ /////
+ //public Boolean SetSimulatedFlowActive(Boolean on)
+ //{
+ // if (_magFluxRequestProtocol == null) return false;
+ // var retVal = _magFluxRequestProtocol.SetSimulatedFlowActive(on);
+ // _logger.Debug(retVal ? $"{_ident} Simulated flow active set to: {on}" :
+ // $"{_ident} Simulated flow active setup failed!");
+ // return retVal;
+ //}
+
+ /////
+ ///// Wrapper to get the ignore empty pipe mode status
+ /////
+ /////
+ /////
+ ///// - Initial
+ /////
+ //public Boolean GetIgnoreEmptyPipeStatus()
+ //{
+ // if (_magFluxRequestProtocol == null) return false;
+ // var retVal = _magFluxRequestProtocol.IgnoreFailOnEmptyPipeOnHealthy();
+ // _logger.Debug(retVal ? $"{_ident} Ignore empty pipe status read back returns: {retVal}" :
+ // $"{_ident} Read back empty pipe status failed!");
+ // return retVal;
+ //}
+
+ /////
+ ///// Wrapper to set the ignore empty pipe mode
+ /////
+ ///// true to ignore state
+ /////
+ /////
+ ///// - Initial
+ /////
+ //public Boolean SetIgnoreEmptyPipeStatus(Boolean on)
+ //{
+ // if (_magFluxRequestProtocol == null) return false;
+ // var retVal = _magFluxRequestProtocol.IgnoreFailOnEmptyPipeOnHealthy(on);
+ // _logger.Debug(retVal ? $"{_ident} Ignore empty pipe status adjusted to: {on}" :
+ // $"{_ident} Setup empty pipe status request failed!");
+ // return retVal;
+ //}
+
+ ///
+ /// Wrapper to get the empty pipe bits
+ ///
+ ///
+ ///
+ ///
+ /// - Initial
+ ///
+ public Boolean GetEmptyPipeControl(out Int32 epd_cntl_bits)
+ {
+ epd_cntl_bits = 0;
+ if (_magFluxRequestProtocol == null) return false;
+ var retVal = _magFluxRequestProtocol.GetEmptyPipeControl(out epd_cntl_bits);
+ _logger.Debug(retVal ? $"{_ident} Empty pipe control bits: 0x{epd_cntl_bits:X1}" :
+ $"{_ident} Empty pipe control bits request failed!");
+ return retVal;
+ }
+
+ ///
+ /// Wrapper to get the board calibration value
+ ///
+ ///
+ ///
+ ///
+ /// - Initial
+ ///
+ public Boolean GetElectrodeBoardCorrectionFactor(out Single value_out)
+ {
+ value_out = 0f;
+ if (_magFluxRequestProtocol == null) return false;
+ var retVal = _magFluxRequestProtocol.GetElectrodeBoardCorrectionFactor(out value_out);
+ _logger.Debug(retVal ? $"{_ident} Board calibration: {value_out:F4}" :
+ $"{_ident} SensorSerialNo request failed!");
+ return retVal;
+ }
+
+ ///
+ /// Wrapper to get the sensor serial number
+ ///
+ ///
+ ///
+ ///
+ /// - Initial
+ ///
+ public Boolean GetSensorSerialNo(out String sensorSerialNo)
+ {
+ sensorSerialNo = "?";
+ if (_magFluxRequestProtocol == null) return false;
+ var retVal = _magFluxRequestProtocol.GetSensorSerialNo(out sensorSerialNo);
+ _logger.Debug(retVal ? $"{_ident} SensorSerialNo: {sensorSerialNo}" :
+ $"{_ident} SensorSerialNo request failed!");
+ return retVal;
+ }
+
+ ///
+ /// Wrapper to get the PcbId
///
///
///
- ///
+ ///
/// - Initial
///
public Boolean GetPcbId(out String pcbId)
{
pcbId = "?";
if (_magFluxRequestProtocol == null) return false;
- var retVal = _magFluxRequestProtocol.GetSensorSerialNo(out pcbId);
- _logger.Debug(retVal ? $"{_ident} PcbId (SensorSerialNo): {pcbId}" :
- $"{_ident} PcbId (SensorSerialNo) request failed!");
+ var retVal = _magFluxRequestProtocol.GetBoardSerialNo(out pcbId);
+ _logger.Debug(retVal ? $"{_ident} PcbId: {pcbId}" :
+ $"{_ident} PcbId request failed!");
return retVal;
}
+
///
- /// Wrapper to set the PcbId which equals the sensor serial number
+ /// Wrapper to set the sensor serial number
///
- ///
+ ///
///
///
/// - Initial
///
- public Boolean SetPcbId(UInt32 pcbId)
+ public Boolean SetSensorSerialNo(UInt32 sensorSerialNo)
{
if (_magFluxRequestProtocol == null) return false;
- var retVal = _magFluxRequestProtocol.SetSensorSerialNo(pcbId);
- _logger.Debug(retVal ? $"{_ident} Set PcbId (SensorSerialNo): {pcbId}" :
- $"{_ident} Set PcbId (SensorSerialNo) request failed!");
+ var retVal = _magFluxRequestProtocol.SetSensorSerialNo(sensorSerialNo);
+ _logger.Debug(retVal ? $"{_ident} Set SensorSerialNo: {sensorSerialNo}" :
+ $"{_ident} Set SensorSerialNo request failed!");
return retVal;
}
+
///
/// Wrapper to get unique id referenced as PCBID
///
@@ -161,7 +305,8 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
pcbId = "?";
if (_magFluxRequestProtocol == null) return false;
var retVal = _magFluxRequestProtocol.GetUniqueId(out pcbId);
- _logger.Debug(retVal ? $"{_ident} UniqueId: {pcbId}" : $"{_ident} UniqueId request failed!");
+ _logger.Debug(retVal ? $"{_ident} UniqueId: {pcbId}" :
+ $"{_ident} UniqueId request failed!");
return retVal;
}
@@ -178,9 +323,11 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
fwVersion = "?";
if (_magFluxRequestProtocol == null) return false;
var retVal = _magFluxRequestProtocol.GetFirmwareVersion(out fwVersion);
- _logger.Debug(retVal ? $"{_ident} FW Version: {fwVersion}" : $"{_ident} FW Version request failed!");
+ _logger.Debug(retVal ? $"{_ident} FW Version: {fwVersion}" :
+ $"{_ident} FW Version request failed!");
return retVal;
}
+
///
/// Wrapper to get FW Build Date
///
@@ -194,7 +341,8 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
fwBuildDate = "?";
if (_magFluxRequestProtocol == null) return false;
var retVal = _magFluxRequestProtocol.GetFwBuildDate(out fwBuildDate);
- _logger.Debug(retVal ? $"{_ident} FW Build Date: {fwBuildDate}" : $"{_ident} FW Build Date request failed!");
+ _logger.Debug(retVal ? $"{_ident} FW Build Date: {fwBuildDate}" :
+ $"{_ident} FW Build Date request failed!");
return retVal;
}
@@ -211,7 +359,26 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
fwGitHash = "?";
if (_magFluxRequestProtocol == null) return false;
var retVal = _magFluxRequestProtocol.GetFwGitHash(out fwGitHash);
- _logger.Debug(retVal ? $"{_ident} FW GIT Hash: {fwGitHash}" : $"{_ident} FW GIT Hash request failed!");
+ _logger.Debug(retVal ? $"{_ident} FW GIT Hash: {fwGitHash}" :
+ $"{_ident} FW GIT Hash request failed!");
+ return retVal;
+ }
+
+ ///
+ /// Wrapper to get API register version of MagFlux
+ ///
+ ///
+ ///
+ ///
+ /// - Initial
+ ///
+ public Boolean GetApiRegisterVersion(out String apiRegisterVersion)
+ {
+ apiRegisterVersion = "?";
+ if (_magFluxRequestProtocol == null) return false;
+ var retVal = _magFluxRequestProtocol.GetAPIRegisterVersion(out apiRegisterVersion);
+ _logger.Debug(retVal ? $"{_ident} MagFlux API Register Version: {apiRegisterVersion}" :
+ $"{_ident} MagFlux API Register Version request failed!");
return retVal;
}
@@ -233,7 +400,8 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
meterSize = 0;
if (_magFluxRequestProtocol == null) return false;
var retVal = _magFluxRequestProtocol.GetDn_mm(out meterSize);
- _logger.Debug(retVal ? $"{_ident} MeterSize DN: {meterSize}" : $"{_ident} MeterSize request failed!");
+ _logger.Debug(retVal ? $"{_ident} MeterSize DN: {meterSize}" :
+ $"{_ident} MeterSize request failed!");
return retVal;
}
@@ -249,7 +417,8 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
{
if (_magFluxRequestProtocol == null) return false;
var retVal = _magFluxRequestProtocol.SetDn_mm(meterSize);
- _logger.Debug(retVal ? $"{_ident} Set MeterSize DN: {meterSize}" : $"{_ident} Set MeterSize failed!");
+ _logger.Debug(retVal ? $"{_ident} Set MeterSize DN: {meterSize}" :
+ $"{_ident} Set MeterSize failed!");
return retVal;
}
@@ -386,11 +555,18 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol
///
/// - Initial
///
+ ///
+ /// - Corrected logic, if !IsConnected = connection is closed
+ ///
public Boolean CloseConnection()
{
if (_magFluxRequestProtocol == null) return false;
- var retVal = _magFluxRequestProtocol.CloseConnection();
- _logger.Debug(retVal ? $"{_ident} Connection closed" : $"{_ident} Close connection request failed!");
+ MagFluxAPI.CloseAllConnections();
+
+ Thread.Sleep(100);
+ var retVal = _magFluxRequestProtocol.IsConnected();
+ _logger.Debug(!retVal ? $"{_ident} Connection is closed" :
+ $"{_ident} Close connection request failed!");
return retVal;
}
}
diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.csproj b/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.csproj
index 6255094c..53469aa6 100644
--- a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.csproj
+++ b/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.csproj
@@ -31,9 +31,15 @@
4
+
+ ..\..\MagFluxApi\magflux_api.dll
+
..\..\..\..\..\packages\NLog.5.2.2\lib\net46\NLog.dll
+
+ ..\..\MagFluxApi\shared_code.dll
+
@@ -53,10 +59,6 @@
-
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}
- modbus_master_csharp
-
{4B88B0D3-E791-4774-9521-EABEACDC420E}
Logging
diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/Properties/AssemblyInfo.cs b/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/Properties/AssemblyInfo.cs
index 41621a5d..066a6f1c 100644
--- a/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/Properties/AssemblyInfo.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/Properties/AssemblyInfo.cs
@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xylem")]
[assembly: AssemblyProduct("")]
-[assembly: AssemblyCopyright("Copyright © Xylem 2023")]
+[assembly: AssemblyCopyright("Copyright © Xylem 2023..2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@@ -33,4 +33,3 @@ using System.Runtime.InteropServices;
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingDecoder.cs b/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingDecoder.cs
index 23e054a8..05a8b9c3 100644
--- a/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingDecoder.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingDecoder.cs
@@ -50,7 +50,7 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol
private MagFluxRecord _dataMagFluxRec;
private readonly Boolean _ignoreCorruptedData;
- private String _pcbIdMask;
+ private String _sensorIdMask;
private String _uniqueIdMask;
///
@@ -72,19 +72,21 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol
///
/// Set decoding mask for streaming protocol, wipes out all not matching records:
- /// - PcbIdMask equals the sensor serial no
+ /// - SensorIdMask,
/// - UniqueIdMask
///
- ///
+ ///
///
/// true if decoding was successful and data has been validated
///
/// - Initial.
///
- public void SetDecodingMask(String pcbIdMask, String uniqueIdMask)
+ ///
+ /// - Changed from PcbId to SensorId.
+ ///
+ public void SetDecodingMask(String sensorIdMask, String uniqueIdMask)
{
- // the pcbId equals the sensorSn
- _pcbIdMask = pcbIdMask;
+ _sensorIdMask = sensorIdMask;
_uniqueIdMask = uniqueIdMask;
}
///
@@ -98,6 +100,9 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol
///
/// - Introduced reverse volume.
///
+ ///
+ /// - Changed from PcbId to SensorId.
+ ///
public Boolean DecodeMsg(String rawMsg)
{
var rawRecordIsValid = false;
@@ -146,11 +151,14 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol
switch (rawMsgFields[0])
{
case "@l":
+ //protocol @m starts with all contents of protocol @l and contains additional fields
+ //which needn't to be decoded as those are used for DEBUG
+ case "@m":
if (rawRecordIsValid || !_ignoreCorruptedData)
{
DecodeProtocolL(ref _dataMagFluxRec, rawMsgFields);
if (string.Equals(_uniqueIdMask, _dataMagFluxRec.UniqueId) &&
- string.Equals(_pcbIdMask, _dataMagFluxRec.SensorId))
+ string.Equals(_sensorIdMask, _dataMagFluxRec.SensorId))
{
DataMagFlux = _dataMagFluxRec;
_dataMagFluxRec.IsValid = rawRecordIsValid;
diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingProtocol.cs b/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingProtocol.cs
index cb15fbae..97bd1ef7 100644
--- a/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingProtocol.cs
+++ b/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingProtocol.cs
@@ -19,7 +19,7 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol
///
private StreamingDecoder _streamingDecode;
private readonly Boolean _ignoreCorruptedData;
- private String _pcbIdMask;
+ private String _sensorIdMask;
private String _uniqueIdMask;
///
@@ -30,16 +30,18 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol
/// - PcbIdMask equals the sensor serial no
/// - UniqueIdMask
///
- ///
+ ///
///
/// true if decoding was successful and data has been validated
///
/// - Initial.
///
- public void SetDecodingMask(String pcbIdMask, String uniqueIdMask)
+ ///
+ /// - Changed from PcbId to SensorId.
+ ///
+ public void SetDecodingMask(String sensorIdMask, String uniqueIdMask)
{
- // the pcbId equals the sensorSn
- _pcbIdMask = pcbIdMask;
+ _sensorIdMask = sensorIdMask;
_uniqueIdMask = uniqueIdMask;
}
///
@@ -49,7 +51,7 @@ namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol
//Data decoding
_streamingDecode = new StreamingDecoder(_ignoreCorruptedData);
- _streamingDecode.SetDecodingMask(_pcbIdMask, _uniqueIdMask);
+ _streamingDecode.SetDecodingMask(_sensorIdMask, _uniqueIdMask);
_streamingDecode.DecodeMsg(data);
//Event for new data
diff --git a/Common/Hardware/WaterMeter/OmniPlus/Common.Hardware.WaterMeter.OmniPlus.Features/SystemParameters.cs b/Common/Hardware/WaterMeter/OmniPlus/Common.Hardware.WaterMeter.OmniPlus.Features/SystemParameters.cs
index 06b7968c..d2d67b28 100644
--- a/Common/Hardware/WaterMeter/OmniPlus/Common.Hardware.WaterMeter.OmniPlus.Features/SystemParameters.cs
+++ b/Common/Hardware/WaterMeter/OmniPlus/Common.Hardware.WaterMeter.OmniPlus.Features/SystemParameters.cs
@@ -62,11 +62,29 @@
{
this.IsValid = true;
- var firmwareTokens = this.VersionAndType
- ?.Value
+ var versionAndType = this.VersionAndType?.Value;
+ var firmwareTokens = versionAndType
?.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
?? new string[2];
+ this.IsValid = firmwareTokens.Length == 3;
+
+ if (!this.IsValid)
+ {
+ this.ValidationMessage = $"Fehlender FW-Versionsparameter! - {versionAndType}";
+
+ return;
+ }
+
+ this.IsValid = firmwareTokens[2].CompareTo("R0.3.19") >= 0;
+
+ if (!this.IsValid)
+ {
+ this.ValidationMessage = $"FW-Version {firmwareTokens[2]} ist zu alt!";
+
+ return;
+ }
+
var versionString = string.Empty;
if (firmwareTokens?.Length > 0 && firmwareTokens[0]?.Length > 0)
@@ -78,7 +96,7 @@
if (!this.IsValid)
{
- this.ValidationMessage = $"{this.VersionAndType.Value} ist kleiner als 1.23";
+ this.ValidationMessage = $"{firmwareTokens[0]} ist kleiner als R1.23";
return;
}
@@ -105,17 +123,19 @@
if (!this.IsValid)
{
- if (3190 > volts)
+ var _volts = volts / 1000.0;
+
+ if (3.19 > _volts)
{
- this.ValidationMessage = $"Zu wenig baterie spannung: {volts / 1000.0}.";
+ this.ValidationMessage = $"Zu wenig baterie spannung: {_volts}.";
}
- else if (3750 < volts)
+ else if (3.75 < _volts)
{
- this.ValidationMessage = $"Zu fiel baterie spannung: {volts / 1000.0}.";
+ this.ValidationMessage = $"Zu fiel baterie spannung: {_volts}.";
}
else
{
- this.ValidationMessage = $"Die byterie spannung ist nicht in ordnung: {volts / 1000.0}.";
+ this.ValidationMessage = $"Die byterie spannung ist nicht in ordnung: {_volts}.";
}
return;
diff --git a/Common/Hardware/WaterMeter/WaterMeterCore/WaterMeterRegisters/obj/Debug/WaterMeterRegisters.csproj.CoreCompileInputs.cache b/Common/Hardware/WaterMeter/WaterMeterCore/WaterMeterRegisters/obj/Debug/WaterMeterRegisters.csproj.CoreCompileInputs.cache
index d110f5fc..8865d283 100644
--- a/Common/Hardware/WaterMeter/WaterMeterCore/WaterMeterRegisters/obj/Debug/WaterMeterRegisters.csproj.CoreCompileInputs.cache
+++ b/Common/Hardware/WaterMeter/WaterMeterCore/WaterMeterRegisters/obj/Debug/WaterMeterRegisters.csproj.CoreCompileInputs.cache
@@ -1 +1 @@
-c43c40a030005a8f189e6179faf40a6d42bfef5c
+89102b0142e574de38a9f47d370f3334e5e6c268
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/DebugCmd.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/DebugCmd.cs
index 9d8d6272..760d8d0e 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/DebugCmd.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/DebugCmd.cs
@@ -2,22 +2,13 @@
{
using System;
- public class DebugCmd
+ public class DebugCmd : Pam
{
- protected readonly Byte[] bytes;
-
- protected DebugCmd(Byte code)
- {
- this.bytes = new Byte[2];
- this.bytes[1] = code;
- }
-
- private DebugCmd(Byte[] bytes) => this.bytes = bytes;
+ protected DebugCmd(Byte code) : base(3, GetDebug)
+ => this.bytes[2] = code;
public static implicit operator Byte[] (DebugCmd cmd) => cmd.bytes;
- public static implicit operator DebugCmd(Byte[] bytes) => new DebugCmd(bytes);
-
///
/// Change from Production Mode to Shipment Mode. 1 = Shipment
///
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/OpticalTelegram.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/OpticalTelegram.cs
index b540b091..4e4138b6 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/OpticalTelegram.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/OpticalTelegram.cs
@@ -10,8 +10,8 @@
public Byte Minutes
{
- get => this.bytes[0];
- set => this.bytes[0] = value;
+ get => this.bytes[1];
+ set => this.bytes[1] = value;
}
}
}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/SetAlarms.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/SetAlarms.cs
index ca68323b..b850458d 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/SetAlarms.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/SetAlarms.cs
@@ -5,7 +5,5 @@
public SetAlarms() : base(2, DebugCmd.SetAlarms)
{
}
-
- public static implicit operator DebugCmd(SetAlarms alarms) => alarms.bytes;
}
}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/SetMetrologyParameters.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/SetMetrologyParameters.cs
index 36826b32..3c108db6 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/SetMetrologyParameters.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister.Features/SetMetrologyParameters.cs
@@ -6,12 +6,12 @@
public class SetMetrologyParameters : Pam
{
- private readonly Byte[] bitsFromByte11;
+ private Byte[] bitsFromByte11;
public SetMetrologyParameters() : base(18, MetrologyParameters)
=> this.bitsFromByte11 = new Byte[8];
- public Byte PamLength => (Byte)(this.bytes.Length - 1);
+ public Byte PamLength => this.bytes[1];
public Int32 Vpp
{
@@ -31,42 +31,54 @@
set => this.bytes[10] = value;
}
- public Single FactoryCalibration
+ public Byte FactoryCalibration
{
- get => this.bytes[11] / 10F;
- set => this.bytes[11] = (Byte)(value * 10);
+ get => this.bytes[11];
+ set => this.bytes[11] = value;
}
-
+
+ public Byte P11
+ {
+ get => this.bitsFromByte11.ToByte();
+ set => this.bitsFromByte11 = value.GetBits();
+ }
+
public MeterUnits Units
{
get
{
var bits = new Byte[8];
- bits[0] = this.bitsFromByte11[4];
- bits[1] = this.bitsFromByte11[3];
- bits[2] = this.bitsFromByte11[2];
- bits[3] = this.bitsFromByte11[1];
bits[4] = this.bitsFromByte11[0];
+ bits[3] = this.bitsFromByte11[1];
+ bits[2] = this.bitsFromByte11[2];
+ bits[1] = this.bitsFromByte11[3];
+ bits[0] = this.bitsFromByte11[4];
- return (MeterUnits)bits.ToByte(0, 5);
+ return (MeterUnits)bits.ToByte();
}
set
{
var bits = ((Byte)value).GetBits();
- this.bitsFromByte11[4] = bits[0];
- this.bitsFromByte11[3] = bits[1];
- this.bitsFromByte11[2] = bits[2];
- this.bitsFromByte11[1] = bits[3];
this.bitsFromByte11[0] = bits[4];
+ this.bitsFromByte11[1] = bits[3];
+ this.bitsFromByte11[2] = bits[2];
+ this.bitsFromByte11[3] = bits[1];
+ this.bitsFromByte11[4] = bits[0];
}
}
public DecimalPointLocations DecimalPoint
{
get => (DecimalPointLocations)this.bitsFromByte11[6];
- set => this.bitsFromByte11[6] = (Byte)value;
+ set
+ {
+ var x = (Byte)value;
+
+ this.bitsFromByte11[6] = (Byte)(x >> 5 & 1);
+ this.bitsFromByte11[5] = (Byte)(x >> 6 & 1);
+ }
}
///
@@ -88,20 +100,16 @@
set => this.bytes[13] = value;
}
- public UInt32 VppLED
+ public Int32 VppLED
{
- get => this.bytes.ToUInt32BigEndian(14);
+ get => this.bytes.ToInt32BigEndian(14);
set => value.ToBigEndianBytes().CopyTo(this.bytes, 14);
}
protected override Byte[] ToByteArray()
{
- var bytes11 = new Byte[8];
-
- Array.Copy(this.bitsFromByte11, 0, bytes11, 0, 8);
- Array.Reverse(bytes11);
-
- this.bytes[12] = bytes11.ToByte();
+ this.bytes[12] = this.bitsFromByte11.ToByte();
+ this.bytes[1] = 0x10;
return base.ToByteArray();
}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Common.Hardware.WaterMeter.eRegister.csproj b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Common.Hardware.WaterMeter.eRegister.csproj
index 814ebfee..56b20a09 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Common.Hardware.WaterMeter.eRegister.csproj
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Common.Hardware.WaterMeter.eRegister.csproj
@@ -50,31 +50,37 @@
+
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
-
+
{05F0CCAF-9F2B-45F9-A7F8-12F29AD182F3}
Common.Utils.Extensions
-
+
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}
+ Common.Hardware.Interfaces.Ports.SirtBroadcaster
+
+
{B23BFAF9-08AE-4311-8C08-FB2BB49EA2AD}
- Common.Hardware.Interfaces.Ports.SIRT
+ Common.Hardware.Interfaces.Ports.Sirt
{9AE071C0-DB12-4E09-A3C7-43F6DCD518D6}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ACKN.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/ACKN.cs
similarity index 90%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ACKN.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/ACKN.cs
index 31c7ade4..65ebc112 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ACKN.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/ACKN.cs
@@ -1,6 +1,6 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
+ using Common.Hardware.Interfaces.Ports.Sirt.Responses;
using System;
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/AppCode.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/AppCode.cs
similarity index 79%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/AppCode.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/AppCode.cs
index 70408be7..59afbf64 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/AppCode.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/AppCode.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
public enum AppCode
{
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/BUP.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/BUP.cs
similarity index 91%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/BUP.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/BUP.cs
index 9dd2f454..b0efd4a6 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/BUP.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/BUP.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
using Common.Hardware.WaterMeter.eRegister.Features;
using Common.Utils.Extensions;
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Debug.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/DEBUG.cs
similarity index 74%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Debug.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/DEBUG.cs
index 7efa45d6..4713762a 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Debug.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/DEBUG.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
using Common.Utils.Extensions;
@@ -12,14 +12,13 @@
this.DebugType = payload[index++];
this.MeterType = payload[index++];
- this.RadioFirmwareVersion = payload[index++].ToString();
- this.FirmwareVersion = payload[index++].ToString();
+ this.RadioFirmwareVersion = this.VersionString(payload[index++], payload[index++]);
this.MetrologyFirmwareVersion = this.VersionString(payload[index++], payload[index++]);
this.HardwareVersion = payload[index++].ToString();
this.FactoryState = payload[index++];
this.PCBID = payload.ToUInt32BigEndian((index += 4) - 4);
this.BoardTemperature = payload[index++];
- this.BatteryVoltage = payload.ToUInt16BigEndian((index += 2) - 2);
+ this.BatteryVoltage = 2 + payload.ToUInt16BigEndian((index += 2) - 2) / 64D;
this.WakeupInterval = payload[index++];
this.PowerLevelSensusRF = payload[index++];
this.PowerLevelFlexNet = payload[index++];
@@ -69,7 +68,10 @@
public Byte BoardTemperature { get; }
- public UInt16 BatteryVoltage { get; }
+ ///
+ /// Min: 3.565
+ ///
+ public Double BatteryVoltage { get; }
public Byte WakeupInterval { get; }
@@ -111,19 +113,37 @@
/// Bits 8-11 – Minor Version
/// Bits 0-7 – Patch Version
///
- private String VersionString(Byte param, Byte patch)
+ private String VersionString(Byte patch, Byte param)
{
- var bits = param.GetBits();
- var _major = new Byte[8];
- var _minor = new Byte[8];
+ var bits = param.GetBits().Reverse();
+ var type = bits[7] == 0 ? 'B' : 'R';
- Array.Copy(bits, 0, _major, 0, 4);
- Array.Copy(bits, 4, _minor, 0, 3);
-
- var major = _major.ToByte();
- var minor = _minor.ToByte();
+ var majorBits = new Byte[8];
+ majorBits[0] = bits[6];
+ majorBits[1] = bits[5];
+ majorBits[2] = bits[4];
- return $"{bits[7]}.{major}.{minor}.{patch}";
+ var major = 0;
+
+ for (var i = 0; i < 8; i++)
+ {
+ major |= majorBits[i] << i;
+ }
+
+ var minorBits = new Byte[8];
+ majorBits[0] = bits[3];
+ majorBits[1] = bits[2];
+ majorBits[2] = bits[1];
+ majorBits[3] = bits[0];
+
+ var minor = 0;
+
+ for (var i = 0; i < 8; i++)
+ {
+ minor |= minorBits[i] << i;
+ }
+
+ return $"{type}{major}.{minor}.{patch}";
}
}
}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Epoch20000101.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/Epoch20000101.cs
similarity index 95%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Epoch20000101.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/Epoch20000101.cs
index 0779bd95..323dc8fa 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Epoch20000101.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/Epoch20000101.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
using System;
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Lat.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/LAT.cs
similarity index 70%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Lat.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/LAT.cs
index 99212f42..f145565e 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Lat.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/LAT.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
using System;
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/MeterUnits.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/MeterUnits.cs
similarity index 61%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/MeterUnits.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/MeterUnits.cs
index b03594f8..c21fc1a7 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/MeterUnits.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/MeterUnits.cs
@@ -1,7 +1,8 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
public enum MeterUnits
{
+ NA = 0,
m3 = 19,
CF = 35,
GAL = 24,
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Payload.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/Payload.cs
similarity index 87%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Payload.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/Payload.cs
index 85d5232d..ea01852e 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Payload.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/Payload.cs
@@ -1,4 +1,4 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
using Common.Utils.Extensions;
@@ -6,7 +6,7 @@
public abstract class Payload
{
- private readonly String bytes;
+ protected readonly String bytes;
protected Payload(Byte[] payload)
{
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/SEMI.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/SEMI.cs
similarity index 94%
rename from Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/SEMI.cs
rename to Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/SEMI.cs
index 3f1ea888..367cd60f 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/SEMI.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Data/SEMI.cs
@@ -1,5 +1,6 @@
-namespace Common.Hardware.WaterMeter.eRegister
+namespace Common.Hardware.WaterMeter.eRegister.Data
{
+ using Common.Hardware.Interfaces.Ports.SirtBroadcaster;
using Common.Utils.Extensions;
using System;
@@ -12,7 +13,7 @@
var index = 11;
this.PAMStatus = new PAMStatus(payload[index++]);
- this.RSSI = this.CalculateRSSI(payload[index++], mhz);
+ this.RSSI = CalculateRSSI(payload[index++], mhz);
this.MeterType = payload[index++];
this.TransmissionInterval = payload.ToUInt16BigEndian((index += 2) - 2);
this.LATInterval = payload[index++];
@@ -26,7 +27,7 @@
this.AlarmActiveInformation = payload[index++];
this.LeakageDetectionParameters = payload[index++];
this.BrokenPipeDetectionParameters = payload[index++];
- this.BatteryRemaining = payload.ToUInt16BigEndian((index += 2) - 2);
+ this.BatteryRemaining = payload.ToUInt16BigEndian((index += 2) - 2) / (4D * 365);
this.BatteryEndDetected = payload.ToUInt16BigEndian((index += 2) - 2);
this.MaximumFlow = payload.ToUInt16BigEndian((index += 2) - 2);
this.TimeOfMaximumFlow = payload.ToUInt16BigEndian((index += 2) - 2);
@@ -98,7 +99,7 @@
public Byte BrokenPipeDetectionParameters { get; }
- public UInt16 BatteryRemaining { get; }
+ public Double BatteryRemaining { get; }
public UInt16 BatteryEndDetected { get; }
@@ -148,7 +149,7 @@
public Byte MeterSize { get; }
- private String CalculateRSSI(Byte value, UInt16 mhz)
+ public static String CalculateRSSI(Byte value, UInt16 mhz)
{
var dbm = 0D;
var per = 0D;
@@ -177,7 +178,7 @@
per = 0;
}
- return $"{dbm:0.00}dBm ({per:0.00}%)";
+ return $"{dbm:0}dBm ({per:0.0}%)";
}
}
}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Endpoint.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Endpoint.cs
deleted file mode 100644
index 0a9d44cb..00000000
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/Endpoint.cs
+++ /dev/null
@@ -1,289 +0,0 @@
-namespace Common.Hardware.WaterMeter.eRegister
-{
- using Common.Hardware.Interfaces.Ports.SIRT;
- using Common.Hardware.WaterMeter.eRegister.Features;
-
- using NLog;
-
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- public class Endpoint
- {
- private readonly ILogger logger;
- private readonly Queue commands;
-
- private Int32 remeiningTasks;
- private EndpointTask checksTask;
-
- public Endpoint(ILogger logger)
- {
- this.logger = logger;
- this.commands = new Queue();
- }
-
- public event Action Done;
-
- public Int32 Slot { get; internal set; }
-
- public UInt32 Address { get; set; }
-
- public UInt32 FinalAddress { get; set; }
-
- public Int32 SerialNo { get; set; }
-
- public String HexKey { get; set; }
-
- public DEBUG DEBUG { get; private set; }
-
- public SEMI SEMI { get; private set; }
-
- public LAT LAT { get; private set; }
-
- public void AddHexCommand(String command)
- {
- if (String.IsNullOrWhiteSpace(command))
- {
- return;
- }
-
- command = command
- .Replace("0x", "")
- .Replace("h", "")
- .Replace(";", "")
- .Replace(",", "")
- .Replace("-", "")
- .Replace(" ", "")
- .Trim();
-
- if (command.Length % 2 != 0)
- {
- return;
- }
-
- Boolean TryParse(Char _char, out Int32 _byte)
- {
- _byte = 0;
-
- if ('0' <= _char && _char <= '9')
- {
- _byte = _char - '0';
- }
- else if ('A' <= _char && _char <= 'F')
- {
- _byte = 16 - ('F' - _char) - 1;
- }
- else
- {
- return false;
- }
-
- return true;
- }
-
- var length = command.Length;
- var bytes = new Byte[length / 2];
-
- for (Int32 c = 0, b = 0; c < length; c += 2, b++)
- {
- if (TryParse(command[c], out var b1) && TryParse(command[c + 1], out var b2))
- {
- bytes[b] = (Byte)(b1 * 16 + b2);
- }
- else
- {
- this.logger.Error($"Invalid hex char: {command}");
-
- bytes = null;
-
- break;
- }
- }
-
- if (bytes != null)
- {
- this.commands.Enqueue(bytes);
- }
- }
-
- public EndpointTask InitForInspection()
- {
- this.remeiningTasks++;
-
- var task = new EndpointTask
- {
- Address = this.Address,
- WakeUpCmd = true,
- DelPamSemi = true,
- Payload = new ChangeWakeUp
- {
- Mode = WakeUpMode.StayAwake
- }
- .Append(new ChangeLATWindows
- {
- N = 0
- })
- .Append(new WMBusMode
- {
- WMBusEnabled = true,
- InstallationModeEnabled = true,
- EncryptionEnabled = true,
- })
- .Append(new ChangeTransmission
- {
- LatWindowIntervalCount = 0,
- LatTXIntervalSeconds = 3
- })
- .Append(new ProvidePin
- {
- AuthLevel = AuthLevel.II
- })
- };
- task.Done += this.Task_Done;
- task.TRXLogging += this.Task_TRXLogging;
-
- return task;
- }
-
- internal EndpointTask RunCommand()
- {
- if (this.commands.Count > 0)
- {
- this.remeiningTasks++;
-
- var task = new EndpointTask
- {
- Address = this.Address,
- WakeUpCmd = true,
- DelPamSemi = true,
- Payload = this.commands.Dequeue()
- };
- task.Done += this.Task_Done;
- task.TRXLogging += this.Task_TRXLogging;
-
- return task;
- }
-
- return null;
- }
-
- public EndpointTask SetupForInspection()
- {
- this.remeiningTasks++;
-
- var task = new EndpointTask
- {
- Address = this.Address,
- WakeUpCmd = true,
- DelPamSemi = true,
- Payload = new SetMetrologyParameters
- {
- DecimalPoint = DecimalPointLocations.Three,
- FactoryCalibration = 0,
- MeterSize = 37,
- OffsetFactor = 0,
- OffsetTime = 5,
- Units = Features.MeterUnits.CubicMeters,
- UseCandIRules = true,
- Vpp = 40960000,
- VppLED = 218843648
- }
- .Append(new ProvidePin
- {
- AuthLevel = AuthLevel.III
- })
- };
- task.Done += this.Task_Done;
- task.TRXLogging += this.Task_TRXLogging;
-
- return task;
- }
-
- public EndpointTask SetDisplay111111111()
- {
- this.remeiningTasks++;
-
- var task = new EndpointTask
- {
- Address = this.Address,
- WakeUpCmd = true,
- DelPamSemi = true,
- Payload = new ChangeMeterReading
- {
- Value = 111_111_111
- }
- .Append(new ProvidePin
- {
- AuthLevel = AuthLevel.III
- })
- };
- task.Done += this.Task_Done;
- task.TRXLogging += this.Task_TRXLogging;
-
- return task;
- }
-
- public EndpointTask StartLED()
- {
- this.remeiningTasks++;
-
- var task = new EndpointTask
- {
- Address = this.Address,
- WakeUpCmd = true,
- DelPamSemi = true,
- Payload = new GetDebug
- {
- Cmd = new OpticalTelegram
- {
- Minutes = 1,
- }
- }
- .Append(new ProvidePin
- {
- AuthLevel = AuthLevel.III
- })
- };
- task.Done += this.Task_Done;
- task.TRXLogging += this.Task_TRXLogging;
-
- return task;
- }
-
- public EndpointTask DoChecks()
- {
- this.checksTask = new EndpointTask();
-
- return this.checksTask;
- }
-
- private void Task_TRXLogging(Byte[] bytes) => this.logger?.Debug($"{this.Slot}|{BitConverter.ToString(bytes)}");
-
- private void Task_Done(SIRTTask task)
- {
- this.remeiningTasks--;
-
- if (this.remeiningTasks <= 0)
- {
- if (this.checksTask != null && task is EndpointTask endpointTask)
- {
- this.LAT = endpointTask.LATS.LastOrDefault();
- this.DEBUG = endpointTask.DEBUGS.LastOrDefault();
- this.SEMI = endpointTask.SEMIS.LastOrDefault();
-
- var batteryVoltage = 2 + (this.DEBUG?.BatteryVoltage ?? 1) / 64F >= 3.565;
- var batteryRemaining = 2 + (this.SEMI?.BatteryRemaining ?? 54669) <= 54668;
- var rebootCount = (this.DEBUG?.RebootCount ?? Byte.MaxValue) <= 2;
-
- if (batteryVoltage && batteryRemaining && rebootCount)
- {
- this.checksTask.NotifyCompleted();
- }
- }
-
- this.Done?.Invoke(0);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/EndpointTask.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/EndpointTask.cs
deleted file mode 100644
index 169370f5..00000000
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/EndpointTask.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-namespace Common.Hardware.WaterMeter.eRegister
-{
- using Common.Hardware.Interfaces.Ports.SIRT;
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
- using Common.Utils.Extensions;
-
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- public class EndpointTask : WritePamTask
- {
- private Byte[] key;
-
- public EndpointTask() : base(5)
- {
- this.Done += _ => this.NotifyCompleted();
- base.Cancelled += _ => this.NotifyCancelled();
- }
-
- public event Action Completed;
- public new event Action Cancelled;
- public event Action Received;
-
- public override UInt32 Address => base.Address;
-
- public String KEY
- {
- get => BitConverter.ToString(this.key);
- set => this.key = value.GetBytes();
- }
-
- public ICollection ACKNS { get; private set; } = new List();
-
- public ICollection LATS { get; private set; } = new List();
-
- public ICollection DEBUGS { get; private set; } = new List();
-
- public ICollection SEMIS { get; } = new List();
-
- public ICollection BUPS { get; } = new List();
-
- public String FirstPamId => $"PAM {this.request.Payload.FirstOrDefault()}";
-
- protected override Boolean FromAirReceived(FromAirResponse response)
- {
- var payload = response.Payload;
- var length = response.Payload.Length;
- var succeeded = false;
-
- if (length == 13)
- {
- var bup = new LAT(payload);
-
- if (bup.AppCode == AppCode.LAT)
- {
- this.LATS.Add(bup);
-
- if (this.request.Payload[0] == 0x35)
- {
- var oldAddress = this.Address;
- var newAddress = this.request.Payload.ToUInt32BigEndian(1);
-
- if (oldAddress != newAddress)
- {
- this.NotifyAddressChanged(oldAddress, newAddress);
- }
- }
-
- this.Received?.Invoke($"LAT({this.LATS.Count})");
- }
- else
- {
- this.BUPS.Add(bup);
-
- this.Received?.Invoke($"BUP({this.BUPS.Count})");
- }
- }
- else if (length == 52)
- {
- this.DEBUGS.Add(new DEBUG(payload));
-
- this.Received?.Invoke($"DEBUG({this.DEBUGS.Count})");
- }
- else if (length == 91)
- {
- this.SEMIS.Add(new SEMI(payload, response.MHz));
-
- this.Received?.Invoke($"SEMI({this.SEMIS.Count})");
-
- succeeded = true;
- }
- else
- {
- // TODO: unrecognized response received.!?
- }
-
- this.NotifyTRX(response);
-
- /// If SEMI received, task is done
- return succeeded;
- }
-
- protected override Boolean AcknOrAnswerReceived(AcknOrAnswerResponse response)
- {
- this.ACKNS.Add(new ACKN(response));
-
- this.Received?.Invoke($"LAT({this.ACKNS.Count})");
- this.NotifyTRX(response);
-
- return base.AcknOrAnswerReceived(response);
- }
-
- protected override Byte[] GetRequestBytes()
- {
- var bytes = base.GetRequestBytes();
-
- this.NotifyTRX(bytes);
-
- return bytes;
- }
-
- internal void NotifyCompleted() => this.Completed?.Invoke();
-
- internal new void NotifyCancelled() => this.Cancelled?.Invoke();
- }
-}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/JustTask.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/JustTask.cs
new file mode 100644
index 00000000..acf8a493
--- /dev/null
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/JustTask.cs
@@ -0,0 +1,33 @@
+namespace Common.Hardware.WaterMeter.eRegister
+{
+ using System;
+ using System.Linq;
+
+ public class JustTask
+ {
+ public event Action OnProgress;
+
+ public Int32 Slotno { get; internal set; }
+
+ public Int32 Rowno { get; internal set; }
+
+ public String Label { get; protected set; }
+
+ public TaskState State { get; protected set; } = TaskState.None;
+
+ public Func> TaskHandler { get; internal set; }
+
+ public Action ProgressHandler
+ {
+ get => (Action)this.OnProgress?.GetInvocationList()?.FirstOrDefault();
+ set => this.OnProgress += value;
+ }
+
+ public void Execute(ParameterSet parameterSet)
+ {
+ var result = this.TaskHandler?.Invoke(parameterSet);
+
+ this.OnProgress?.Invoke(this.Slotno, this.Rowno, result.Item1, result.Item2);
+ }
+ }
+}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/PAMStatus.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/PAMStatus.cs
deleted file mode 100644
index 63cd01fe..00000000
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/PAMStatus.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace Common.Hardware.WaterMeter.eRegister
-{
- using Common.Utils.Extensions;
-
- using System;
-
- public class PAMStatus
- {
- private readonly Byte[] bits;
-
- public PAMStatus(Byte _byte)
- => this.bits = _byte.GetBits();
-
- public Boolean CMD_UNKNOWN => this.bits[0] == 1;
-
- public Boolean WRONG_AUTH => this.bits[1] == 1;
-
- public Boolean EXPIRED_AUTH => this.bits[2] == 1;
-
- public Boolean MIXED_TYPES => this.bits[3] == 1;
-
- public Boolean OUT_OF_RANGE => this.bits[4] == 1;
- }
-}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ParameterSet.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ParameterSet.cs
new file mode 100644
index 00000000..bdaa0ca6
--- /dev/null
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ParameterSet.cs
@@ -0,0 +1,113 @@
+namespace Common.Hardware.WaterMeter.eRegister
+{
+ using Common.Hardware.Interfaces.Ports.Sirt;
+ using Common.Hardware.Interfaces.Ports.Sirt.Parameters;
+ using Common.Hardware.WaterMeter.eRegister.Features;
+ using Common.Utils.Extensions;
+
+ using System;
+
+ public class ParameterSet
+ {
+ public Int32 SharedId { get; set; }
+
+ public Int32 Psno { get; set; }
+
+ public Int32 Slotno { get; set; }
+
+ public Int32 Serialno { get; set; }
+
+ public Boolean IsSealed { get; set; }
+
+ public Byte[] RadioKey { get; set; }
+
+ public UInt32 RadioAddress { get; set; }
+
+ public UInt32 FinalAddress { get; set; }
+
+ public Byte[] Parameters { get; set; }
+
+ internal ProgrammingTask BuildWupTxLatMBusTask()
+ => new ProgrammingTask
+ {
+ Cmd = JustSirtMessage.W_PAM,
+ P1 = new P811
+ {
+ DelPamSemi = true,
+ WakeUpCmd = true
+ },
+ Address = this.RadioAddress,
+ Data = new Byte[] // Multipam commands
+ {
+ 0x00, 0x00, // WUP stay awake
+ 0x02, 0x00, // LAT window interval
+ 0x05, 0x07, // MBus status
+ 0x10, 0x00, 0x03, // TX interval
+ 0x43, 0x02, 0x14, 0x0E, 0x80, 0x40, // Pin level II
+ },
+ EncryptionKey = this.IsSealed ? this.RadioKey : null
+ };
+
+ internal ProgrammingTask BuildTestParametersTask()
+ => new ProgrammingTask
+ {
+ Cmd = JustSirtMessage.W_PAM,
+ P1 = new P811
+ {
+ DelPamSemi = true
+ },
+ Address = this.RadioAddress,
+ Data = new SetMetrologyParameters
+ {
+ Vpp = this.Parameters.Int32BigEndian(3),
+ OffsetFactor = this.Parameters.Int32BigEndian(7),
+ OffsetTime = this.Parameters.Byte(11),
+ FactoryCalibration = this.Parameters.Byte(12),
+ P11 = this.Parameters.Byte(13),
+ MeterSize = this.Parameters.Byte(14),
+ VppLED = this.Parameters.Int32BigEndian(15),
+ }
+ .Append(new ProvidePin
+ {
+ AuthLevel = Features.AuthLevel.III
+ }),
+ EncryptionKey = this.IsSealed ? this.RadioKey : null
+ };
+
+ internal ProgrammingTask BuildSetupDisplayTask()
+ => new ProgrammingTask
+ {
+ Cmd = JustSirtMessage.W_PAM,
+ P1 = new P811
+ {
+ DelPamSemi = true
+ },
+ Address = this.RadioAddress,
+ Data = new Byte[]
+ {
+ 0x30, 0x06, 0x9F, 0x6B, 0xC7, // Display: 111111111
+ 0x43, 0x03, 0x63, 0x93, 0x73, 0x22 // Pin level III
+ },
+ EncryptionKey = this.IsSealed ? this.RadioKey : null
+ };
+
+ internal ProgrammingTask BuildOptoOnTask()
+ => new ProgrammingTask
+ {
+ Cmd = JustSirtMessage.W_PAM,
+ P1 = new P811
+ {
+ DelPamSemi = true
+ },
+ Address = this.RadioAddress,
+ Data = new OpticalTelegram
+ {
+ Minutes = 1 // TODO: Get opto value
+ }.Append(new ProvidePin
+ {
+ AuthLevel = Features.AuthLevel.III
+ }),
+ EncryptionKey = this.IsSealed ? this.RadioKey : null
+ };
+ }
+}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ProgrammingBatch.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ProgrammingBatch.cs
index 4189e653..b211e86c 100644
--- a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ProgrammingBatch.cs
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ProgrammingBatch.cs
@@ -1,7 +1,6 @@
namespace Common.Hardware.WaterMeter.eRegister
{
- using Common.Hardware.Interfaces.Ports;
- using Common.Hardware.Interfaces.Ports.SIRT;
+ using Common.Hardware.Interfaces.Ports.SirtBroadcaster;
using NLog;
using NLog.Config;
@@ -9,126 +8,436 @@
using System;
using System.Collections.Generic;
- using System.Linq;
using System.Threading;
public class ProgrammingBatch
{
- private readonly ILogger logger;
- private readonly SIRTBroadcaster broadcaster;
- private readonly IDictionary endpoints;
+ private readonly Dictionary programmingParameters
+ = new Dictionary();
+ private readonly Dictionary> programmingTasks
+ = new Dictionary>();
+ private readonly Dictionary> eregisterTasks
+ = new Dictionary>();
+ private readonly Dictionary> completedTasks
+ = new Dictionary>();
+ private readonly ILogger logger = CreateNLogger("SIRT");
+ private JustSirtBroadcaster broadcaster;
+ private Int32 rssiRow;
- private Int32 tasksDone;
+ public event Action OnProgress;
- public ProgrammingBatch(String portName, Int32 rwTimeout = 3000)
+ public void AddOrReplace(ParameterSet parameterSet)
+ => this.programmingParameters[parameterSet.Slotno] = parameterSet;
+
+ public void InitializeCalibration()
{
- this.logger = CreateNLogger("SIRT");
- this.endpoints = new Dictionary();
- this.broadcaster = new SIRTBroadcaster(new SerialPortSettings
+ this.programmingTasks.Clear();
+ this.eregisterTasks.Clear();
+
+ this.OnProgress?.Invoke(0, 0, $"Einbauplatz", TaskState.Disabled);
+
+ for (var x = 1; x < 11; x++)
{
- BaudRate = SerialPortBaudRate.X115200,
- DataBits = SerialPortDataBits.X8,
- Parity = SerialPortParity.None,
- PortName = portName,
- StopBits = SerialPortStopBits.One,
- RWTimeout = rwTimeout
+ this.OnProgress?.Invoke(x, 0, $"{x}", TaskState.Disabled);
+ }
+
+ var rowno = 1;
+
+ this.OnProgress?.Invoke(0, rowno++, $"Seriennr", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Radio Adresse", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Finale Adresse", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"RSSI", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"WUP-TX-LAT-MBus", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Parametersatz", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Anzeige-111111111", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Opto ein", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"MBus status = 7", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Batteriespannung (Volts)", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Batterielaufzeit (Jahre)", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"FW Version", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Reboots <= 2", TaskState.Disabled);
+
+ foreach (var kvp in this.programmingParameters)
+ {
+ var slotno = kvp.Key;
+ var parameterSet = kvp.Value;
+
+ rowno = 1;
+
+ this.OnProgress?.Invoke(slotno, rowno++, $"{parameterSet.Serialno}", TaskState.Disabled);
+ this.OnProgress?.Invoke(slotno, rowno++, $"{parameterSet.RadioAddress}", TaskState.Disabled);
+ this.OnProgress?.Invoke(slotno, rowno++, $"{parameterSet.FinalAddress}", TaskState.Disabled);
+ this.OnProgress?.Invoke(slotno, rowno++, $"0dBm (0%)", TaskState.Disabled);
+ this.rssiRow = rowno - 1;
+
+ if (!this.programmingTasks.ContainsKey(slotno))
+ {
+ this.programmingTasks[slotno] = new Queue();
+ }
+
+ var tasks = this.programmingTasks[slotno];
+
+ var task1 = parameterSet.BuildWupTxLatMBusTask();
+ task1.OnProgress += this.Task_OnProgress;
+ task1.Slotno = slotno;
+ task1.Rowno = rowno++;
+ tasks.Enqueue(task1);
+
+ var task2 = parameterSet.BuildTestParametersTask();
+ task2.OnProgress += this.Task_OnProgress;
+ task2.Slotno = slotno;
+ task2.Rowno = rowno++;
+ tasks.Enqueue(task2);
+
+ var task3 = parameterSet.BuildSetupDisplayTask();
+ task3.OnProgress += this.Task_OnProgress;
+ task3.Slotno = slotno;
+ task3.Rowno = rowno++;
+ tasks.Enqueue(task3);
+
+ var task4 = parameterSet.BuildOptoOnTask();
+ task4.OnProgress += this.Task_OnProgress;
+ task4.Slotno = slotno;
+ task4.Rowno = rowno++;
+ tasks.Enqueue(task4);
+
+ if (!this.eregisterTasks.ContainsKey(slotno))
+ {
+ this.eregisterTasks[slotno] = new Queue();
+ }
+
+ var etasks = this.eregisterTasks[slotno];
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckMBusStatus,
+ ProgressHandler = this.Task_OnProgress
+ });
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckBatteryVoltage,
+ ProgressHandler = this.Task_OnProgress
+ });
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckBatteryRemaining,
+ ProgressHandler = this.Task_OnProgress
+ });
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckRadioFWVersion,
+ ProgressHandler = this.Task_OnProgress
+ });
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckReboots,
+ ProgressHandler = this.Task_OnProgress
+ });
+ }
+ }
+
+ public void InitializeCalibration(Int32 slotno)
+ {
+ var parameterSet = this.programmingParameters[slotno];
+ var rowno = 1;
+
+ this.OnProgress?.Invoke(0, rowno++, $"Seriennr", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Radio Adresse", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Finale Adresse", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"WUP-TX-LAT-MBus", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Parametersatz", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Anzeige-111111111", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Opto ein", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"MBus status = 7", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Batteriespannung (Volts)", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Batterielaufzeit (Jahre)", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"FW Version", TaskState.Disabled);
+ this.OnProgress?.Invoke(0, rowno++, $"Reboots <= 2", TaskState.Disabled);
+
+ rowno = 1;
+
+ this.OnProgress?.Invoke(slotno, rowno++, $"{parameterSet.Serialno}", TaskState.Disabled);
+ this.OnProgress?.Invoke(slotno, rowno++, $"{parameterSet.RadioAddress}", TaskState.Disabled);
+ this.OnProgress?.Invoke(slotno, rowno++, $"{parameterSet.FinalAddress}", TaskState.Disabled);
+
+ this.programmingTasks[slotno] = new Queue();
+ var tasks = this.programmingTasks[slotno];
+
+ var task1 = parameterSet.BuildWupTxLatMBusTask();
+ task1.OnProgress += this.Task_OnProgress;
+ task1.Slotno = slotno;
+ task1.Rowno = rowno++;
+ tasks.Enqueue(task1);
+
+ var task2 = parameterSet.BuildTestParametersTask();
+ task2.OnProgress += this.Task_OnProgress;
+ task2.Slotno = slotno;
+ task2.Rowno = rowno++;
+ tasks.Enqueue(task2);
+
+ var task3 = parameterSet.BuildSetupDisplayTask();
+ task3.OnProgress += this.Task_OnProgress;
+ task3.Slotno = slotno;
+ task3.Rowno = rowno++;
+ tasks.Enqueue(task3);
+
+ var task4 = parameterSet.BuildOptoOnTask();
+ task4.OnProgress += this.Task_OnProgress;
+ task4.Slotno = slotno;
+ task4.Rowno = rowno++;
+ tasks.Enqueue(task4);
+
+ this.eregisterTasks[slotno] = new Queue();
+ var etasks = this.eregisterTasks[slotno];
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckMBusStatus,
+ ProgressHandler = this.Task_OnProgress
+ });
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckBatteryVoltage,
+ ProgressHandler = this.Task_OnProgress
+ });
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckBatteryRemaining,
+ ProgressHandler = this.Task_OnProgress
+ });
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckRadioFWVersion,
+ ProgressHandler = this.Task_OnProgress
+ });
+
+ etasks.Enqueue(new JustTask
+ {
+ Slotno = slotno,
+ Rowno = rowno++,
+ TaskHandler = task4.CheckReboots,
+ ProgressHandler = this.Task_OnProgress
});
}
- public event Action Done;
-
- public event Action Activated
+ public void Run()
{
- add => this.broadcaster.Activated += value;
- remove => this.broadcaster.Activated -= value;
- }
+ var tasks = default(List);
+ var allDone = true;
- public void Add(Int32 slotno, Int32 serialno, UInt32 address)
- {
- this.endpoints[slotno] = new Endpoint(this.logger)
- {
- Slot = slotno,
- SerialNo = serialno,
- Address = address
- };
- this.endpoints[slotno].Done += this.Endpoint_Done;
- }
-
- public void AddHexCommand(Int32 slotno, String command)
- {
- if (this.endpoints.ContainsKey(slotno))
- {
- this.endpoints[slotno].AddHexCommand(command);
- }
- }
-
- public void ActivateSIRT() => this.broadcaster.Open();
-
- public void DeactivateSIRT() => this.broadcaster.Close();
-
- public IEnumerable Slots() => this.endpoints.Values.Select(x => x.Slot);
-
- public IEnumerable SerialNumbers() => this.endpoints.Values.Select(x => x.SerialNo);
-
- public IEnumerable RadioAddresses() => this.endpoints.Values.Select(x => x.Address);
-
- public IEnumerable InitForInspection() => this.endpoints.Values.Select(x => this.Run(x.InitForInspection));
-
- public IEnumerable SetupForInspection() => this.endpoints.Values.Select(x => this.Run(x.SetupForInspection));
-
- public IEnumerable SetDisplay111111111() => this.endpoints.Values.Select(x => this.Run(x.SetDisplay111111111));
-
- public IEnumerable StartLED() => this.endpoints.Values.Select(x => this.Run(x.StartLED));
-
- public IEnumerable DoChecks() => this.endpoints.Values.Select(x => x.DoChecks());
-
- public IEnumerable> RunCommands()
- {
do
{
- var commands = this.endpoints.Values.Select(x => x.RunCommand()).ToArray();
+ tasks = new List();
- foreach (var command in commands)
+ foreach (var queue in this.programmingTasks.Values)
{
- if (command != null)
+ if (queue.Count > 0)
{
- this.Run(() => command);
+ tasks.Add(queue.Dequeue());
}
}
- if (commands.Any(x => x is null))
+ do
{
- break;
- }
- else
+ allDone = true;
+
+ foreach (var task in tasks)
+ {
+ if (task.TaskStatus != JustTaskStatus.Completed)
+ {
+ this.broadcaster.TryRun(task);
+
+ Thread.Sleep(100);
+
+ allDone = false;
+ }
+ }
+
+ Thread.Sleep(100);
+
+ } while (!allDone);
+
+ foreach (var task in tasks)
{
- yield return commands;
+ var slotno = task.Slotno;
+
+ if (!this.completedTasks.ContainsKey(slotno))
+ {
+ this.completedTasks[slotno] = new Queue();
+ }
+
+ this.completedTasks[slotno].Enqueue(task);
}
- } while (true);
- }
+ } while (tasks.Count > 0);
- private EndpointTask Run(Func taskHandler)
- {
- var task = taskHandler();
-
- this.broadcaster.Add(task);
-
- return task;
- }
-
- private void Endpoint_Done(Int32 remainingTasks)
- {
- this.tasksDone++;
-
- Thread.Sleep(1000);
-
- if (this.tasksDone == this.endpoints.Count)
+ foreach (var kvp in this.completedTasks)
{
- this.Done?.Invoke(0);
+ foreach (var task in kvp.Value)
+ {
+ task.Refresh();
+ }
+ }
+
+ var countTasks = this.eregisterTasks[1].Count;
+
+ for (var c = 0; c < countTasks; c++)
+ {
+ foreach (var kvp in this.eregisterTasks)
+ {
+ var slotno = kvp.Key;
+ var parameterSet = this.programmingParameters[slotno];
+ var eregisterTask = kvp.Value.Dequeue();
+
+ eregisterTask.Execute(parameterSet);
+ kvp.Value.Enqueue(eregisterTask);
+ }
}
}
+ public void Run(Int32 slotno)
+ {
+ this.completedTasks[slotno] = new Queue();
+
+ var queue = this.programmingTasks[slotno];
+ var awaiter = new ManualResetEventSlim();
+
+ while (queue.Count > 0)
+ {
+ var task = queue.Dequeue();
+
+ while (true)
+ {
+ if (this.broadcaster.TryRun(task) == JustTaskStatus.Sent)
+ {
+ task.Cancelled += _ => awaiter.Set();
+ task.Completed += _ => awaiter.Set();
+
+ awaiter.Wait();
+ awaiter.Reset();
+ }
+
+ if (task.TaskStatus == JustTaskStatus.Completed)
+ {
+ break;
+ }
+
+ Thread.Sleep(100);
+ }
+
+ this.completedTasks[slotno].Enqueue(task);
+ }
+
+ foreach (var kvp in this.completedTasks)
+ {
+ foreach (var task in kvp.Value)
+ {
+ task.Refresh();
+ }
+ }
+
+ var countTasks = this.eregisterTasks[1].Count;
+ var eregisterTasks = this.eregisterTasks[slotno];
+ var eregisterTasksCount = eregisterTasks.Count;
+ var parameterSet = this.programmingParameters[slotno];
+
+ for (var row = 0; row < eregisterTasksCount; row++)
+ {
+ var eregisterTask = eregisterTasks.Dequeue();
+
+ eregisterTask.Execute(parameterSet);
+ eregisterTasks.Enqueue(eregisterTask);
+ }
+ }
+
+ public void Run(ProgrammingTask task)
+ {
+ var status = this.broadcaster.TryRun(task);
+ var awaiter = new ManualResetEventSlim();
+
+ while (status != JustTaskStatus.Sent)
+ {
+ awaiter.Wait(1000);
+ awaiter.Reset();
+
+ status = this.broadcaster.TryRun(task);
+ }
+ }
+
+ public Boolean StartOnCOMPort(String portName)
+ {
+ var activated = false;
+
+ for (var i = 0; i < 10; i++)
+ {
+ this.Stop();
+
+ this.broadcaster = new JustSirtBroadcaster(portName);
+ this.broadcaster.Logging += this.logger.Debug;
+
+ if (this.broadcaster.TryActivate())
+ {
+ activated = true;
+
+ break;
+ }
+
+ Thread.Sleep(1000);
+ }
+
+ return activated;
+ }
+
+ public void Stop()
+ {
+ if (this.broadcaster != null)
+ {
+ this.broadcaster.TryDeactivate();
+ this.programmingParameters.Clear();
+ this.programmingTasks.Clear();
+
+ this.broadcaster = null;
+ }
+ }
+
+ private void Task_OnProgress(ProgrammingTask task)
+ {
+ this.OnProgress?.Invoke(task.Slotno, task.Rowno, task.Label, task.State);
+
+ if (!String.IsNullOrWhiteSpace(task.RSSI))
+ {
+ this.OnProgress?.Invoke(task.Slotno, this.rssiRow, task.RSSI, TaskState.Disabled);
+ }
+ }
+
+ private void Task_OnProgress(Int32 slot, Int32 rowno, String label, TaskState state)
+ => this.OnProgress?.Invoke(slot, rowno, label, state);
+
private static ILogger CreateNLogger(string name)
{
LogManager.Configuration = new LoggingConfiguration();
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ProgrammingTask.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ProgrammingTask.cs
new file mode 100644
index 00000000..55d0266b
--- /dev/null
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/ProgrammingTask.cs
@@ -0,0 +1,326 @@
+namespace Common.Hardware.WaterMeter.eRegister
+{
+ using Common.Hardware.Interfaces.Ports.Sirt;
+ using Common.Hardware.Interfaces.Ports.Sirt.Parameters;
+ using Common.Hardware.Interfaces.Ports.SirtBroadcaster;
+ using Common.Hardware.WaterMeter.eRegister.Data;
+
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+
+ public class ProgrammingTask : JustSirtTask
+ {
+ private const String PENDING = nameof(PENDING);
+
+ private readonly ICollection lats = new List();
+ private readonly ICollection bups = new List();
+ private readonly ICollection debugs = new List();
+ private readonly ICollection semis = new List();
+
+ public event Action OnProgress;
+
+ public Byte[] EncryptionKey { get; set; }
+
+ public Int32 Slotno { get; internal set; }
+
+ public Int32 Rowno { get; internal set; }
+
+ public String Label { get; private set; }
+
+ public String RSSI { get; private set; }
+
+ public TaskState State { get; private set; } = TaskState.None;
+
+ public override void PrepareForRun()
+ {
+ this.OnProgress?.Invoke(this);
+
+ base.PrepareForRun();
+ }
+
+ public override void ReceiveMessage(JustSirtMessage response, Int32 mhz)
+ {
+ if (this.EncryptionKey != null && this.EncryptionKey.Length == 16)
+ {
+ this.DecryptResponse(response);
+ }
+
+ if (this.State != TaskState.Success && response.Cmd == JustSirtMessage.FROMAIR)
+ {
+ var label = this.Label;
+ var state = this.State;
+ var data = response.Data;
+ var type = data[0];
+
+ if (type == JustSirtMessage.SEMI)
+ {
+ var semi = new SEMI(data, (UInt16)mhz);
+ label = semi.PAMStatus.ToString();
+
+ if (semi.PAMStatus == PAMStatus.OK)
+ {
+ state = TaskState.Success;
+ this.TaskStatus = JustTaskStatus.Completed;
+ }
+ else
+ {
+ state = TaskState.Error;
+ this.TaskStatus = JustTaskStatus.Cancelled;
+ }
+
+ this.semis.Add(semi);
+ }
+ else if (type == JustSirtMessage.BUP)
+ {
+ label = nameof(JustSirtMessage.BUP);
+ state = TaskState.Warning;
+
+ this.bups.Add(new BUP(data));
+ }
+ else if (type == JustSirtMessage.LAT)
+ {
+ label = nameof(JustSirtMessage.LAT);
+ state = TaskState.Warning;
+
+ this.lats.Add(new LAT(data));
+ }
+ else if (type == JustSirtMessage.DEBUG)
+ {
+ label = nameof(JustSirtMessage.DEBUG);
+ state = TaskState.Warning;
+
+ this.debugs.Add(new DEBUG(data));
+ }
+
+ this.Label = label;
+ this.State = state;
+ this.RSSI = SEMI.CalculateRSSI(response.P2, (UInt16)mhz);
+ }
+
+ this.OnProgress?.Invoke(this);
+ base.ReceiveMessage(response, mhz);
+ }
+
+ public override Byte[] ToByteArray()
+ {
+ if (this.EncryptionKey != null && this.EncryptionKey.Length == 16)
+ {
+ this.EncryptRequest();
+ }
+
+ return base.ToByteArray();
+ }
+
+ internal void Refresh()
+ {
+ var semi = this.semis.LastOrDefault();
+
+ if (semi != null)
+ {
+ this.Label = semi.PAMStatus.ToString();
+
+ if (semi.PAMStatus == PAMStatus.OK)
+ {
+ this.State = TaskState.Success;
+ }
+ else
+ {
+ this.State = TaskState.Error;
+ }
+ }
+ else if (this.LastPayload != null)
+ {
+ var last = new JustSirtMessage(this.LastPayload);
+ P11 p11 = last.P1;
+
+ if (p11.LenOverflow)
+ {
+ this.Label = "LEN OVERFLOW";
+ this.State = TaskState.Error;
+ }
+ else if (!p11.SrcChannel && p11.InvalidMod1)
+ {
+ this.Label = "MOD 1 CRC ERROR";
+ this.State = TaskState.Error;
+ }
+ else if (p11.SrcChannel && p11.InvalidMod2)
+ {
+ this.Label = "MOD 2 CRC ERROR";
+ this.State = TaskState.Error;
+ }
+ else
+ {
+ this.Label = nameof(PAMStatus.OK);
+ this.State = TaskState.Success;
+ }
+ }
+ else
+ {
+ this.Label = "NA";
+ this.State = TaskState.Error;
+ }
+
+ this.OnProgress?.Invoke(this);
+ }
+
+ internal Tuple CheckMBusStatus(ParameterSet parameterSet)
+ {
+ var label = $"{this.semis.LastOrDefault()?.MBusStatus} OK";
+
+ return new Tuple(label, TaskState.Success);
+ }
+
+ internal Tuple CheckBatteryVoltage(ParameterSet parameterSet)
+ {
+ var label = $"{this.debugs.LastOrDefault()?.BatteryVoltage:0.00} OK";
+
+ return new Tuple(label, TaskState.Success);
+ }
+
+ internal Tuple CheckBatteryRemaining(ParameterSet parameterSet)
+ {
+ var label = $"{this.semis.LastOrDefault()?.BatteryRemaining:0.0} OK";
+
+ return new Tuple(label, TaskState.Success);
+ }
+
+ internal Tuple CheckRadioFWVersion(ParameterSet parameterSet)
+ {
+ var label = $"{this.debugs.LastOrDefault()?.RadioFirmwareVersion} OK";
+
+ return new Tuple(label, TaskState.Success);
+ }
+
+ internal Tuple CheckMetrologyFWVersion(ParameterSet arg)
+ {
+ var label = $"{this.debugs.LastOrDefault()?.MetrologyFirmwareVersion} OK";
+
+ return new Tuple(label, TaskState.Success);
+ }
+
+ internal Tuple CheckReboots(ParameterSet parameterSet)
+ {
+ var label = $"{this.debugs.LastOrDefault()?.RebootCount} OK";
+
+ return new Tuple(label, TaskState.Success);
+ }
+
+ private void DecryptResponse(JustSirtMessage response)
+ {
+ var data = response.Data;
+ var length = data.Length;
+
+ if (length < 13)
+ {
+ return;
+ }
+
+ var bytes = new Byte[length];
+ var hex = BitConverter.ToString(bytes);
+
+ Array.Copy(data, 0, bytes, 0, length);
+
+ var token = bytes[1];
+
+ for (var x = 6; x < length; x++)
+ {
+ token += (Byte)(bytes[x - (token & 0x3) - 1] >> ((token >> 6) & 0x1));
+
+ bytes[x] ^= this.EncryptionKey[(token >> 2) & 0x0F];
+
+ if (token >= 0x80)
+ {
+ bytes[x] = (Byte)~bytes[x];
+ }
+ }
+
+ var crc = this.CalculateCRC(bytes, 5, length - 2);
+
+ if (crc == 0 || crc == UInt16.MaxValue)
+ {
+ response.Data = bytes;
+ }
+ }
+
+ private void EncryptRequest()
+ {
+ var data = this.Data;
+ var dataLength = data.Length;
+ var telegramLength = dataLength + 2;
+ var telegram = new Byte[telegramLength];
+
+ Array.Copy(data, 0, telegram, 0, dataLength);
+
+ var telegramForCRCLength = telegramLength + 4;
+ var telegramForCRC = new Byte[telegramForCRCLength];
+ var address = this.Address;
+
+ telegramForCRC[0] = (Byte)(address >> 24);
+ telegramForCRC[1] = (Byte)(address >> 16);
+ telegramForCRC[2] = (Byte)(address >> 8);
+ telegramForCRC[3] = (Byte)(address >> 0);
+
+ Array.Copy(telegram, 0, telegramForCRC, 4, telegramLength);
+
+ var telegramCRC = this.CalculateCRC(telegramForCRC, 1, telegramForCRCLength - 2);
+
+ telegram[telegramLength - 2] = (Byte)(telegramCRC >> 8);
+ telegram[telegramLength - 1] = (Byte)(telegramCRC >> 0);
+
+ var reference = address;
+ var token = (Byte)0xFF;
+
+ for (var i = 0; i < telegramLength; i++)
+ {
+ token += (Byte)(((reference >> ((token & 0x3) << 3)) & 0xFF) >> ((token >> 6) & 1));
+
+ reference = reference << 8;
+ reference += telegram[i];
+
+ telegram[i] ^= this.EncryptionKey[(token >> 2) & 0x0F];
+
+ if (token >= 0x80)
+ {
+ telegram[i] = (Byte)~telegram[i];
+ }
+ }
+
+ this.Data = telegram;
+ }
+
+ private UInt16 CalculateCRC(Byte[] data, Int32 start, Int32 length)
+ {
+ var crc = (UInt16)0xFFFF;
+ var dataLength = data?.Length ?? 0;
+
+ if (start + length > dataLength)
+ {
+ return crc;
+ }
+
+ for (var b = start; b < length; b++)
+ {
+ var _byte = data[b];
+ var token = (UInt16)((_byte << 8) & 0xFF00);
+
+ for (var i = 0; i < 8; i++)
+ {
+ if (0x8000 == ((crc ^ token) & 0x8000))
+ {
+ crc <<= 1;
+ crc ^= 0x1021;
+ }
+ else
+ {
+ crc <<= 1;
+ }
+
+ token <<= 1;
+ }
+ }
+
+ return crc;
+ }
+ }
+}
diff --git a/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/TaskState.cs b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/TaskState.cs
new file mode 100644
index 00000000..e06d6018
--- /dev/null
+++ b/Common/Hardware/WaterMeter/eRegister/Common.Hardware.WaterMeter.eRegister/TaskState.cs
@@ -0,0 +1,11 @@
+namespace Common.Hardware.WaterMeter.eRegister
+{
+ public enum TaskState
+ {
+ Disabled,
+ None,
+ Success,
+ Warning,
+ Error
+ }
+}
\ No newline at end of file
diff --git a/Common/Logic/Common.Logic.Extensions.SQL/SQLReader.cs b/Common/Logic/Common.Logic.Extensions.SQL/SQLReader.cs
index fca11316..1a19eaf5 100644
--- a/Common/Logic/Common.Logic.Extensions.SQL/SQLReader.cs
+++ b/Common/Logic/Common.Logic.Extensions.SQL/SQLReader.cs
@@ -4,6 +4,7 @@
using System;
using System.Data.SqlClient;
+ using System.Diagnostics;
public class SQLReader : ISQLReader, IDisposable
{
@@ -34,9 +35,35 @@
type = typeof(T);
}
- readedValue = Convert.ChangeType(readedValue, type);
+ var tryParse = true;
- if (readedValue is T expectedValue)
+ if (tryParse)
+ {
+ try
+ {
+ readedValue = Convert.ChangeType(readedValue, type);
+ tryParse = false;
+ }
+ catch (Exception e)
+ {
+ Debug.Print(e.ToString());
+ }
+ }
+
+ if (tryParse)
+ {
+ try
+ {
+ readedValue = Enum.Parse(type, $"{readedValue}", true);
+ tryParse = false;
+ }
+ catch (Exception e)
+ {
+ Debug.Print(e.ToString());
+ }
+ }
+
+ if (!tryParse && readedValue is T expectedValue)
{
value = expectedValue;
}
diff --git a/Common/OmniPlus/InspectionUI.Plugins.Omni/TestBatch.cs b/Common/OmniPlus/InspectionUI.Plugins.Omni/TestBatch.cs
index 0bf773c6..37ca2e05 100644
--- a/Common/OmniPlus/InspectionUI.Plugins.Omni/TestBatch.cs
+++ b/Common/OmniPlus/InspectionUI.Plugins.Omni/TestBatch.cs
@@ -8,15 +8,10 @@
using System;
using System.Collections.Generic;
+ using System.Text;
using System.Threading;
using System.Threading.Tasks;
- ///
- /// if $(ConfigurationName) == Development rmdir "Z:\Programme_Sensus\plugins\omni" /s
- /// if $(ConfigurationName) == Development mkdir "Z:\Programme_Sensus\plugins\omni" /s
- /// if $(ConfigurationName) == Development xcopy $(TargetDir) "Z:\Programme_Sensus\plugins\omni" /s /y
- ///
-
[TestBatch("OMNI+ Prüfung")]
public partial class TestBatch : TestBatchBase
{
@@ -85,7 +80,7 @@
var testPointsCount = testPoints.Count;
var layout = this.testBench.Layout;
var columnsCount = this.SetColumnDefinitions(testPointsCount, layout);
- this.info = this.remoteControl.GetInfo();
+ this.info = new InfoMessage(); // this.remoteControl.GetInfo();
this.SetTestHead(layout, columnsCount);
this.SetOrderHead(inspectionOrder, layout, columnsCount);
@@ -271,6 +266,18 @@
}
})
.Wait();
+
+ var stringBuilder = new StringBuilder();
+
+ foreach (var meter in this.uimeters)
+ {
+ if (meter.IsInvalid)
+ {
+ stringBuilder.AppendLine(meter.Messages);
+ }
+ }
+
+ this.testBench.Notify(stringBuilder.ToString());
}
private void SetTestMeters(Int32 testPointsCount, IGrid layout)
diff --git a/Common/OmniPlus/InspectionUI.Plugins.Omni/UIMeter.cs b/Common/OmniPlus/InspectionUI.Plugins.Omni/UIMeter.cs
index 385ebe90..be1fe674 100644
--- a/Common/OmniPlus/InspectionUI.Plugins.Omni/UIMeter.cs
+++ b/Common/OmniPlus/InspectionUI.Plugins.Omni/UIMeter.cs
@@ -38,7 +38,7 @@
set => this[1].Text = value;
}
- public String Messages => this.meter.Messages;
+ public String Messages => $"{this.Slot} {this.meter.Messages}";
protected Int32 currentTPCellIndex;
@@ -48,6 +48,8 @@
set => this.currentTPCellIndex = value;
}
+ public Boolean IsInvalid => !this.meter.IsActive && !String.IsNullOrWhiteSpace(this.meter.Messages);
+
public Task ConnectAsync(CancellationToken cancellationToken)
{
void Connect(Object state)
@@ -72,6 +74,11 @@
}
};
}
+ else if (!meter.IsActive && !String.IsNullOrWhiteSpace(meter.Messages))
+ {
+ this[1].Background = TestBatch.Brushes.Red;
+ this[1].Foreground = TestBatch.Brushes.White;
+ }
uimeter.Pcb = meter.Pcb;
}
diff --git a/Common/OmniPlus/InspectionUI.RemoteControl/RemoteConnection.cs b/Common/OmniPlus/InspectionUI.RemoteControl/RemoteConnection.cs
index 1bc0ce2e..50d034ad 100644
--- a/Common/OmniPlus/InspectionUI.RemoteControl/RemoteConnection.cs
+++ b/Common/OmniPlus/InspectionUI.RemoteControl/RemoteConnection.cs
@@ -11,15 +11,13 @@
using Microsoft.AspNet.SignalR.Client;
- // xcopy "$(TargetDir)*.dll" "\\sla12file\Auftrag\Programme_Sensus\Pruefstation2000\TLB\Remote control" /Y
-
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IRemoteConnectionEvents))]
[Guid("FB571D10-F46A-4B32-B1B1-6E7DCE362CC1")]
[ComVisible(true)]
public class RemoteConnection : IRemoteConnection
{
- const string LogFile = @".\signalR.txt";
+ private const string LogFile = @".\signalR.txt";
private readonly ICollection disposables = new List();
diff --git a/Common/OmniPlus/InspectionUI/App.config b/Common/OmniPlus/InspectionUI/App.config
index b86b950d..cd98da8d 100644
--- a/Common/OmniPlus/InspectionUI/App.config
+++ b/Common/OmniPlus/InspectionUI/App.config
@@ -4,10 +4,9 @@
-
-
-
-
+
+
+
diff --git a/Common/OmniPlus/InspectionUI/App.xaml b/Common/OmniPlus/InspectionUI/App.xaml
index 30938e9e..1d3170bf 100644
--- a/Common/OmniPlus/InspectionUI/App.xaml
+++ b/Common/OmniPlus/InspectionUI/App.xaml
@@ -2,7 +2,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Converters="clr-namespace:InspectionUI.Converters"
- StartupUri="eRegister/Init.xaml" >
+ StartupUri="MainWindow.xaml" >
diff --git a/Common/OmniPlus/InspectionUI/InspectionUI.csproj b/Common/OmniPlus/InspectionUI/InspectionUI.csproj
index fc585af5..46e5dcda 100644
--- a/Common/OmniPlus/InspectionUI/InspectionUI.csproj
+++ b/Common/OmniPlus/InspectionUI/InspectionUI.csproj
@@ -72,17 +72,6 @@
MSBuild:Compile
Designer
-
- Init.xaml
-
-
- RunCommans.xaml
-
-
-
-
-
-
ItemsGrid.xaml
@@ -111,16 +100,8 @@
-
-
-
- Designer
- MSBuild:Compile
-
-
- Designer
- MSBuild:Compile
-
+
+
Designer
MSBuild:Compile
diff --git a/Common/OmniPlus/InspectionUI/ItemsGrid.xaml.cs b/Common/OmniPlus/InspectionUI/ItemsGrid.xaml.cs
index f3a54f97..278e1936 100644
--- a/Common/OmniPlus/InspectionUI/ItemsGrid.xaml.cs
+++ b/Common/OmniPlus/InspectionUI/ItemsGrid.xaml.cs
@@ -1,5 +1,6 @@
namespace InspectionUI
{
+ using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
@@ -45,52 +46,55 @@
private void ReorderItems(object sender, PropertyChangedEventArgs e)
{
- this.Children.Clear();
- this.RowDefinitions.Clear();
- this.ColumnDefinitions.Clear();
-
- var row = 0;
- var col = 0;
-
- foreach (var rowItem in this.ItemsSource)
+ this.Dispatcher.Invoke(new Action(() =>
{
- this.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
+ this.Children.Clear();
+ this.RowDefinitions.Clear();
+ this.ColumnDefinitions.Clear();
- foreach (var cell in rowItem)
+ var row = 0;
+ var col = 0;
+
+ foreach (var rowItem in this.ItemsSource)
{
- if (row == 0)
- {
- if (cell is ItemsGridCellVM header)
- {
- for (int i = 0; i < header.ColSpan; i++)
- {
- var width = header.Width <= 0
- ? GridLength.Auto
- : new GridLength(header.Width, GridUnitType.Star);
+ this.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
- this.ColumnDefinitions.Add(new ColumnDefinition { Width = width });
+ foreach (var cell in rowItem)
+ {
+ if (row == 0)
+ {
+ if (cell is ItemsGridCellVM header)
+ {
+ for (int i = 0; i < header.ColSpan; i++)
+ {
+ var width = header.Width <= 0
+ ? GridLength.Auto
+ : new GridLength(header.Width, GridUnitType.Star);
+
+ this.ColumnDefinitions.Add(new ColumnDefinition { Width = width });
+ }
}
}
+
+ cell.Col = col;
+ cell.Row = row;
+
+ var cellContent = new ContentControl { Content = cell };
+
+ Grid.SetRow(cellContent, row);
+ Grid.SetRowSpan(cellContent, cell.RowSpan);
+ Grid.SetColumn(cellContent, col);
+ Grid.SetColumnSpan(cellContent, cell.ColSpan);
+
+ this.Children.Add(cellContent);
+
+ col += cell.ColSpan;
}
- cell.Col = col;
- cell.Row = row;
-
- var cellContent = new ContentControl { Content = cell };
-
- Grid.SetRow(cellContent, row);
- Grid.SetRowSpan(cellContent, cell.RowSpan);
- Grid.SetColumn(cellContent, col);
- Grid.SetColumnSpan(cellContent, cell.ColSpan);
-
- this.Children.Add(cellContent);
-
- col += cell.ColSpan;
+ col = 0;
+ row++;
}
-
- col = 0;
- row++;
- }
+ }));
}
}
}
diff --git a/Common/OmniPlus/InspectionUI/VM.cs b/Common/OmniPlus/InspectionUI/ViewModels/VM.cs
similarity index 100%
rename from Common/OmniPlus/InspectionUI/VM.cs
rename to Common/OmniPlus/InspectionUI/ViewModels/VM.cs
diff --git a/Common/OmniPlus/InspectionUI/VM[T].cs b/Common/OmniPlus/InspectionUI/ViewModels/VM[T].cs
similarity index 100%
rename from Common/OmniPlus/InspectionUI/VM[T].cs
rename to Common/OmniPlus/InspectionUI/ViewModels/VM[T].cs
diff --git a/Common/OmniPlus/InspectionUI/eRegister/Init.xaml b/Common/OmniPlus/InspectionUI/eRegister/Init.xaml
deleted file mode 100644
index 3e6077d2..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/Init.xaml
+++ /dev/null
@@ -1,174 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Common/OmniPlus/InspectionUI/eRegister/Init.xaml.cs b/Common/OmniPlus/InspectionUI/eRegister/Init.xaml.cs
deleted file mode 100644
index 8d9a2a9f..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/Init.xaml.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Shapes;
-
-namespace InspectionUI.eRegister
-{
- ///
- /// Interaction logic for Init.xaml
- ///
- public partial class Init : Window
- {
- public Init()
- {
- InitializeComponent();
- }
- }
-}
diff --git a/Common/OmniPlus/InspectionUI/eRegister/RunCommans.xaml b/Common/OmniPlus/InspectionUI/eRegister/RunCommans.xaml
deleted file mode 100644
index 878d08e2..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/RunCommans.xaml
+++ /dev/null
@@ -1,176 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Common/OmniPlus/InspectionUI/eRegister/RunCommans.xaml.cs b/Common/OmniPlus/InspectionUI/eRegister/RunCommans.xaml.cs
deleted file mode 100644
index 4a6a347a..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/RunCommans.xaml.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Shapes;
-
-namespace InspectionUI.eRegister
-{
- ///
- /// Interaction logic for RunCommans.xaml
- ///
- public partial class RunCommans : Window
- {
- public RunCommans()
- {
- InitializeComponent();
- }
- }
-}
diff --git a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/GridCellVM.cs b/Common/OmniPlus/InspectionUI/eRegister/ViewModels/GridCellVM.cs
deleted file mode 100644
index ba93b787..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/GridCellVM.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-namespace InspectionUI.eRegister.ViewModels
-{
- using System;
- using System.Windows;
- using System.Windows.Media;
-
- public class GridCellVM : VM
- {
- private Int32 gridColumn;
- private Int32 gridRow;
- private String view;
- private TextAlignment textAlignment;
- private Brush background;
- private Brush foreground;
- private FontWeight fontWeight;
-
- public GridCellVM() : base()
- {
- this.Background = Brushes.White;
- this.Foreground = Brushes.Black;
- this.TextAlignment = TextAlignment.Center;
- this.FontWeight = FontWeights.Normal;
- }
-
- public String View
- {
- get => this.view;
- set => this.Set(x => x.view = value);
- }
-
- public Int32 GridColumn
- {
- get => this.gridColumn;
- set => this.Set(x => x.gridColumn = value);
- }
-
- public Int32 GridRow
- {
- get => this.gridRow;
- set => this.Set(x => x.gridRow = value);
- }
-
- public TextAlignment TextAlignment
- {
- get => this.textAlignment;
- set => this.Set(x => x.textAlignment = value);
- }
-
- public Brush Background
- {
- get => this.background;
- set => this.Set(x => x.background = value);
- }
-
- public Brush Foreground
- {
- get => this.foreground;
- set => this.Set(x => x.foreground = value);
- }
-
- public FontWeight FontWeight
- {
- get => this.fontWeight;
- set => this.Set(x => x.fontWeight = value);
- }
- }
-}
diff --git a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/InitVM.cs b/Common/OmniPlus/InspectionUI/eRegister/ViewModels/InitVM.cs
deleted file mode 100644
index c0e167d4..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/InitVM.cs
+++ /dev/null
@@ -1,251 +0,0 @@
-namespace InspectionUI.eRegister.ViewModels
-{
- using Common.Hardware.WaterMeter.eRegister;
-
- using System;
- using System.Collections.ObjectModel;
- using System.Threading;
- using System.Windows;
- using System.Windows.Media;
-
- public class InitVM : VM
- {
- private ProgrammingBatch programmingBatch;
- private Boolean waitingActivation;
- private String sirt;
-
- public InitVM() : base()
- {
- this.waitingActivation = true;
- this.ItemsSource = new ObservableCollection();
- }
-
- public Boolean WaitingActivation
- {
- get => this.waitingActivation;
- set => this.Set(vm => vm.waitingActivation = value);
- }
-
- public String SIRT
- {
- get => this.sirt;
- set => this.Set(vm => vm.sirt = value);
- }
-
- public ObservableCollection ItemsSource { get; }
-
- public override void Dispose()
- {
- this.programmingBatch.DeactivateSIRT();
-
- foreach (var disposable in this.ItemsSource)
- {
- disposable.Dispose();
- }
-
- base.Dispose();
- }
-
- public void Activate(ProgrammingBatch programmingBatch)
- {
- this.programmingBatch = programmingBatch;
- this.programmingBatch.Activated += this.LoadEndpoints;
- this.programmingBatch.Done += this.Shutdown;
-
- this.StartTask(this.programmingBatch.ActivateSIRT);
- }
-
- private void Shutdown(Int32 exitCode)
- {
- this.DispatcherInvoke(() =>
- {
- this.Dispose();
-
- Thread.Sleep(5000);
- App.Current.Shutdown(exitCode);
- });
- }
-
- private void LoadEndpoints(String sirtID, Int32 MHz)
- {
- this.SIRT = $"SIRT({sirtID}) - {MHz}MHz";
- this.programmingBatch.Activated -= this.LoadEndpoints;
-
- this.DispatcherInvoke(() =>
- {
- var gridRow = 0;
-
- this.AddSlots(gridRow++);
- this.AddSerialNumbers(gridRow++);
- this.AddRadioAddresses(gridRow++);
- this.AddInitTasks(gridRow++);
- this.AddSetupTasks(gridRow++);
- this.AddMeterReading(gridRow++);
- this.AddLED(gridRow++);
- this.AddChecks(gridRow++);
- });
- }
-
- private void AddSlots(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Einbauplatz",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var slot in this.programmingBatch.Slots())
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = $"{slot}",
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
- }
- }
-
- private void AddSerialNumbers(Int32 gridRow, Int32 gridColumn = 0)
- {
-
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "SerienNr",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var serialno in this.programmingBatch.SerialNumbers())
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = $"{serialno}",
- });
- }
- }
-
- private void AddRadioAddresses(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Adresse",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var address in this.programmingBatch.RadioAddresses())
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = $"{address}",
- });
- }
- }
-
- private void AddInitTasks(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "WUP|LAT|TXIV|MBUS",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.InitForInspection())
- {
- this.ItemsSource.Add(new TaskVM(gridRow, gridColumn++, task));
- }
- }
-
- private void AddSetupTasks(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Prüfunginitialisierung",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.InitForInspection())
- {
- this.ItemsSource.Add(new TaskVM(gridRow, gridColumn++, task));
- }
- }
-
- private void AddMeterReading(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "111111.111",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.SetDisplay111111111())
- {
- this.ItemsSource.Add(new TaskVM(gridRow, gridColumn++, task));
- }
- }
-
- private void AddLED(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "LED AN",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.StartLED())
- {
- this.ItemsSource.Add(new TaskVM(gridRow, gridColumn++, task));
- }
- }
-
- private void AddChecks(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Überprüfen",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.DoChecks())
- {
- this.ItemsSource.Add(new TaskVM(gridRow, gridColumn++, task));
- }
- }
- }
-}
diff --git a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/RunCommandsVM.cs b/Common/OmniPlus/InspectionUI/eRegister/ViewModels/RunCommandsVM.cs
deleted file mode 100644
index 4350b1fd..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/RunCommandsVM.cs
+++ /dev/null
@@ -1,137 +0,0 @@
-namespace InspectionUI.eRegister.ViewModels
-{
- using Common.Hardware.WaterMeter.eRegister;
-
- using System;
- using System.Collections.ObjectModel;
- using System.Threading;
- using System.Windows;
- using System.Windows.Media;
-
- public class RunCommandsVM : VM
- {
- private ProgrammingBatch programmingBatch;
- private Boolean waitingActivation;
- private String sirt;
-
- public RunCommandsVM() : base()
- {
- this.waitingActivation = true;
- this.ItemsSource = new ObservableCollection();
- }
-
- public Boolean WaitingActivation
- {
- get => this.waitingActivation;
- set => this.Set(vm => vm.waitingActivation = value);
- }
-
- public String SIRT
- {
- get => this.sirt;
- set => this.Set(vm => vm.sirt = value);
- }
-
- public ObservableCollection ItemsSource { get; }
-
- public override void Dispose()
- {
- this.programmingBatch.DeactivateSIRT();
-
- foreach (var disposable in this.ItemsSource)
- {
- disposable.Dispose();
- }
-
- base.Dispose();
- }
-
- public void Activate(ProgrammingBatch programmingBatch)
- {
- this.programmingBatch = programmingBatch;
- this.programmingBatch.Activated += this.LoadEndpoints;
- this.programmingBatch.Done += this.Shutdown;
-
- this.StartTask(this.programmingBatch.ActivateSIRT);
- }
-
- private void Shutdown(Int32 exitCode)
- {
- this.DispatcherInvoke(() =>
- {
- this.Dispose();
-
- Thread.Sleep(5000);
- App.Current.Shutdown(exitCode);
- });
- }
-
- private void LoadEndpoints(String sirtID, Int32 MHz)
- {
- this.SIRT = $"SIRT({sirtID}) - {MHz}MHz";
- this.programmingBatch.Activated -= this.LoadEndpoints;
-
- this.DispatcherInvoke(() =>
- {
- var gridRow = 0;
- var first = false;
-
- foreach (var commands in this.programmingBatch.RunCommands())
- {
- var gridColumn = 0;
-
- if (!first)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Einbauplatz",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var slot in this.programmingBatch.Slots())
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = $"{slot}",
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
- }
-
- first = true;
- }
-
- var headerSet = false;
- var header = new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "PAM -1",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- };
-
- this.ItemsSource.Add(header);
-
- foreach (var command in commands)
- {
- if (!headerSet)
- {
- header.View = command.FirstPamId;
- headerSet = true;
- }
-
- this.ItemsSource.Add(new TaskVM(gridRow, gridColumn++, command));
- }
- }
- });
- }
- }
-}
diff --git a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/TaskVM.cs b/Common/OmniPlus/InspectionUI/eRegister/ViewModels/TaskVM.cs
deleted file mode 100644
index 56d0e6cb..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/TaskVM.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-namespace InspectionUI.eRegister.ViewModels
-{
- using Common.Hardware.WaterMeter.eRegister;
-
- using System;
- using System.Windows.Media;
-
- public class TaskVM : GridCellVM
- {
- const String VIEW = "-----";
-
- private readonly EndpointTask task;
-
- public TaskVM(Int32 gridRow, Int32 gridColumn, EndpointTask task) : base()
- {
- this.GridRow = gridRow;
- this.GridColumn = gridColumn;
- this.task = task;
- this.task.Cancelled += this.Cancelled;
- this.task.Completed += this.Completed;
- this.task.Received += this.Received;
- this.View = VIEW;
- }
-
- public override void Dispose()
- {
- this.task.Cancelled -= this.Cancelled;
- this.task.Completed -= this.Completed;
-
- base.Dispose();
- }
-
- private void Completed()
- {
- this.Background = Brushes.LightGreen;
- this.Foreground = Brushes.DarkGreen;
-
- if (this.View == VIEW)
- {
- this.View = "OK";
- }
- }
-
- private void Cancelled()
- {
- this.Background = Brushes.LightCoral;
- this.Foreground = Brushes.DarkRed;
-
- if (this.View == VIEW)
- {
- this.View = "FEHLER";
- }
- }
-
- private void Received(String type)
- {
- this.Background = Brushes.White;
- this.Foreground = Brushes.Black;
- this.View = type;
- }
- }
-}
diff --git a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/TextVM.cs b/Common/OmniPlus/InspectionUI/eRegister/ViewModels/TextVM.cs
deleted file mode 100644
index 9c0faf0a..00000000
--- a/Common/OmniPlus/InspectionUI/eRegister/ViewModels/TextVM.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace InspectionUI.eRegister.ViewModels
-{
- public class TextVM : GridCellVM
- {
- public TextVM() : base()
- {
- }
- }
-}
diff --git a/Common/PendingEmails/PendingEmails.csproj b/Common/PendingEmails/PendingEmails.csproj
index dd0e6dd6..f66d0fa0 100644
--- a/Common/PendingEmails/PendingEmails.csproj
+++ b/Common/PendingEmails/PendingEmails.csproj
@@ -48,7 +48,7 @@
4
- 4F225C82652E1EBABD8B58C34175D7B260B3A052
+ 857BDC9424CA995BBB5640EE4C4D03DB5F1F2369
PendingEmails_TemporaryKey.pfx
@@ -57,7 +57,17 @@
true
- true
+ false
+
+
+ false
+
+
+
+
+
+
+ true
@@ -75,7 +85,6 @@
-
diff --git a/Common/PendingEmails/Program.cs b/Common/PendingEmails/Program.cs
index 3e1aee8b..c1f2cd07 100644
--- a/Common/PendingEmails/Program.cs
+++ b/Common/PendingEmails/Program.cs
@@ -69,29 +69,42 @@
{
command.CommandTimeout = 60000;
command.CommandText = @"
- SELECT [Pruefstation]
- , [Pruefdatum]
- , [Mitarbaiter]
- , [Auftrag]
- , [Position]
- , [Fertigungsauftrag]
- , [Merkmal]
- , [Bezeichnung]
- , [Menge]
- , [SerienNrVon]
- , [SerienNrBis]
- , [Kunde]
- , [Kundenort]
- FROM [AlleAuftraegeMitGarantieAusLetzte13Min]
- ORDER BY [Pruefdatum]";
-
- using (var reader = command.ExecuteReader())
- {
- while (reader.Read())
- {
- reader.AddToPendingMessages();
- }
- }
+ INSERT INTO Messages
+ ( Source
+ , InDate
+ , StationNr
+ , PCName
+ , IPAddress
+ , Trace
+ , Sender
+ , Subject
+ , Body
+ , Recipients
+ , CC
+ , State)
+ SELECT ag.Fertigungsauftrag
+ , CURRENT_TIMESTAMP
+ , ag.Pruefstation
+ , @@SERVERNAME
+ , @@SERVICENAME
+ , 'Xylem.Common.Service.PendingMails'
+ , 'noreplay@xylem.com'
+ , ISNULL(ag.Kundenort, 'Kundenort') + ' - ' + CAST(ag.Auftrag AS VARCHAR(15)) + '/' + CAST(ag.Position AS VARCHAR(10))
+ + ' erfolgreich geprüft - bitte Garantiescheine drucken und bereitlegen!'
+ , 'Auftrag: ' + CAST(ag.Auftrag AS VARCHAR(15)) + '/' + CAST(ag.Position AS VARCHAR(10)) + CHAR(10)
+ 'FertigungsauftragNr: ' + CAST(ISNULL(ag.Fertigungsauftrag, 0) AS VARCHAR(15)) + CHAR(10)
+ + CHAR(10)
+ CAST(ISNULL(ag.Menge, 0) AS VARCHAR(10)) + ' Stück ' + ag.Bezeichnung + CHAR(10)
+ 'wurde an der Prüfstation: ' + CAST(ISNULL(ag.Pruefstation, 0) AS VARCHAR(5)) + CHAR(10)
+ 'am ' + CONVERT(VARCHAR(10), ag.Pruefdatum, 105) + ' um ' + CONVERT(VARCHAR(5), ag.Pruefdatum, 108) + ' Uhr' + CHAR(10)
+ 'von ' + ag.Mitarbaiter + ' vollständig geprüft.' + CHAR(10)
+ + CHAR(10)
+ 'Seriennummern: ' + CAST(ag.SerienNrVon AS VARCHAR(15)) + ' - ' + CAST(ag.SerienNrBis AS VARCHAR(15)) + '' + CHAR(10)
+ + CHAR(10)
+ + ag.Merkmal + CHAR(10)
+ , 'uwe.kubon@xylem.com'
+ , 'stoyan.zlatev@xylem.com'
+ , 'Automatische fertigmeldung für garantiescheine.'
+ FROM AlleGepruefteAuftraegeMitGarantieAusLetzte24Hours AS ag
+ LEFT JOIN Messages AS msg
+ ON ag.Fertigungsauftrag LIKE msg.Source
+ WHERE msg.Id IS NULL";
+
+ LogToFile($"Inserted: {command.ExecuteNonQuery()}");
}
var updated = new HashSet();
@@ -215,86 +228,6 @@
return Path.Combine(logPath, $"{DateTime.Now:yyyy-MM-dd}.txt");
}
- private static void AddToPendingMessages(this SqlDataReader reader)
- {
- var psno = reader.GetValue(0);
- var date = reader.GetValue(1);
- var empl = reader.GetValue(2);
- var orderno = reader.GetValue(3);
- var posno = reader.GetValue(4);
- var pono = reader.GetValue(5);
- var vako = reader.GetValue(6);
- var desc = reader.GetValue(7);
- var count = reader.GetValue(8);
- var snfrom = reader.GetValue(9);
- var snto = reader.GetValue(10);
- var client = reader.GetValue(11);
- var ort = reader.GetValue(12);
-
- var source = $"{orderno}/{posno}";
- var subject = $"{ort} - {orderno}/{posno} erfolgreich geprüft - bitte Garantiescheine drucken und bereitlegen!";
- var body = $"Auftrag: {orderno}/{posno}{Environment.NewLine}"
+ $"FertigungsauftragNr: {pono}{Environment.NewLine}"
- + $"{Environment.NewLine}"
+ $"{count} Stück {desc}{Environment.NewLine}"
+ $"wurde an der Prüfstation: {psno}{Environment.NewLine}"
+ $"am {date:dd-MM-yyyy} um {date:HH:mm} Uhr{Environment.NewLine}"
+ $"von {empl} vollständig geprüft.{Environment.NewLine}"
+ $"{Environment.NewLine}"
+ $"Seriennummern: {snfrom} - {snto}{Environment.NewLine}"
- + $"{Environment.NewLine}"
- + $"{vako}{Environment.NewLine}";
-
- var connectionString = ConfigurationManager.ConnectionStrings["Auftrag"].ConnectionString;
-
- using (var connection = new SqlConnection(connectionString))
- {
- connection.FireInfoMessageEventOnUserErrors = true;
- connection.InfoMessage += (_2, args) => LogToFile(args.Message);
- connection.Open();
-
- var ready = new List();
-
- using (var command = connection.CreateCommand())
- {
- command.CommandText = $@"
- IF (SELECT COUNT(1) FROM [Messages] WHERE [Source] = @{nameof(source)}) = 0
- BEGIN
- INSERT INTO [Messages]
- ( [Source]
- , [InDate]
- , [StationNr]
- , [PCName]
- , [IPAddress]
- , [Trace]
- , [Sender]
- , [Subject]
- , [Body]
- , [IsHtml]
- , [Recipients]
- , [CC]
- , [OutDate]
- , [State])
- VALUES (@{nameof(source)}
- , GETDATE()
- , @{nameof(psno)}
- , 'localhost'
- , '127.0.0.1'
- , 'Xylem.Common.Service.PendingMails.Timer_Elapsed(Object, ElapsedEventArgs))'
- , 'noreplay@xylem.com'
- , @{nameof(subject)}
- , @{nameof(body)}
- , 0
- , 'uwe.kubon@xylem.com'
- , 'stoyan.zlatev@xylem.com'
- , NULL
- , 'Automatische fertigmeldung für garantiescheine')
- END";
- command.Parameters.AddWithValue(nameof(source), source);
- command.Parameters.AddWithValue(nameof(subject), subject);
- command.Parameters.AddWithValue(nameof(body), body);
- command.Parameters.AddWithValue(nameof(psno), psno);
-
- LogToFile($"Inserted: {command.ExecuteNonQuery()}");
-
- command.Parameters.Clear();
- }
- }
- }
-
private static T GetValue(this SqlDataReader sqlDataReader, Int32 index, T defaultValue = default(T))
{
var value = defaultValue;
diff --git a/Common/Service/MeterProcessState/Controllers/FinalCheckController.cs b/Common/Service/MeterProcessState/Controllers/FinalCheckController.cs
index bbc73c44..5539a4fb 100644
--- a/Common/Service/MeterProcessState/Controllers/FinalCheckController.cs
+++ b/Common/Service/MeterProcessState/Controllers/FinalCheckController.cs
@@ -1,4 +1,5 @@
-using Logic.ProductionToProductMapper.Cordonel;
+using Common.Logic.Extensions.SQL;
+using Logic.ProductionToProductMapper.Cordonel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
@@ -1270,6 +1271,71 @@ namespace Xylem.Common.Service.MeterProcessState.Controllers
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex.ToString() + "
" + ex.InnerException.ToString());
}
}
+
+
+
+ [HttpGet]
+ [Route("CalibrationResults/{pcbId}")]
+ public IHttpActionResult CalibrationResults(String pcbId)
+ {
+ var result = SQLConnection
+ .CreateSQLConnection(GlobalConfig.ConnectionString.Value)
+ .CreateCommand($@"
+ SELECT TOP 1
+ ID
+ , PcbId
+ , CalFactor1
+ , CalFactor2
+ , CalFactor3
+ , ZeroOffset1
+ , ZeroOffset2
+ , ZeroOffset3
+ , FirstHitUpdatePeriod
+ , FirstHitShift
+ , FirstHitPercent1
+ , FirstHitPercent2
+ , FirstHitPercent3
+ , ToFTempOffset1
+ , ToFTempOffset2
+ , ToFTempOffset3
+ , MeterSize
+ , date
+ , successful
+ FROM CordonelMeterCalibrationResults
+ WHERE successful = 1
+ AND PcbId = @{nameof(pcbId)}
+ ORDER BY date DESC")
+ .SetParameter(nameof(pcbId), pcbId)
+ .FirstOrDefault(x => new
+ {
+ Id = x.GetValue(0),
+ PcbId = x.GetValue(1),
+ CalFactor1 = x.GetValue(2),
+ CalFactor2 = x.GetValue(3),
+ CalFactor3 = x.GetValue(4),
+ ZeroOffset1 = x.GetValue(5),
+ ZeroOffset2 = x.GetValue(6),
+ ZeroOffset3 = x.GetValue(7),
+ FirstHitUpdatePeriod = x.GetValue(8),
+ FirstHitShift = x.GetValue(9),
+ FirstHitPercent1 = x.GetValue(10),
+ FirstHitPercent2 = x.GetValue(11),
+ FirstHitPercent3 = x.GetValue(12),
+ ToFTempOffset1 = x.GetValue(13),
+ ToFTempOffset2 = x.GetValue(14),
+ ToFTempOffset3 = x.GetValue(15),
+ MeterSize = x.GetValue(16),
+ Date = x.GetValue(17),
+ Succeeded = x.GetValue(18),
+ });
+
+ if (result is null)
+ {
+ return this.NotFound();
+ }
+
+ return this.Json(result);
+ }
}
}
diff --git a/Common/Service/MeterProcessState/Controllers/RadioCheckController.cs b/Common/Service/MeterProcessState/Controllers/RadioCheckController.cs
index ebdeba22..c10a6b56 100644
--- a/Common/Service/MeterProcessState/Controllers/RadioCheckController.cs
+++ b/Common/Service/MeterProcessState/Controllers/RadioCheckController.cs
@@ -1,4 +1,5 @@
-using Newtonsoft.Json;
+using Common.Logic.Extensions.SQL;
+using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
@@ -208,6 +209,7 @@ namespace Xylem.Common.Service.MeterProcessState.Controllers
JObject jsonData = new JObject();
saveRssiToDb(SaveData);
jsonData.Add("message", "ok");
+ jsonData.Add("radiocheckid", saveRssiToDb(SaveData));
return Json(JObject.FromObject(jsonData));
}
@@ -215,32 +217,40 @@ namespace Xylem.Common.Service.MeterProcessState.Controllers
/// Speichert das SaveData Object
///
///
- private void saveRssiToDb(SaveDataClass SaveData)
+ private Int64 saveRssiToDb(SaveDataClass SaveData)
{
- var sql = new StringBuilder();
+ var sqlConnection = SQLConnection.CreateSQLConnection(GlobalConfig.connectionString.Value);
- sql.AppendLine($" Update [Cordonel_Radio_RSSI_History] Set IsLast = 0 WHERE [RadioAdress] = {SaveData.RadioAdress}");
- using (SqlCommand sqlcommand = new SqlCommand(sql.ToString(), connection))
- {
- sqlcommand.ExecuteNonQuery();
- }
+ sqlConnection
+ .CreateCommand($@"
+ UPDATE Cordonel_Radio_RSSI_History
+ SET IsLast = 0
+ WHERE RadioAdress = @{nameof(SaveData.RadioAdress)}")
+ .SetParameter(nameof(SaveData.RadioAdress), (Int64)SaveData.RadioAdress)
+ .ExecuteNonQuery();
-
- sql = new StringBuilder();
- sql.AppendLine($" Insert into [Cordonel_Radio_RSSI_History] ");
- sql.AppendLine($" ([RadioAdress],[RSSI_PAM],[RSSI_SEMI],[LimitId],[Result]) VALUES ( ");
- sql.AppendLine($" {SaveData.RadioAdress},");
- sql.AppendLine($" {SaveData.RSSI_PAM},");
- sql.AppendLine($" {SaveData.RSSI_SEMI},");
- sql.AppendLine($" {SaveData.LimitId},");
- sql.AppendLine($" {SaveData.Result}");
- sql.AppendLine($" )");
-
- using (SqlCommand sqlcommand = new SqlCommand(sql.ToString(), connection))
- {
- sqlcommand.ExecuteNonQuery();
- }
+ return sqlConnection
+ .CreateCommand($@"
+ INSERT INTO Cordonel_Radio_RSSI_History
+ ( RadioAdress
+ , RSSI_PAM
+ , RSSI_SEMI
+ , Datum
+ , LimitId
+ , Result)
+ OUTPUT inserted.id
+ VALUES (@{nameof(SaveData.RadioAdress)}
+ , @{nameof(SaveData.RSSI_PAM)}
+ , @{nameof(SaveData.RSSI_SEMI)}
+ , CURRENT_TIMESTAMP
+ , @{nameof(SaveData.LimitId)}
+ , @{nameof(SaveData.Result)})")
+ .SetParameter(nameof(SaveData.RadioAdress), (Int64)SaveData.RadioAdress)
+ .SetParameter(nameof(SaveData.RSSI_PAM), SaveData.RSSI_PAM)
+ .SetParameter(nameof(SaveData.RSSI_SEMI), SaveData.RSSI_SEMI)
+ .SetParameter(nameof(SaveData.LimitId), SaveData.LimitId)
+ .SetParameter(nameof(SaveData.Result), SaveData.Result)
+ .ExecuteScalar(x => x.GetValue(0));
}
-
}
}
diff --git a/Common/Service/MeterProcessState/Controllers/TestBenchController.cs b/Common/Service/MeterProcessState/Controllers/TestBenchController.cs
index 76cb8147..6885f443 100644
--- a/Common/Service/MeterProcessState/Controllers/TestBenchController.cs
+++ b/Common/Service/MeterProcessState/Controllers/TestBenchController.cs
@@ -223,7 +223,7 @@
return this.BadRequest("Invalid data.");
}
-
+
[Route("GetTestResults"), HttpGet]
public IHttpActionResult GetTestResults(int SerialNr, int TestRunNr)
@@ -357,22 +357,22 @@
{
}
-
+
+ }
+
+ return this.Content(HttpStatusCode.OK, tr);
}
+ }
- return this.Content(HttpStatusCode.OK, tr);
+ public class CordonelCalibration
+ {
+ public int PcbId { get; set; }
+
+ public int TestRunNr { get; set; }
+
+ public double Offset { get; set; }
}
}
-
- public class CordonelCalibration
- {
- public int PcbId { get; set; }
-
- public int TestRunNr { get; set; }
-
- public double Offset { get; set; }
- }
-}
}
diff --git a/Common/SoftwareAccessHelper/LocalWebRequest.cs b/Common/SoftwareAccessHelper/LocalWebRequest.cs
index fb15f337..7f42fae3 100644
--- a/Common/SoftwareAccessHelper/LocalWebRequest.cs
+++ b/Common/SoftwareAccessHelper/LocalWebRequest.cs
@@ -4,6 +4,8 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
namespace Xylem.Common.Logic.SoftwareAccessHelper
{
@@ -118,7 +120,7 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
var request = new RestRequest(Method.POST);
ServicePointManager.Expect100Continue = false;
-
+
request.AddHeader("Content-Type", "multipart/form-data");
@@ -126,7 +128,8 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
request.Files.Add(new FileParameter
{
Name = "file",
- Writer = (s) => {
+ Writer = (s) =>
+ {
var stream = new MemoryStream(content);
stream.CopyTo(s);
stream.Dispose();
@@ -166,19 +169,20 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
{
var client = new RestClient(url);
- // WebRequest.DefaultWebProxy = null;
+ // WebRequest.DefaultWebProxy = null;
var request = new RestRequest(Method.POST);
ServicePointManager.Expect100Continue = false;
-
+
request.AddHeader("Content-Type", "multipart/form-data");
request.Files.Add(new FileParameter
{
Name = "file",
- Writer = (s) => {
+ Writer = (s) =>
+ {
var stream = new MemoryStream(content);
stream.CopyTo(s);
stream.Dispose();
@@ -264,6 +268,45 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
}
+
+ ///
+ /// Post Request Async
+ ///
+ ///
+ /// - Initial.
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static String PostRequestAsync(String url, Double timeoutMs, out HttpStatusCode httpStatus, Object json = null)
+ {
+ try
+ {
+ var httpClient = new HttpClient();
+
+ httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ httpClient.Timeout = TimeSpan.FromMilliseconds(timeoutMs);
+
+ var postedJson = JsonConvert.SerializeObject(json, Formatting.Indented);
+ var postedBody = new StringContent(postedJson);
+ postedBody.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
+ var posted = httpClient
+ .PostAsync(url, postedBody)
+ .Result;
+
+ httpStatus = posted.StatusCode;
+ return posted.Content.ReadAsStringAsync().Result;
+ }
+ catch (Exception error)
+ {
+ httpStatus = HttpStatusCode.ServiceUnavailable;
+ return error.Message;
+ }
+ }
+
+
///
/// Web request with asynchronous operation
///
@@ -272,18 +315,19 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
///
///
///
- public static IRestResponse PostRequestAndGetResponseAsync(String url, Int32? timeoutMs = null, Object json = null,
+ public static IRestResponse PostRequestAndGetResponseAsync(String url, Int32? timeoutMs = null, Object json = null,
Dictionary header = null)
{
try
{
var client = new RestClient(url);
+ client.AddDefaultHeader("Accept", "application/json");
//WebRequest.DefaultWebProxy = null;
ServicePointManager.Expect100Continue = false;
var request = new RestRequest(Method.POST);
-
+
if (header != null)
{
foreach (var item in header)
@@ -294,10 +338,7 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
}
}
-
}
-
-
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
@@ -308,8 +349,6 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
var r = client.ExecuteAsPost(request, Method.POST.ToString());
return r;
-
-
}
catch (Exception error)
{
@@ -318,9 +357,7 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
StatusCode = HttpStatusCode.InternalServerError,
Content = error.ToString()
};
-
}
-
}
#region HTTP String extensions
@@ -367,6 +404,70 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
}
#endregion HTTP Object extensions
+ ///
+ /// Web request
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static String DeleteRequest(String url, Int32? timeoutMs = null, Dictionary header = null, Boolean isRetry = false)
+ {
+ Int32 temp;
+ var ret = DeleteRequestWithError(url, out temp, timeoutMs, header, isRetry);
+ if (temp != 200)
+ {
+ throw new ApplicationException($"WebRequest Status {temp}");
+ }
+ return ret;
+ }
+
+ ///
+ /// Web request with asynchronous operation, error code response
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static String DeleteRequestWithError(String url, out Int32 errorCode, Int32? timeoutMs = null, Dictionary header = null, Boolean isRetry = false)
+ {
+ var client = new RestClient(url);
+ var request = new RestRequest(Method.DELETE);
+ ServicePointManager.Expect100Continue = false;
+ if (!timeoutMs.HasValue)
+ {
+ timeoutMs = 800;
+ }
+
+ request.Timeout = timeoutMs.Value;
+
+ if (header != null)
+ {
+ foreach (var item in header)
+ {
+ if (item.Key != "Accept")
+ {
+ request.AddHeader(item.Key, item.Value);
+ }
+ }
+ }
+ request.AddHeader("Accept", "application/json");
+
+ var r = client.Execute(request);
+ errorCode = r.StatusCode.GetHashCode();
+ if (r.StatusCode == HttpStatusCode.OK)
+ {
+ return r.Content;
+ }
+
+ if (r.StatusCode != 0)
+ return r.Content;
+
+ return !isRetry ? DeleteRequest(url, timeoutMs, header, true) : r.Content;
+ }
///
/// Web request
///
@@ -378,7 +479,7 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
public static String GetRequest(String url, Int32? timeoutMs = null, Dictionary header = null, Boolean isRetry = false)
{
Int32 temp;
- var ret = GetRequestWithError(url, out temp, timeoutMs, header, isRetry);
+ var ret = GetRequestWithError(url, out temp, timeoutMs, header, isRetry);
if (temp != 200)
{
throw new ApplicationException($"WebRequest Status {temp}");
@@ -399,7 +500,6 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
{
var client = new RestClient(url);
- //WebRequest.DefaultWebProxy = null;
var request = new RestRequest(Method.GET);
ServicePointManager.Expect100Continue = false;
if (!timeoutMs.HasValue)
@@ -430,17 +530,10 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
return r.Content;
}
- if (r.StatusCode != 0) return r.Content;
+ if (r.StatusCode != 0)
+ return r.Content;
- // Changed logic as it seems to be an endless loop THW 25-Mar-2021
- //if (presult.Status == IPStatus.Success || !isRetry)
- if (!isRetry)
- {
- return GetRequest(url, timeoutMs, header, true);
- }
- // Removed throwing of exception as the caller cannot evaluate the result THW 25-Mar-2021
- //throw new ApplicationException($"Timeout { r.StatusDescription} {Environment.NewLine} PingState: {presult.Status} {Environment.NewLine} RoundtripTime: {presult.RoundtripTime} ");
- return r.Content;
+ return !isRetry ? GetRequest(url, timeoutMs, header, true) : r.Content;
}
private static HttpResponse AsJson(this Method method, String url, Action headersHandler = null, Object model = null, Int32? timeoutMs = null)
@@ -472,7 +565,7 @@ namespace Xylem.Common.Logic.SoftwareAccessHelper
}
ServicePointManager.Expect100Continue = false;
-
+
var response = client.Execute(request);
httpResponse.HttpStatusCode = response.StatusCode;
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/App.config b/Common/Ui/Common.UI.SIRTBroadcaster/App.config
deleted file mode 100644
index 6551dddf..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/App.config
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/App.xaml b/Common/Ui/Common.UI.SIRTBroadcaster/App.xaml
deleted file mode 100644
index 6f249b31..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/App.xaml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/App.xaml.cs b/Common/Ui/Common.UI.SIRTBroadcaster/App.xaml.cs
deleted file mode 100644
index 81ab4403..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/App.xaml.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-namespace Common.UI.SIRTBroadcaster
-{
- using System;
- using System.Windows;
-
- public partial class App : Application
- {
- private static Boolean activatedForFirstTime;
-
- public static event Action Exited;
- public static event Action Started;
-
- public static void Invoke(Action action) => Current?.Dispatcher?.Invoke(action);
-
- protected override void OnActivated(EventArgs e)
- {
- base.OnActivated(e);
-
- if (!activatedForFirstTime)
- {
- activatedForFirstTime = true;
-
- Started?.Invoke();
- }
- }
-
- protected override void OnExit(ExitEventArgs e)
- {
- Exited?.Invoke();
-
- base.OnExit(e);
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Common.UI.SIRTBroadcaster.csproj b/Common/Ui/Common.UI.SIRTBroadcaster/Common.UI.SIRTBroadcaster.csproj
deleted file mode 100644
index 75043f30..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Common.UI.SIRTBroadcaster.csproj
+++ /dev/null
@@ -1,147 +0,0 @@
-
-
-
-
- Debug
- AnyCPU
- {8D3B1C46-B23E-46CC-9B59-24E34DE60510}
- WinExe
- Common.UI.SIRTBroadcaster
- Common.UI.SIRTBroadcaster
- v4.0
- 512
- {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
- 4
- true
-
-
- AnyCPU
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
- IDE0003;IDE0049;
-
-
- AnyCPU
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
-
-
-
- ..\..\packages\Newtonsoft.Json.13.0.3\lib\net40\Newtonsoft.Json.dll
-
-
- ..\..\packages\NLog.5.3.2\lib\net35\NLog.dll
-
-
-
-
-
-
-
-
-
-
- 4.0
-
-
-
-
-
-
-
- MSBuild:Compile
- Designer
-
-
- InitInspectionWindow.xaml
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Designer
- MSBuild:Compile
-
-
- MSBuild:Compile
- Designer
-
-
- App.xaml
- Code
-
-
- MainWindow.xaml
- Code
-
-
-
-
-
- Code
-
-
- True
- True
- Resources.resx
-
-
- True
- Settings.settings
- True
-
-
- ResXFileCodeGenerator
- Resources.Designer.cs
-
-
-
-
- SettingsSingleFileGenerator
- Settings.Designer.cs
-
-
-
-
- {b23bfaf9-08ae-4311-8c08-fb2bb49ea2ad}
- Common.Hardware.Interfaces.Ports.SIRT
-
-
- {9ae071c0-db12-4e09-a3c7-43f6dcd518d6}
- Common.Hardware.Interfaces.Ports
-
-
- {E19C1694-132E-477C-86CB-8E146D5F59B0}
- Common.Hardware.WaterMeter.eRegister.Features
-
-
- {4E8BB839-D40A-488C-88CE-F21811F1F476}
- Common.Hardware.WaterMeter.eRegister
-
-
- {05f0ccaf-9f2b-45f9-a7f8-12f29ad182f3}
- Common.Utils.Extensions
-
-
-
-
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/InitInspectionWindow.xaml b/Common/Ui/Common.UI.SIRTBroadcaster/InitInspectionWindow.xaml
deleted file mode 100644
index 6ced5c2e..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/InitInspectionWindow.xaml
+++ /dev/null
@@ -1,72 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/InitInspectionWindow.xaml.cs b/Common/Ui/Common.UI.SIRTBroadcaster/InitInspectionWindow.xaml.cs
deleted file mode 100644
index 14944a74..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/InitInspectionWindow.xaml.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-namespace Common.UI.SIRTBroadcaster
-{
- using Common.Hardware.WaterMeter.eRegister;
- using Common.UI.SIRTBroadcaster.ViewModels;
-
- using System.Windows;
-
- public partial class InitInspectionWindow : Window
- {
- public InitInspectionWindow()
- {
- this.InitializeComponent();
-
- App.Started += this.App_Started;
- }
-
- private void App_Started()
- {
- if (this.DataContext is InitInspectionVM inspection)
- {
- inspection.Shutdown += App.Current.Shutdown;
- inspection.StartProgramming();
- }
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/MainWindow.xaml b/Common/Ui/Common.UI.SIRTBroadcaster/MainWindow.xaml
deleted file mode 100644
index d5adcd04..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/MainWindow.xaml
+++ /dev/null
@@ -1,122 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/MainWindow.xaml.cs b/Common/Ui/Common.UI.SIRTBroadcaster/MainWindow.xaml.cs
deleted file mode 100644
index ce8eca7b..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/MainWindow.xaml.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace Common.UI.SIRTBroadcaster
-{
- using System.Windows;
-
- public partial class MainWindow : Window
- {
- public MainWindow() => this.InitializeComponent();
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Models/InitInspectionM.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Models/InitInspectionM.cs
deleted file mode 100644
index 46928920..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Models/InitInspectionM.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Models
-{
- using Common.Hardware.WaterMeter.eRegister;
-
- using System.Collections.Generic;
-
- public class InitInspectionM
- {
- private ProgrammingBatch programmingBatch;
-
- internal void InitProgramming(ProgrammingBatch programmingBatch)
- => this.programmingBatch = programmingBatch;
-
- internal IEnumerable> ProgrammingTasks()
- => null;
-
- internal void StartProgramming()
- {
-
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Models/Result.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Models/Result.cs
deleted file mode 100644
index 421af9c1..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Models/Result.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Models
-{
- using System;
-
- public enum Result : Byte
- {
- None,
- NA,
- Processing,
- Completed,
- Succes,
- Warning,
- Fail,
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Models/SIRTBroadcasterModel.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Models/SIRTBroadcasterModel.cs
deleted file mode 100644
index 1819d40f..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Models/SIRTBroadcasterModel.cs
+++ /dev/null
@@ -1,139 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Models
-{
- using Common.Hardware.Interfaces.Ports;
- using Common.Hardware.Interfaces.Ports.SIRT;
- using Common.UI.SIRTBroadcaster.Utilities;
-
- using NLog;
-
- using System;
-
- public partial class SIRTBroadcasterModel
- {
- private readonly SIRTBroadcaster broadcaster;
- private readonly ILogger logger;
-
- public SIRTBroadcasterModel(String portName, Int32 timeout)
- {
- this.logger = Appsettings.CreateNLogger(nameof(SIRTBroadcaster));
- this.broadcaster = new SIRTBroadcaster(new SerialPortSettings
- {
- BaudRate = SerialPortBaudRate.X115200,
- DataBits = SerialPortDataBits.X8,
- Parity = SerialPortParity.None,
- PortName = portName,
- StopBits = SerialPortStopBits.One,
- RWTimeout = timeout
- });
- this.broadcaster.Logging += text => this.logger.Trace(text);
- }
-
- public Int32 Frequency => this.broadcaster?.MHz ?? 0;
-
- public String Id => this.broadcaster?.SIRTID ?? String.Empty;
-
- public Boolean IsConnected => this.broadcaster?.IsOpen ?? false;
-
- public event Action DeviceAvailable
- {
- add => this.broadcaster.EndpointAvailable += value;
- remove => this.broadcaster.EndpointAvailable -= value;
- }
-
- //public event Action PamPoolChanged
- //{
- // add => this.broadcaster.PamPoolChanged += value;
- // remove => this.broadcaster.PamPoolChanged -= value;
- //}
-
- public event Action ProgrammingDone;
-
- public void Activate() => this.broadcaster.Open();
-
- public void Deactivate() => this.broadcaster.Close();
-
- internal void StartProgramming()
- {
- //var awaiter = new ManualResetEventSlim();
- //var request = new WritePamRequest
- //{
- // Address = 319020416,
- // DelPamSemi = true,
- // Payload = new Byte[]
- // {
- // 0x35, 0x13, 0x03, 0xDD, 0x7f,
- // 0x43, 0x03, 0x63, 0x93, 0x73, 0x22
- // }
- //};
- //var task = new WritePamTask(request);
-
- //task.Done += _ => awaiter.Set();
- //task.Cancelled += _ => awaiter.Set();
- //task.Logging += content =>
- //{
- // this.ProgrammingDone?.Invoke(task.Address, content);
- //};
-
- //this.broadcaster.Run(task);
-
- //awaiter.Wait();
- //awaiter.Reset();
-
- //request = new WritePamRequest
- //{
- // Address = task.Address,
- // DelPamSemi = true,
- // Payload = new Byte[]
- // {
- // 0x1F, 0x01, 0x08,
- // 0x43, 0x03, 0x63, 0x93, 0x73, 0x22
- // }
- //};
- //task = new WritePamTask(request);
-
- //var payload = new ChangeWakeUp()
- //{
- // Mode = WakeUpMode.StayAwake
- //}
- //.Append(new ChangeLATWindows
- //{
- // N = 0
- //})
- //.Append(new WMBusMode
- //{
- // WMBusEnabled = true,
- // InstallationModeEnabled = true,
- // EncryptionEnabled = true,
- //})
- //.Append(new ChangeTransmission
- //{
- // LatWindowIntervalCount = 0,
- // LatTXIntervalSeconds = 3
- //})
- //.Append(new ProvidePin
- //{
- // AuthLevel = AuthLevel.II
- //});
-
- //var request = new WritePamRequest
- //{
- // Address = 319020415,
- // WakeUpCmd = true,
- // DelPamSemi = true,
- // Payload = payload
- //};
-
- //var task = new WritePamTask(request);
- //task.Done += _ => awaiter.Set();
- //task.Cancelled += _ => awaiter.Set();
- //task.Logging += content =>
- //{
- // this.ProgrammingDone?.Invoke(task.RequestAddress, content);
- //};
-
- //this.broadcaster.Run(task);
-
- //awaiter.Wait();
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Models/WritePamTask.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Models/WritePamTask.cs
deleted file mode 100644
index d5f27c32..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Models/WritePamTask.cs
+++ /dev/null
@@ -1,90 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Models
-{
- using Common.Hardware.Interfaces.Ports.SIRT;
- using Common.Hardware.Interfaces.Ports.SIRT.Requests;
- using Common.Hardware.Interfaces.Ports.SIRT.Responses;
- using Common.Hardware.WaterMeter.eRegister;
- using Common.Utils.Extensions;
-
- using Newtonsoft.Json;
-
- using System;
- using System.Collections.Generic;
-
- public class WritePamTask : SIRTTask
- {
- public WritePamTask(UInt32 timeoutSeconds = 60) : base(timeoutSeconds)
- {
- }
-
- public event Action Logging;
-
- public SIRTRequest Request => this.request;
-
- public ACKN ACKN { get; private set; }
-
- public LAT LAT { get; private set; }
-
- public DEBUG DEBUG { get; private set; }
-
- public SEMI SEMI { get; private set; }
-
- public ICollection Bups { get; } = new List();
-
- protected override Boolean FromAirReceived(FromAirResponse response)
- {
- var payload = response.Payload;
- var length = response.Payload.Length;
-
- if (length == 13)
- {
- var bup = new LAT(payload);
-
- if (bup.AppCode == AppCode.LAT)
- {
- this.LAT = bup;
-
- if (this.request.Payload[0] == 0x35)
- {
- var oldAddress = this.Address;
- var newAddress = this.request.Payload.ToUInt32BigEndian(1);
-
- if (oldAddress != newAddress)
- {
- this.NotifyAddressChanged(oldAddress, newAddress);
- }
- }
- }
- else
- {
- this.Bups.Add(bup);
- }
- }
- else if (length == 52)
- {
- this.DEBUG = new DEBUG(payload);
- }
- else if (length == 91)
- {
- this.SEMI = new SEMI(payload, response.MHz);
- }
- else
- {
- // TODO:
- }
-
- this.Logging.Invoke(JsonConvert.SerializeObject(this, Formatting.Indented));
-
- return this.SEMI != null;
- }
-
- protected override Boolean AcknOrAnswerReceived(AcknOrAnswerResponse response)
- {
- this.ACKN = new ACKN(response);
-
- this.Logging.Invoke(JsonConvert.SerializeObject(this, Formatting.Indented));
-
- return base.AcknOrAnswerReceived(response);
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/AssemblyInfo.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Properties/AssemblyInfo.cs
deleted file mode 100644
index f459f9e5..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-using System.Reflection;
-using System.Resources;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Windows;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("Common.UI.SIRTBroadcaster")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("Common.UI.SIRTBroadcaster")]
-[assembly: AssemblyCopyright("Copyright © 2024")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-//In order to begin building localizable applications, set
-//CultureYouAreCodingWith in your .csproj file
-//inside a . For example, if you are using US english
-//in your source files, set the to en-US. Then uncomment
-//the NeutralResourceLanguage attribute below. Update the "en-US" in
-//the line below to match the UICulture setting in the project file.
-
-//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
-
-
-[assembly: ThemeInfo(
- ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
- //(used if a resource is not found in the page,
- // or application resource dictionaries)
- ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
- //(used if a resource is not found in the page,
- // app, or any theme specific resource dictionaries)
-)]
-
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Resources.Designer.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Resources.Designer.cs
deleted file mode 100644
index 6e2083cb..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Resources.Designer.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-//------------------------------------------------------------------------------
-//
-// This code was generated by a tool.
-// Runtime Version:4.0.30319.42000
-//
-// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
-//
-//------------------------------------------------------------------------------
-
-namespace Common.UI.SIRTBroadcaster.Properties
-{
-
-
- ///
- /// A strongly-typed resource class, for looking up localized strings, etc.
- ///
- // This class was auto-generated by the StronglyTypedResourceBuilder
- // class via a tool like ResGen or Visual Studio.
- // To add or remove a member, edit your .ResX file then rerun ResGen
- // with the /str option, or rebuild your VS project.
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- internal class Resources
- {
-
- private static global::System.Resources.ResourceManager resourceMan;
-
- private static global::System.Globalization.CultureInfo resourceCulture;
-
- [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal Resources()
- {
- }
-
- ///
- /// Returns the cached ResourceManager instance used by this class.
- ///
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Resources.ResourceManager ResourceManager
- {
- get
- {
- if ((resourceMan == null))
- {
- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Common.UI.SIRTBroadcaster.Properties.Resources", typeof(Resources).Assembly);
- resourceMan = temp;
- }
- return resourceMan;
- }
- }
-
- ///
- /// Overrides the current thread's CurrentUICulture property for all
- /// resource lookups using this strongly typed resource class.
- ///
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Globalization.CultureInfo Culture
- {
- get
- {
- return resourceCulture;
- }
- set
- {
- resourceCulture = value;
- }
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Resources.resx b/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Resources.resx
deleted file mode 100644
index af7dbebb..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Resources.resx
+++ /dev/null
@@ -1,117 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- text/microsoft-resx
-
-
- 2.0
-
-
- System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
- System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
-
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Settings.Designer.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Settings.Designer.cs
deleted file mode 100644
index 0869499e..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Settings.Designer.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-//------------------------------------------------------------------------------
-//
-// This code was generated by a tool.
-// Runtime Version:4.0.30319.42000
-//
-// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
-//
-//------------------------------------------------------------------------------
-
-namespace Common.UI.SIRTBroadcaster.Properties
-{
-
-
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
- internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
- {
-
- private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
-
- public static Settings Default
- {
- get
- {
- return defaultInstance;
- }
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Settings.settings b/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Settings.settings
deleted file mode 100644
index 033d7a5e..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Properties/Settings.settings
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/Appsettings.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/Appsettings.cs
deleted file mode 100644
index 4bbc6460..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/Appsettings.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Utilities
-{
- using NLog;
- using NLog.Config;
- using NLog.Targets;
-
- using System;
- using System.Configuration;
-
- public class Appsettings
- {
- private static Configuration Configuration => ConfigurationManager.OpenExeConfiguration(typeof(Appsettings).Assembly.Location);
-
- private static AppSettingsSection AppSettings => Configuration.AppSettings;
-
- private static String AppSettingsSectionName => AppSettings.SectionInformation.Name;
-
- public static readonly Appsettings Current = new Appsettings();
-
- public Appsettings() { }
-
- public String this[String key] => Value(key);
-
- internal static String Value(String settingKey)
- {
- ConfigurationManager.RefreshSection(AppSettingsSectionName);
-
- return AppSettings.Settings[settingKey].Value ?? String.Empty;
- }
-
- internal static ILogger CreateNLogger(string name)
- {
- LogManager.Configuration = new LoggingConfiguration();
- LogManager.ThrowConfigExceptions = true;
- LogManager.ThrowExceptions = true;
- LogManager.AutoShutdown = true;
-
- LogManager.Configuration.AddTarget(new FileTarget(name)
- {
- CreateDirs = true,
- KeepFileOpen = true,
- FileName = $"${{CurrentDir}}/{name}/{DateTime.Now:yyyy-MM-dd}.txt"
- });
-
- LogManager.Configuration.AddRule(LogLevel.Trace, LogLevel.Fatal, name);
- LogManager.LogFactory.ReconfigExistingLoggers(true);
- LogManager.ReconfigExistingLoggers(true);
-
- return LogManager.GetLogger(name);
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/BooleanToVisibilityConverter.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/BooleanToVisibilityConverter.cs
deleted file mode 100644
index 311ae7f4..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/BooleanToVisibilityConverter.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Utilities
-{
- using System;
- using System.Globalization;
- using System.Windows;
- using System.Windows.Data;
-
- public class BooleanToVisibilityConverter : IValueConverter
- {
- public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
- {
- if (value is Boolean _bool && _bool)
- {
- return Visibility.Visible;
- }
-
- return Visibility.Collapsed;
- }
-
- public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/CompilerServices.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/CompilerServices.cs
deleted file mode 100644
index 698b37d5..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/CompilerServices.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
- public class CallerMemberNameAttribute : Attribute
- {
- }
-
- [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
- public class CallerFilePathAttribute : Attribute
- {
- }
-
- [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
- public class CallerLineNumberAttribute : Attribute
- {
- }
-}
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToBackgroundConverter.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToBackgroundConverter.cs
deleted file mode 100644
index 8b7d246f..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToBackgroundConverter.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Utilities
-{
- using Common.UI.SIRTBroadcaster.Models;
-
- using System;
- using System.Globalization;
- using System.Windows.Data;
- using System.Windows.Media;
-
- public class ResultToBackgroundConverter : IValueConverter
- {
- public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
- {
- var color = Brushes.White;
-
- //if (value is Result result)
- //{
- // if (result == Result.Succes)
- // {
- // color = Brushes.LightGreen;
- // }
- // else if (result == Result.Fail)
- // {
- // color = Brushes.LightSalmon;
- // }
- // else if (result == Result.Warning)
- // {
- // color = Brushes.LightYellow;
- // }
- // else if (result == Result.Processing)
- // {
- // color = Brushes.AliceBlue;
- // }
- // else if (result == Result.NA )
- // {
- // color = Brushes.LightGray;
- // }
- //}
-
- return color;
- }
-
- public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToForegroundConverter.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToForegroundConverter.cs
deleted file mode 100644
index aaae87d1..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToForegroundConverter.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Utilities
-{
- using Common.UI.SIRTBroadcaster.Models;
-
- using System;
- using System.Globalization;
- using System.Windows.Data;
- using System.Windows.Media;
-
- public class ResultToForegroundConverter : IValueConverter
- {
- public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
- {
- var color = Brushes.White;
-
- if (value is Result result)
- {
- if (result == Result.Succes)
- {
- color = Brushes.Green;
- }
- else if (result == Result.Fail)
- {
- color = Brushes.Red;
- }
- else if (result == Result.Warning)
- {
- color = Brushes.Orange;
- }
- }
-
- return color;
- }
-
- public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToStringConverter.cs b/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToStringConverter.cs
deleted file mode 100644
index 29e9136d..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/Utilities/ResultToStringConverter.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.Utilities
-{
- using Common.UI.SIRTBroadcaster.Models;
-
- using System;
- using System.Globalization;
- using System.Windows.Data;
-
- public class ResultToStringConverter : IValueConverter
- {
- public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
- {
- var text = default(String);
-
- if (value is Result result)
- {
- if (result == Result.Succes)
- {
- text = "✓";
- }
- else if (result == Result.Fail)
- {
- text = "✘";
- }
- else if (result == Result.Warning)
- {
- text = "❗";
- }
- }
-
- return text;
- }
-
- public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitInspectionTaskVM.cs b/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitInspectionTaskVM.cs
deleted file mode 100644
index 18b67087..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitInspectionTaskVM.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.ViewModels
-{
- public class InitInspectionTaskVM
- {
- }
-}
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitInspectionVM.cs b/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitInspectionVM.cs
deleted file mode 100644
index 8bb4aae8..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitInspectionVM.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.ViewModels
-{
- using Common.Hardware.WaterMeter.eRegister;
- using Common.UI.SIRTBroadcaster.Models;
-
- using System;
- using System.Collections.ObjectModel;
-
- public class InitInspectionVM : VM
- {
- private readonly InitInspectionM model;
-
- public InitInspectionVM()
- {
- this.model = new InitInspectionM();
- this.Tasks = new ObservableCollection();
- }
-
- public event Action Shutdown;
-
- public ObservableCollection Tasks { get; }
-
- public void InitInspection(ProgrammingBatch programmingBatch)
- {
- this.model.InitProgramming(programmingBatch);
-
- foreach (var tasks in this.model.ProgrammingTasks())
- {
-
- }
- }
-
- internal void StartProgramming()
- {
- this.model.StartProgramming();
- this.Shutdown?.Invoke();
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitResultVM.cs b/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitResultVM.cs
deleted file mode 100644
index 844fee1b..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/InitResultVM.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.ViewModels
-{
- using Common.UI.SIRTBroadcaster.Models;
-
- using System;
-
- public class InitResultVM : VM
- {
- private Int32 serialNo;
- public Int32 SerialNo
- {
- get => this.serialNo;
- set => this.Set(() => this.serialNo = value);
- }
-
- private Int32 address;
- public Int32 Address
- {
- get => this.address;
- set => this.Set(() => this.address = value);
- }
-
- private Result wakeup = Result.Succes;
- public Result WakeUp
- {
- get => this.wakeup;
- set => this.Set(() => this.wakeup = value);
- }
-
- private Result txInterval = Result.Warning;
- public Result TxInterval
- {
- get => this.txInterval;
- set => this.Set(() => this.txInterval = value);
- }
-
- private Result latInterval = Result.Fail;
- public Result LatInterval
- {
- get => this.latInterval;
- set => this.Set(() => this.latInterval = value);
- }
-
- private Result mbus = Result.NA;
- public Result Mbus
- {
- get => this.mbus;
- set => this.Set(() => this.mbus = value);
- }
-
- private Result setup = Result.Processing;
- public Result Setup
- {
- get => this.setup;
- set => this.Set(() => this.setup = value);
- }
-
- private Result reading;
- public Result Reading
- {
- get => this.reading;
- set => this.Set(() => this.reading = value);
- }
-
- private Result led;
- public Result LED
- {
- get => this.led;
- set => this.Set(() => this.led = value);
- }
-
- private Boolean skipChecks;
- public Boolean SkipChecks
- {
- get => this.skipChecks;
- set => this.Set(() => this.skipChecks = value);
- }
-
- private Result batteryVoltage;
- public Result BatteryVoltage
- {
- get => this.batteryVoltage;
- set => this.Set(() => this.batteryVoltage = value);
- }
-
- private Result batteryRemaining;
- public Result BatteryRemaining
- {
- get => this.batteryRemaining;
- set => this.Set(() => this.batteryRemaining = value);
- }
-
- private Result fwVersion;
- public Result FWVersion
- {
- get => this.fwVersion;
- set => this.Set(() => this.fwVersion = value);
- }
-
- private Result rebootCounter;
- public Result RebootCounter
- {
- get => this.rebootCounter;
- set => this.Set(() => this.rebootCounter = value);
- }
-
- private Result meterType;
- public Result MeterType
- {
- get => this.meterType;
- set => this.Set(() => this.meterType = value);
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/SIRTBroadcasterViewModel.cs b/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/SIRTBroadcasterViewModel.cs
deleted file mode 100644
index 8197640f..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/SIRTBroadcasterViewModel.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.ViewModels
-{
- using Common.UI.SIRTBroadcaster.Models;
- using Common.UI.SIRTBroadcaster.Utilities;
-
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Threading.Tasks;
- using System.Windows.Input;
-
- public class SIRTBroadcasterViewModel : VM
- {
- private readonly SortedDictionary devices;
- private readonly SIRTBroadcasterModel model;
-
- public SIRTBroadcasterViewModel()
- {
- App.Started += App_Started;
- App.Exited += App_Exited;
-
- var portName = Appsettings.Value("SIRT.PortName");
- var _timeout = Appsettings.Value("SIRT.RWTimeout");
- var parsed = Int32.TryParse(_timeout, out var timeout);
-
- this.model = new SIRTBroadcasterModel(portName, parsed ? timeout : 3000);
- this.model.DeviceAvailable += this.Model_DeviceAvailable;
- // this.model.PamPoolChanged += this.BroadcasterModel_PamPoolChanged;
-
- this.devices = new SortedDictionary();
- this.StartProgramming = new Command(this.StartProgrammingHandler);
- }
-
- private String sirtIdentity;
- public String SIRTIdentity
- {
- get => this.sirtIdentity;
- set => this.Set(() => this.sirtIdentity = value);
- }
-
- private String programming;
- public String Programming
- {
- get => this.programming;
- set => this.Set(() => this.programming = value);
- }
-
- private Int32 availableAddressesCount;
- public Int32 AvailableDevicesCount
- {
- get => this.availableAddressesCount;
- set => this.Set(() => this.availableAddressesCount = value);
- }
-
- public ICommand StartProgramming { get; }
-
- public ObservableCollection PamPool { get; }
- = new ObservableCollection { 0, 0, 0, 0, 0 };
-
- public ObservableCollection AvailableDevices { get; }
- = new ObservableCollection();
-
- private void App_Exited() => this.model.Deactivate();
-
- private void App_Started() => Task.Factory.StartNew(() =>
- {
- this.model.Activate();
-
- this.SIRTIdentity = $"Pam Pool of SIRT: {this.model.Id} - {this.model.Frequency} MHz";
- });
-
- private void Model_DeviceAvailable(UInt32 address)
- => App.Invoke(() =>
- {
- this.devices[address] = true;
- this.RefreshAvailableDevices();
- });
-
- private void RefreshAvailableDevices()
- {
- this.AvailableDevices.Clear();
-
- foreach (var key in this.devices.Keys)
- {
- this.AvailableDevices.Add(key);
- }
-
- this.AvailableDevicesCount = this.AvailableDevices.Count;
- }
-
- private void StartProgrammingHandler()
- {
- void LogProgramming(UInt32 address, String log) => this.Programming += $"{Environment.NewLine}{address}: {log}";
-
- this.model.ProgrammingDone += LogProgramming;
-
- Task.Factory
- .StartNew(this.model.StartProgramming)
- .ContinueWith(_ => this.model.ProgrammingDone -= LogProgramming);
- }
-
- private void BroadcasterModel_PamPoolChanged(UInt32[] addressesInPamPool)
- {
- var length = addressesInPamPool.Length;
-
- for (var i = 0; i < length; i++)
- {
- App.Invoke(() => this.PamPool[i] = addressesInPamPool[i]);
- }
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/VM.cs b/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/VM.cs
deleted file mode 100644
index 53c15d53..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/ViewModels/VM.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-namespace Common.UI.SIRTBroadcaster.ViewModels
-{
- using System;
- using System.ComponentModel;
- using System.Runtime.CompilerServices;
- using System.Windows.Input;
-
- public abstract class VM : INotifyPropertyChanged, IDisposable
- {
- protected VM() => App.Exited += this.Dispose;
-
- public event PropertyChangedEventHandler PropertyChanged;
-
- public virtual void Dispose() => App.Exited -= this.Dispose;
-
- protected void Invoke(Action action) => App.Current.Dispatcher.Invoke(action);
-
- protected void NotifyPropertyChanged([CallerMemberName] string property = "")
- {
- this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
- }
-
- protected void Set(Action setExpression, [CallerMemberName] string property = "")
- {
- setExpression?.Invoke();
- this.NotifyPropertyChanged(property);
- }
-
- protected class Command : ICommand
- {
- private readonly Action executable;
-
- public Command(Action executable)
- {
- this.executable = executable;
- }
-
- public event EventHandler CanExecuteChanged
- {
- add => CommandManager.RequerySuggested += value;
- remove => CommandManager.RequerySuggested -= value;
- }
-
- public bool CanExecute(object _)
- {
- return this.executable != null;
- }
-
- public void Execute(object _)
- {
- this.executable?.Invoke();
- }
- }
-
- protected class Command : ICommand
- {
- private readonly Action executable;
-
- public Command(Action executable)
- {
- this.executable = executable;
- }
-
- public event EventHandler CanExecuteChanged
- {
- add => CommandManager.RequerySuggested += value;
- remove => CommandManager.RequerySuggested -= value;
- }
-
- public bool CanExecute(object _)
- {
- return this.executable != null;
- }
-
- public void Execute(object parameter)
- {
- this.executable?.Invoke(parameter is T t ? t : default(T));
- }
- }
- }
-}
diff --git a/Common/Ui/Common.UI.SIRTBroadcaster/packages.config b/Common/Ui/Common.UI.SIRTBroadcaster/packages.config
deleted file mode 100644
index ec30915e..00000000
--- a/Common/Ui/Common.UI.SIRTBroadcaster/packages.config
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.VFM/Common.UI.VFM.csproj b/Common/Ui/Common.UI.VFM/Common.UI.VFM.csproj
index d5fe69e2..3ca91531 100644
--- a/Common/Ui/Common.UI.VFM/Common.UI.VFM.csproj
+++ b/Common/Ui/Common.UI.VFM/Common.UI.VFM.csproj
@@ -57,16 +57,16 @@
false
- 0F55F7C5256A0679A793CF846EE16C762E09517E
+ 2AAD7D379BFB7F46CA9B0F35907CFDA28F27D632
- Common.UI.VFM_TemporaryKey.pfx
+ Common.UI.VFM_1_TemporaryKey.pfx
true
- true
+ false
@@ -151,7 +151,6 @@
Resources.Designer.cs
-
SettingsSingleFileGenerator
Settings.Designer.cs
diff --git a/Common/Ui/Common.UI.WPF/App.xaml b/Common/Ui/Common.UI.WPF/App.xaml
index a46f7539..903771f7 100644
--- a/Common/Ui/Common.UI.WPF/App.xaml
+++ b/Common/Ui/Common.UI.WPF/App.xaml
@@ -1,7 +1,10 @@
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:In="clr-namespace:Common.UI.WPF.Infrastructure"
+ StartupUri="MainWindow.xaml">
-
+
+
diff --git a/Common/Ui/Common.UI.WPF/App.xaml.cs b/Common/Ui/Common.UI.WPF/App.xaml.cs
index b03ad8cd..71043ab4 100644
--- a/Common/Ui/Common.UI.WPF/App.xaml.cs
+++ b/Common/Ui/Common.UI.WPF/App.xaml.cs
@@ -1,52 +1,40 @@
namespace Common.UI.WPF
{
using System;
- using System.Configuration;
+ using System.Diagnostics;
using System.Windows;
public partial class App : Application
{
- public static readonly AppConfig Appsettings = AppConfig.Current;
- public static Boolean IsActivated;
-
- public static event Action Activate;
- public static event Action Deactivate;
-
- protected override void OnExit(ExitEventArgs e)
- => Deactivate?.Invoke();
-
- protected override void OnActivated(EventArgs e)
+ protected override void OnStartup(StartupEventArgs args)
{
- base.OnActivated(e);
+ var currentProcess = Process.GetCurrentProcess();
+ var currentProcessName = currentProcess.ProcessName;
+ var currentProcessId = currentProcess.Id;
- if (!IsActivated)
+ try
{
- Activate?.Invoke();
-
- IsActivated = true;
+ foreach (var _process in Process.GetProcessesByName(currentProcessName))
+ {
+ if (_process.Id != currentProcessId)
+ {
+ try
+ {
+ _process.Kill();
+ }
+ catch (Exception e)
+ {
+ MessageBox.Show(e.StackTrace, e.Message);
+ }
+ }
+ }
}
- }
-
- public class AppConfig
- {
- private static readonly Configuration ExeConfiguration = ConfigurationManager.OpenExeConfiguration(typeof(App).Assembly.Location);
-
- private AppConfig()
+ catch (Exception e)
{
+ MessageBox.Show(e.StackTrace, e.Message);
}
- public String this[String key] => GetSetting(key);
-
- private static String GetSetting(String setting)
- {
- var appsettingsSectionName = ExeConfiguration.AppSettings.SectionInformation.Name;
-
- ConfigurationManager.RefreshSection(appsettingsSectionName);
-
- return ExeConfiguration.AppSettings.Settings[setting]?.Value ?? String.Empty;
- }
-
- public static AppConfig Current = new AppConfig();
+ base.OnStartup(args);
}
}
}
diff --git a/Common/Ui/Common.UI.WPF/Common.UI.WPF.csproj b/Common/Ui/Common.UI.WPF/Common.UI.WPF.csproj
index 7b237fd5..dd703dd1 100644
--- a/Common/Ui/Common.UI.WPF/Common.UI.WPF.csproj
+++ b/Common/Ui/Common.UI.WPF/Common.UI.WPF.csproj
@@ -23,7 +23,7 @@
DEBUG;TRACE
prompt
4
- IDE0003;IDE0049;
+ IDE0003;IDE0049;IDE1006;
AnyCPU
@@ -55,26 +55,31 @@
MSBuild:Compile
Designer
-
- EregisterInit.xaml
-
-
- EregisterRunCommands.xaml
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
-
- MSBuild:Compile
- Designer
-
+
+ eRegisterPruefungInitialisierungView.xaml
+
+
+ MainWindowView.xaml
+
MSBuild:Compile
Designer
@@ -87,9 +92,13 @@
MainWindow.xaml
Code
-
- MSBuild:Compile
+
Designer
+ MSBuild:Compile
+
+
+ Designer
+ MSBuild:Compile
@@ -117,10 +126,18 @@
+
+ {F408DE9E-01E6-4CFF-AE79-B572B0674FA2}
+ Common.Hardware.Interfaces.Ports.SirtBroadcaster
+
{4E8BB839-D40A-488C-88CE-F21811F1F476}
Common.Hardware.WaterMeter.eRegister
+
+ {62490923-cd17-45a6-b79f-a027927c75b5}
+ Common.Logic.Extensions.SQL
+
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.WPF/EregisterInit.xaml b/Common/Ui/Common.UI.WPF/EregisterInit.xaml
deleted file mode 100644
index c129cf7a..00000000
--- a/Common/Ui/Common.UI.WPF/EregisterInit.xaml
+++ /dev/null
@@ -1,174 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Common/Ui/Common.UI.WPF/EregisterInit.xaml.cs b/Common/Ui/Common.UI.WPF/EregisterInit.xaml.cs
deleted file mode 100644
index 163b7055..00000000
--- a/Common/Ui/Common.UI.WPF/EregisterInit.xaml.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace Common.UI.WPF
-{
- using System.Windows;
-
- public partial class EregisterInit : Window
- {
- public EregisterInit() => this.InitializeComponent();
- }
-}
diff --git a/Common/Ui/Common.UI.WPF/EregisterRunCommands.xaml b/Common/Ui/Common.UI.WPF/EregisterRunCommands.xaml
deleted file mode 100644
index a9702c31..00000000
--- a/Common/Ui/Common.UI.WPF/EregisterRunCommands.xaml
+++ /dev/null
@@ -1,176 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Common/Ui/Common.UI.WPF/EregisterRunCommands.xaml.cs b/Common/Ui/Common.UI.WPF/EregisterRunCommands.xaml.cs
deleted file mode 100644
index 2001e320..00000000
--- a/Common/Ui/Common.UI.WPF/EregisterRunCommands.xaml.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace Common.UI.WPF
-{
- using System.Windows;
-
- public partial class EregisterRunCommands : Window
- {
- public EregisterRunCommands() => this.InitializeComponent();
- }
-}
diff --git a/Common/Ui/Common.UI.WPF/Infrastructure/Appsettings.cs b/Common/Ui/Common.UI.WPF/Infrastructure/Appsettings.cs
new file mode 100644
index 00000000..56a0203b
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Infrastructure/Appsettings.cs
@@ -0,0 +1,27 @@
+namespace Common.UI.WPF.Infrastructure
+{
+ using System;
+ using System.Configuration;
+
+ public class Appsettings
+ {
+ private static readonly Configuration ExeConfiguration = ConfigurationManager.OpenExeConfiguration(typeof(App).Assembly.Location);
+
+ private Appsettings()
+ {
+ }
+
+ public String this[String key] => GetSetting(key);
+
+ private static String GetSetting(String setting)
+ {
+ var appsettingsSectionName = ExeConfiguration.AppSettings.SectionInformation.Name;
+
+ ConfigurationManager.RefreshSection(appsettingsSectionName);
+
+ return ExeConfiguration.AppSettings.Settings[setting]?.Value ?? String.Empty;
+ }
+
+ public static Appsettings Current = new Appsettings();
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Infrastructure/Auftrag.cs b/Common/Ui/Common.UI.WPF/Infrastructure/Auftrag.cs
new file mode 100644
index 00000000..9362b757
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Infrastructure/Auftrag.cs
@@ -0,0 +1,101 @@
+namespace Common.UI.WPF.Infrastructure
+{
+ using Common.Hardware.WaterMeter.eRegister;
+ using Common.Logic.Extensions.SQL;
+ using Common.Logic.Extensions.SQL.Interfaces;
+ using Common.UI.WPF.Models;
+
+ using System;
+ using System.Collections.Generic;
+
+ public class Auftrag
+ {
+ private static readonly ISQLConnection sqlConnection = SQLConnection.CreateSQLConnection(Appsettings.Current["PS.ConnectionString"]);
+
+ internal static IEnumerable All_eRegister_Shared_ByRunno(Int32 scharedId)
+ => sqlConnection
+ .CreateCommand($@"
+ SELECT P2000_Shared_Id
+ , Slotno
+ , Serialno
+ , RadioAddress
+ , FinalAddress
+ , IsSealed
+ , RadioKey
+ , Parameters
+ FROM eRegister_Shared
+ WHERE P2000_Shared_Id = @{nameof(scharedId)}
+ ORDER BY Slotno")
+ .SetParameter(nameof(scharedId), scharedId)
+ .ExecuteReader(ReadJusteRegisterParameterSet);
+
+ internal static ParameterSet eRegister_Shared_ByRunno_Slotno(Int32 scharedId, Int32 slotno)
+ => sqlConnection
+ .CreateCommand($@"
+ SELECT P2000_Shared_Id
+ , Slotno
+ , Serialno
+ , RadioAddress
+ , FinalAddress
+ , IsSealed
+ , RadioKey
+ , Parameters
+ FROM eRegister_Shared
+ WHERE P2000_Shared_Id = @{nameof(scharedId)}
+ AND Slotno = @{nameof(slotno)}")
+ .SetParameter(nameof(scharedId), scharedId)
+ .SetParameter(nameof(slotno), slotno)
+ .FirstOrDefault(ReadJusteRegisterParameterSet);
+
+ internal static Boolean TryFind_P2000_Shared_Action(out Int32 psno, out Int32 sharedId, out P2000Action action)
+ {
+ psno = 0;
+ sharedId = 0;
+ action = P2000Action.None;
+
+ var succeeded = Int32.TryParse(Appsettings.Current["PS.Nr"], out psno);
+
+ if (succeeded)
+ {
+ dynamic result = sqlConnection
+ .CreateCommand($@"
+ SELECT TOP 1
+ Id
+ , Action
+ FROM P2000_Shared
+ WHERE Psno = @{nameof(psno)}
+ AND Completed = 0
+ ORDER BY Id DESC")
+ .SetParameter(nameof(psno), psno)
+ .FirstOrDefault(reader => new
+ {
+ sharedId = reader.GetValue(0),
+ action = reader.GetValue(1)
+ });
+
+ succeeded = result != null;
+
+ if (succeeded)
+ {
+ sharedId = result.sharedId;
+ action = result.action;
+ }
+ }
+
+ return succeeded;
+ }
+
+ private static ParameterSet ReadJusteRegisterParameterSet(ISQLReader reader)
+ => new ParameterSet
+ {
+ SharedId = reader.GetValue(0),
+ Slotno = reader.GetValue(1),
+ Serialno = reader.GetValue(2),
+ RadioAddress = reader.GetValue(3),
+ FinalAddress = reader.GetValue(4),
+ IsSealed = reader.GetValue(5),
+ RadioKey = reader.GetValue(6),
+ Parameters = reader.GetValue(7),
+ };
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Infrastructure/State2BackgroundConverter.cs b/Common/Ui/Common.UI.WPF/Infrastructure/State2BackgroundConverter.cs
new file mode 100644
index 00000000..b12ac93f
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Infrastructure/State2BackgroundConverter.cs
@@ -0,0 +1,46 @@
+namespace Common.UI.WPF.Infrastructure
+{
+ using Common.UI.WPF.Models;
+
+ using System;
+ using System.Globalization;
+ using System.Windows.Data;
+ using System.Windows.Media;
+
+ public class State2BackgroundConverter : IValueConverter
+ {
+ public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
+ {
+ var brush = Brushes.White;
+
+ if (value is TaskState state)
+ {
+ switch (state)
+ {
+ case TaskState.Disabled:
+ brush = Brushes.LightGray;
+ break;
+ case TaskState.None:
+ brush = Brushes.WhiteSmoke;
+ break;
+ case TaskState.Success:
+ brush = Brushes.LightGreen;
+ break;
+ case TaskState.Warning:
+ brush = Brushes.LightYellow;
+ break;
+ case TaskState.Error:
+ brush = Brushes.LightSalmon;
+ break;
+ default:
+ brush = Brushes.White;
+ break;
+ }
+ }
+
+ return brush;
+ }
+
+ public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) => value;
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Infrastructure/State2ForegroundConverter.cs b/Common/Ui/Common.UI.WPF/Infrastructure/State2ForegroundConverter.cs
new file mode 100644
index 00000000..e35670eb
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Infrastructure/State2ForegroundConverter.cs
@@ -0,0 +1,46 @@
+namespace Common.UI.WPF.Infrastructure
+{
+ using Common.UI.WPF.Models;
+
+ using System;
+ using System.Globalization;
+ using System.Windows.Data;
+ using System.Windows.Media;
+
+ public class State2ForegroundConverter : IValueConverter
+ {
+ public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
+ {
+ var brush = Brushes.White;
+
+ if (value is TaskState state)
+ {
+ switch (state)
+ {
+ case TaskState.Disabled:
+ brush = Brushes.Black;
+ break;
+ case TaskState.None:
+ brush = Brushes.Black;
+ break;
+ case TaskState.Success:
+ brush = Brushes.DarkGreen;
+ break;
+ case TaskState.Warning:
+ brush = Brushes.DarkOrange;
+ break;
+ case TaskState.Error:
+ brush = Brushes.DarkRed;
+ break;
+ default:
+ brush = Brushes.Black;
+ break;
+ }
+ }
+
+ return brush;
+ }
+
+ public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) => value;
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/MainWindow.xaml b/Common/Ui/Common.UI.WPF/MainWindow.xaml
index e4af73d7..732abcca 100644
--- a/Common/Ui/Common.UI.WPF/MainWindow.xaml
+++ b/Common/Ui/Common.UI.WPF/MainWindow.xaml
@@ -1,12 +1,20 @@
-
-
-
+ xmlns:VM="clr-namespace:Common.UI.WPF.ViewModels"
+ xmlns:Views="clr-namespace:Common.UI.WPF.Views"
+ Title="{Binding Title}">
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Common/Ui/Common.UI.WPF/Models/Contracts/IMainModel.cs b/Common/Ui/Common.UI.WPF/Models/Contracts/IMainModel.cs
new file mode 100644
index 00000000..1a3d887f
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Models/Contracts/IMainModel.cs
@@ -0,0 +1,15 @@
+namespace Common.UI.WPF.Models.Contracts
+{
+ using System;
+
+ public interface IMainModel
+ {
+ Int32 Psno { get; set; }
+
+ Int32 Runno { get; set; }
+
+ P2000Action Action { get; set; }
+
+ void LoadP2000Shared();
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Models/MainWindowModel.cs b/Common/Ui/Common.UI.WPF/Models/MainWindowModel.cs
new file mode 100644
index 00000000..ab19b053
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Models/MainWindowModel.cs
@@ -0,0 +1,30 @@
+namespace Common.UI.WPF.Models
+{
+ using Common.UI.WPF.Infrastructure;
+ using Common.UI.WPF.Models.Contracts;
+
+ using System;
+
+ public class MainWindowModel : IMainModel
+ {
+ public Int32 Psno { get; set; }
+
+ public Int32 Runno { get; set; }
+
+ public P2000Action Action { get; set; }
+
+ public void LoadP2000Shared()
+ {
+ this.Psno = -1;
+ this.Runno = -1;
+ this.Action = P2000Action.None;
+
+ if (Auftrag.TryFind_P2000_Shared_Action(out var psno, out var runno, out var action))
+ {
+ this.Psno = psno;
+ this.Runno = runno;
+ this.Action = action;
+ }
+ }
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Models/P2000Action.cs b/Common/Ui/Common.UI.WPF/Models/P2000Action.cs
new file mode 100644
index 00000000..b6c6cbc4
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Models/P2000Action.cs
@@ -0,0 +1,9 @@
+namespace Common.UI.WPF.Models
+{
+ public enum P2000Action
+ {
+ None,
+ eRegister_PruefungInitialisierung,
+ eRegister_PruefungAbschluss,
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Models/TaskModel.cs b/Common/Ui/Common.UI.WPF/Models/TaskModel.cs
new file mode 100644
index 00000000..2f339cf5
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Models/TaskModel.cs
@@ -0,0 +1,15 @@
+namespace Common.UI.WPF.Models
+{
+ using System;
+
+ public class TaskModel
+ {
+ public Int32 Column { get; set; }
+
+ public Int32 Row { get; set; }
+
+ public String Label { get; set; }
+
+ public TaskState State { get; set; }
+ }
+}
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.WPF/Models/TaskState.cs b/Common/Ui/Common.UI.WPF/Models/TaskState.cs
new file mode 100644
index 00000000..998e9a33
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Models/TaskState.cs
@@ -0,0 +1,11 @@
+namespace Common.UI.WPF.Models
+{
+ public enum TaskState
+ {
+ Disabled,
+ None,
+ Success,
+ Warning,
+ Error
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Models/eRegisterPruefungInitialisierungModel.cs b/Common/Ui/Common.UI.WPF/Models/eRegisterPruefungInitialisierungModel.cs
new file mode 100644
index 00000000..e3b4825b
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Models/eRegisterPruefungInitialisierungModel.cs
@@ -0,0 +1,117 @@
+namespace Common.UI.WPF.Models
+{
+ using Common.Hardware.WaterMeter.eRegister;
+ using Common.UI.WPF.Infrastructure;
+ using Common.UI.WPF.Models.Contracts;
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading;
+ using System.Threading.Tasks;
+
+ public class eRegisterPruefungInitialisierungModel
+ {
+ private readonly IMainModel mainModel;
+ private readonly ProgrammingBatch programmingBatch;
+
+ public eRegisterPruefungInitialisierungModel(IMainModel mainModel)
+ {
+ this.mainModel = mainModel;
+ this.programmingBatch = new ProgrammingBatch();
+ }
+
+ public event Action OnProgress;
+ public event Action Done;
+
+ public Boolean IsRunning { get; private set; }
+
+ public ICollection Tasks { get; }
+
+ public void Load()
+ {
+ if (!this.IsRunning)
+ {
+ foreach (var parameterSet in Auftrag.All_eRegister_Shared_ByRunno(this.mainModel.Runno))
+ {
+ this.programmingBatch.AddOrReplace(parameterSet);
+ }
+ }
+ }
+
+ private void ProgrammingBatch_OnProgress(Int32 slot, Int32 processno, String label, Hardware.WaterMeter.eRegister.TaskState state)
+ => this.OnProgress?.Invoke(new TaskModel
+ {
+ Column = slot,
+ Row = processno,
+ Label = label,
+ State = (TaskState)state
+ });
+
+ public void Run()
+ => Task.Factory
+ .StartNew(state =>
+ {
+ if (state is eRegisterPruefungInitialisierungModel model && !model.IsRunning)
+ {
+ model.IsRunning = true;
+ model.programmingBatch.OnProgress += model.ProgrammingBatch_OnProgress;
+
+ var portName = Appsettings.Current["SIRT.PortName"];
+
+ model.programmingBatch.StartOnCOMPort(portName);
+ model.programmingBatch.InitializeCalibration();
+ model.programmingBatch.Run();
+ }
+ }, this, CancellationToken.None)
+ .ContinueWith(task =>
+ {
+ if (task.AsyncState is eRegisterPruefungInitialisierungModel model && model.IsRunning)
+ {
+ model.programmingBatch.Stop();
+
+ model.programmingBatch.OnProgress -= model.ProgrammingBatch_OnProgress;
+ model.IsRunning = false;
+
+ model.Done?.Invoke();
+ }
+ }, CancellationToken.None);
+
+ public void Load(Int32 slotno)
+ {
+ if (!this.IsRunning)
+ {
+ var parameterSet = Auftrag.eRegister_Shared_ByRunno_Slotno(this.mainModel.Runno, slotno);
+ this.programmingBatch.AddOrReplace(parameterSet);
+ }
+ }
+
+ public void Run(Int32 slotno)
+ => Task.Factory
+ .StartNew(state =>
+ {
+ if (state is eRegisterPruefungInitialisierungModel model && !model.IsRunning)
+ {
+ model.IsRunning = true;
+ model.programmingBatch.OnProgress += model.ProgrammingBatch_OnProgress;
+
+ var portName = Appsettings.Current["SIRT.PortName"];
+
+ model.programmingBatch.StartOnCOMPort(portName);
+ model.programmingBatch.InitializeCalibration(slotno);
+ model.programmingBatch.Run(slotno);
+ }
+ }, this, CancellationToken.None)
+ .ContinueWith(task =>
+ {
+ if (task.AsyncState is eRegisterPruefungInitialisierungModel model && model.IsRunning)
+ {
+ model.programmingBatch.Stop();
+
+ model.programmingBatch.OnProgress -= model.ProgrammingBatch_OnProgress;
+ model.IsRunning = false;
+
+ model.Done?.Invoke();
+ }
+ }, CancellationToken.None);
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/ActionVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/ActionVM.cs
new file mode 100644
index 00000000..356bdf1a
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/ViewModels/ActionVM.cs
@@ -0,0 +1,33 @@
+namespace Common.UI.WPF.ViewModels
+{
+ using System;
+ using System.Windows;
+ using System.Windows.Input;
+
+ public class ActionVM : TaskVM
+ {
+ public ActionVM() : base()
+ => this.Execute = new Command(this.ExecuteAction);
+
+ public event Action Executed;
+
+ private Int32 parameter;
+ public Int32 Parameter
+ {
+ get => this.parameter;
+ set => this.Set(() => this.parameter = value);
+ }
+
+ private Visibility visibility;
+ public Visibility Visibility
+ {
+ get => this.visibility;
+ set => this.Set(() => this.visibility = value);
+ }
+
+ public ICommand Execute { get; }
+
+ private void ExecuteAction(Int32 slotno = -1)
+ => this.Executed?.Invoke(slotno);
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/EregisterInitVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/EregisterInitVM.cs
deleted file mode 100644
index f77716cf..00000000
--- a/Common/Ui/Common.UI.WPF/ViewModels/EregisterInitVM.cs
+++ /dev/null
@@ -1,251 +0,0 @@
-namespace Common.UI.WPF.ViewModels
-{
- using Common.Hardware.WaterMeter.eRegister;
-
- using System;
- using System.Collections.ObjectModel;
- using System.Threading;
- using System.Windows;
- using System.Windows.Media;
-
- public class EregisterInitVM : VM
- {
- private ProgrammingBatch programmingBatch;
- private Boolean waitingActivation;
- private String sirt;
-
- public EregisterInitVM() : base()
- {
- this.waitingActivation = true;
- this.ItemsSource = new ObservableCollection();
- }
-
- public Boolean WaitingActivation
- {
- get => this.waitingActivation;
- set => this.Set(vm => vm.waitingActivation = value);
- }
-
- public String SIRT
- {
- get => this.sirt;
- set => this.Set(vm => vm.sirt = value);
- }
-
- public ObservableCollection ItemsSource { get; }
-
- public override void Dispose()
- {
- this.programmingBatch.DeactivateSIRT();
-
- foreach (var disposable in this.ItemsSource)
- {
- disposable.Dispose();
- }
-
- base.Dispose();
- }
-
- public void Activate(ProgrammingBatch programmingBatch)
- {
- this.programmingBatch = programmingBatch;
- this.programmingBatch.Activated += this.LoadEndpoints;
- this.programmingBatch.Done += this.Shutdown;
-
- this.StartTask(this.programmingBatch.ActivateSIRT);
- }
-
- private void Shutdown(Int32 exitCode)
- {
- this.DispatcherInvoke(() =>
- {
- this.Dispose();
-
- Thread.Sleep(5000);
- App.Current.Shutdown(exitCode);
- });
- }
-
- private void LoadEndpoints(String sirtID, Int32 MHz)
- {
- this.SIRT = $"SIRT({sirtID}) - {MHz}MHz";
- this.programmingBatch.Activated -= this.LoadEndpoints;
-
- this.DispatcherInvoke(() =>
- {
- var gridRow = 0;
-
- this.AddSlots(gridRow++);
- this.AddSerialNumbers(gridRow++);
- this.AddRadioAddresses(gridRow++);
- this.AddInitTasks(gridRow++);
- this.AddSetupTasks(gridRow++);
- this.AddMeterReading(gridRow++);
- this.AddLED(gridRow++);
- this.AddChecks(gridRow++);
- });
- }
-
- private void AddSlots(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Einbauplatz",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var slot in this.programmingBatch.Slots())
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = $"{slot}",
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
- }
- }
-
- private void AddSerialNumbers(Int32 gridRow, Int32 gridColumn = 0)
- {
-
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "SerienNr",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var serialno in this.programmingBatch.SerialNumbers())
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = $"{serialno}",
- });
- }
- }
-
- private void AddRadioAddresses(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Adresse",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var address in this.programmingBatch.RadioAddresses())
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = $"{address}",
- });
- }
- }
-
- private void AddInitTasks(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "WUP|LAT|TXIV|MBUS",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.InitForInspection())
- {
- this.ItemsSource.Add(new EregisterTaskVM(gridRow, gridColumn++, task));
- }
- }
-
- private void AddSetupTasks(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Prüfunginitialisierung",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.InitForInspection())
- {
- this.ItemsSource.Add(new EregisterTaskVM(gridRow, gridColumn++, task));
- }
- }
-
- private void AddMeterReading(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "111111.111",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.SetDisplay111111111())
- {
- this.ItemsSource.Add(new EregisterTaskVM(gridRow, gridColumn++, task));
- }
- }
-
- private void AddLED(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "LED AN",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.StartLED())
- {
- this.ItemsSource.Add(new EregisterTaskVM(gridRow, gridColumn++, task));
- }
- }
-
- private void AddChecks(Int32 gridRow, Int32 gridColumn = 0)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Überprüfen",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var task in this.programmingBatch.DoChecks())
- {
- this.ItemsSource.Add(new EregisterTaskVM(gridRow, gridColumn++, task));
- }
- }
- }
-}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/EregisterRunCommandsVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/EregisterRunCommandsVM.cs
deleted file mode 100644
index 38e5af62..00000000
--- a/Common/Ui/Common.UI.WPF/ViewModels/EregisterRunCommandsVM.cs
+++ /dev/null
@@ -1,146 +0,0 @@
-namespace Common.UI.WPF.ViewModels
-{
- using Common.Hardware.WaterMeter.eRegister;
-
- using System;
- using System.Collections.ObjectModel;
- using System.Threading;
- using System.Windows;
- using System.Windows.Media;
-
- public class EregisterRunCommandsVM : VM
- {
- private ProgrammingBatch programmingBatch;
- private Boolean waitingActivation;
- private String sirt;
-
- public EregisterRunCommandsVM() : base()
- {
- this.waitingActivation = true;
- this.ItemsSource = new ObservableCollection();
- }
-
- public Boolean WaitingActivation
- {
- get => this.waitingActivation;
- set => this.Set(vm => vm.waitingActivation = value);
- }
-
- public String SIRT
- {
- get => this.sirt;
- set => this.Set(vm => vm.sirt = value);
- }
-
- public ObservableCollection ItemsSource { get; }
-
- public override void Dispose()
- {
- this.programmingBatch.DeactivateSIRT();
-
- foreach (var disposable in this.ItemsSource)
- {
- disposable.Dispose();
- }
-
- base.Dispose();
- }
-
- public void Activate(ProgrammingBatch programmingBatch)
- {
- this.programmingBatch = programmingBatch;
- this.programmingBatch.Activated += this.LoadEndpoints;
- this.programmingBatch.Done += this.Shutdown;
-
- this.StartTask(this.programmingBatch.ActivateSIRT);
- }
-
- private void Shutdown(Int32 exitCode)
- {
- this.DispatcherInvoke(() =>
- {
- this.Dispose();
-
- Thread.Sleep(5000);
- App.Current.Shutdown(exitCode);
- });
- }
-
- private void LoadEndpoints(String sirtID, Int32 MHz)
- {
- this.SIRT = $"SIRT({sirtID}) - {MHz}MHz";
- this.programmingBatch.Activated -= this.LoadEndpoints;
-
- this.DispatcherInvoke(() =>
- {
- var gridRow = 0;
- var first = false;
-
- foreach (var commands in this.programmingBatch.RunCommands())
- {
- var gridColumn = 0;
-
- if (!first)
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "Einbauplatz",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
-
- foreach (var slot in this.programmingBatch.Slots())
- {
- this.ItemsSource.Add(new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = $"{slot}",
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- });
- }
-
- gridRow++;
- gridColumn = 0;
- first = true;
- }
-
- var headerSet = false;
- var header = new TextVM
- {
- GridColumn = gridColumn++,
- GridRow = gridRow,
- View = "PAM -1",
- TextAlignment = TextAlignment.Right,
- FontWeight = FontWeights.SemiBold,
- Background = Brushes.WhiteSmoke
- };
-
- this.ItemsSource.Add(header);
-
- foreach (var command in commands)
- {
- if (command is null)
- {
- continue;
- }
-
- if (!headerSet)
- {
- header.View = command.FirstPamId;
- headerSet = true;
- }
-
- this.ItemsSource.Add(new EregisterTaskVM(gridRow, gridColumn++, command));
- }
-
- gridRow++;
- }
- });
- }
- }
-}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/EregisterTaskVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/EregisterTaskVM.cs
deleted file mode 100644
index e98cb819..00000000
--- a/Common/Ui/Common.UI.WPF/ViewModels/EregisterTaskVM.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-namespace Common.UI.WPF.ViewModels
-{
- using Common.Hardware.WaterMeter.eRegister;
-
- using System;
- using System.Windows.Media;
-
- public class EregisterTaskVM : GridCellVM
- {
- const String VIEW = "-----";
-
- private readonly EndpointTask task;
-
- public EregisterTaskVM(Int32 gridRow, Int32 gridColumn, EndpointTask task) : base()
- {
- this.GridRow = gridRow;
- this.GridColumn = gridColumn;
- this.task = task;
- this.task.Cancelled += this.Cancelled;
- this.task.Completed += this.Completed;
- this.task.Received += this.Received;
- this.View = VIEW;
- }
-
- public override void Dispose()
- {
- this.task.Cancelled -= this.Cancelled;
- this.task.Completed -= this.Completed;
-
- base.Dispose();
- }
-
- private void Completed()
- {
- this.Background = Brushes.LightGreen;
- this.Foreground = Brushes.DarkGreen;
-
- if (this.View == VIEW)
- {
- this.View = "OK";
- }
- }
-
- private void Cancelled()
- {
- this.Background = Brushes.LightCoral;
- this.Foreground = Brushes.DarkRed;
-
- if (this.View == VIEW)
- {
- this.View = "FEHLER";
- }
- }
-
- private void Received(String type)
- {
- this.Background = Brushes.White;
- this.Foreground = Brushes.Black;
- this.View = type;
- }
- }
-}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/GridCellVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/GridCellVM.cs
deleted file mode 100644
index c4b982d0..00000000
--- a/Common/Ui/Common.UI.WPF/ViewModels/GridCellVM.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-namespace Common.UI.WPF.ViewModels
-{
- using System;
- using System.Windows;
- using System.Windows.Media;
-
- public class GridCellVM : VM
- {
- private Int32 gridColumn;
- private Int32 gridRow;
- private String view;
- private TextAlignment textAlignment;
- private Brush background;
- private Brush foreground;
- private FontWeight fontWeight;
-
- public GridCellVM() : base()
- {
- this.Background = Brushes.White;
- this.Foreground = Brushes.Black;
- this.TextAlignment = TextAlignment.Center;
- this.FontWeight = FontWeights.Normal;
- }
-
- public String View
- {
- get => this.view;
- set => this.Set(x => x.view = value);
- }
-
- public Int32 GridColumn
- {
- get => this.gridColumn;
- set => this.Set(x => x.gridColumn = value);
- }
-
- public Int32 GridRow
- {
- get => this.gridRow;
- set => this.Set(x => x.gridRow = value);
- }
-
- public TextAlignment TextAlignment
- {
- get => this.textAlignment;
- set => this.Set(x => x.textAlignment = value);
- }
-
- public Brush Background
- {
- get => this.background;
- set => this.Set(x => x.background = value);
- }
-
- public Brush Foreground
- {
- get => this.foreground;
- set => this.Set(x => x.foreground = value);
- }
-
- public FontWeight FontWeight
- {
- get => this.fontWeight;
- set => this.Set(x => x.fontWeight = value);
- }
- }
-}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/MainWindowVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/MainWindowVM.cs
new file mode 100644
index 00000000..ce30c19d
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/ViewModels/MainWindowVM.cs
@@ -0,0 +1,57 @@
+namespace Common.UI.WPF.ViewModels
+{
+ using Common.UI.WPF.Models;
+ using Common.UI.WPF.Models.Contracts;
+
+ using System;
+
+ public class MainWindowVM : VM
+ {
+ private readonly IMainModel model = new MainWindowModel();
+
+ private P2000Action action;
+
+ public MainWindowVM() : base()
+ {
+ this.model.LoadP2000Shared();
+
+ var content = this.Content;
+
+ if (this.action != this.model.Action)
+ {
+ this.action = this.model.Action;
+
+ switch (this.action)
+ {
+ case P2000Action.eRegister_PruefungInitialisierung:
+ content = new eRegisterPruefungInitialisierungVM(this.model);
+ title = "Prüfunginitializierung_NeueVako";
+ break;
+ case P2000Action.eRegister_PruefungAbschluss:
+ content = this;
+ title = "Prüfungabschluss_NeueVako";
+ break;
+ default:
+ content = this;
+ break;
+ }
+ }
+
+ this.Content = content;
+ }
+
+ private String title;
+ public String Title
+ {
+ get => this.title;
+ set => this.Set(x => x.title = value);
+ }
+
+ private VM content;
+ public VM Content
+ {
+ get => this.content;
+ set => this.Set(x => x.content = value);
+ }
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/TaskVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/TaskVM.cs
new file mode 100644
index 00000000..48717225
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/ViewModels/TaskVM.cs
@@ -0,0 +1,37 @@
+namespace Common.UI.WPF.ViewModels
+{
+ using Common.UI.WPF.Models;
+
+ using System;
+
+ public class TaskVM : VM
+ {
+ private Int32 column;
+ public Int32 Column
+ {
+ get => this.column;
+ set => this.Set(x => x.column = value);
+ }
+
+ private Int32 row;
+ public Int32 Row
+ {
+ get => this.row;
+ set => this.Set(x => x.row = value);
+ }
+
+ private String label;
+ public String Label
+ {
+ get => this.label;
+ set => this.Set(x => x.label = value);
+ }
+
+ private TaskState state;
+ public TaskState State
+ {
+ get => this.state;
+ set => this.Set(x => x.state = value);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/TextVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/TextVM.cs
deleted file mode 100644
index f7ae1a19..00000000
--- a/Common/Ui/Common.UI.WPF/ViewModels/TextVM.cs
+++ /dev/null
@@ -1,9 +0,0 @@
-namespace Common.UI.WPF.ViewModels
-{
- public class TextVM : GridCellVM
- {
- public TextVM() : base()
- {
- }
- }
-}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/VM.cs b/Common/Ui/Common.UI.WPF/ViewModels/VM.cs
index 35333c73..9e32cc85 100644
--- a/Common/Ui/Common.UI.WPF/ViewModels/VM.cs
+++ b/Common/Ui/Common.UI.WPF/ViewModels/VM.cs
@@ -4,71 +4,19 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Input;
using System.Windows.Threading;
///
/// Base view model with notification features and commands.
///
- public abstract partial class VM : INotifyPropertyChanged, IDisposable
+ public abstract partial class VM : INotifyPropertyChanged
{
private static readonly Dispatcher dispatcher = App.Current.Dispatcher;
- private String exception;
- private Visibility exceptionVisible;
-
- ///
- /// Should be implemented in order to use Activate and Deactivate events.
- ///
- protected VM()
- {
- App.Activate += this.Activated;
-
- this.ExceptionVisible = Visibility.Collapsed;
- this.CloseException = new Command(this.CloseExceptionHanler);
- }
-
public event PropertyChangedEventHandler PropertyChanged;
- public String Exception
- {
- get => this.exception;
- protected set => this.Set(() => this.exception = value);
- }
- public Visibility ExceptionVisible
- {
- get => this.exceptionVisible;
- protected set => this.Set(() => this.exceptionVisible = value);
- }
-
- public ICommand CloseException { get; }
-
- ///
- /// Should be the last call when overriden
- ///
- public virtual void Dispose()
- {
- App.Activate -= this.Activated;
- App.Deactivate -= this.Dispose;
- }
-
- protected void DispatcherInvoke(Action action)
- {
- try
- {
- dispatcher.Invoke(action);
- }
- catch (Exception e)
- {
- this.Exception = e.ToString();
- }
- }
-
- ///
- /// Should be the first call when overriden
- ///
- protected virtual void Activated() => App.Deactivate += this.Dispose;
+ protected void DispatcherInvoke(Action action)
+ => dispatcher.Invoke(action);
protected void NotifyPropertyChanged([CallerMemberName] String property = "")
=> this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
@@ -79,22 +27,7 @@
this.NotifyPropertyChanged(property);
}
- protected void StartTask(Action action)
- => Task.Factory.StartNew(action).ContinueWith(this.Catch);
-
- protected void Catch(Task task)
- {
- if (task.Exception != null)
- {
- this.Exception = task.Exception.ToString();
- this.ExceptionVisible = Visibility.Visible;
- }
- }
-
- private void CloseExceptionHanler()
- {
- this.Exception = null;
- this.ExceptionVisible = Visibility.Collapsed;
- }
+ protected Task StartTask(Action action)
+ => Task.Factory.StartNew(action);
}
}
diff --git a/Common/Ui/Common.UI.WPF/ViewModels/eRegisterPruefungInitialisierungVM.cs b/Common/Ui/Common.UI.WPF/ViewModels/eRegisterPruefungInitialisierungVM.cs
new file mode 100644
index 00000000..8df94287
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/ViewModels/eRegisterPruefungInitialisierungVM.cs
@@ -0,0 +1,129 @@
+namespace Common.UI.WPF.ViewModels
+{
+ using Common.UI.WPF.Models;
+ using Common.UI.WPF.Models.Contracts;
+
+ using System;
+ using System.Collections.ObjectModel;
+ using System.Windows;
+
+ public class eRegisterPruefungInitialisierungVM : VM
+ {
+ const Int32 ColumnsCount = 11;
+ const Int32 RowsCount = 15;
+
+ private readonly TaskVM[,] tasks;
+ private readonly IMainModel mainModel;
+ private readonly eRegisterPruefungInitialisierungModel model;
+
+ public eRegisterPruefungInitialisierungVM()
+ {
+
+ }
+
+ public eRegisterPruefungInitialisierungVM(IMainModel mainModel) : base()
+ {
+ this.mainModel = mainModel;
+ this.model = new eRegisterPruefungInitialisierungModel(mainModel);
+ this.model.OnProgress += this.Model_OnProgress;
+ this.model.Done += this.Model_Done;
+ this.Tasks = new ObservableCollection();
+ this.tasks = new TaskVM[RowsCount, ColumnsCount];
+
+ this.ExecuteAllTasks();
+ }
+
+ public ObservableCollection Tasks { get; }
+
+ private void ExecuteAllTasks()
+ {
+ this.Tasks.Clear();
+
+ var row = 0;
+ var rowsCount = RowsCount - 1;
+
+ for (var column = 0; column < ColumnsCount; column++)
+ {
+ for (row = 0; row < rowsCount; row++)
+ {
+ this.tasks[row, column] = new TaskVM
+ {
+ State = TaskState.None,
+ Column = column,
+ Row = row,
+ };
+
+ this.Tasks.Add(this.tasks[row, column]);
+ }
+ }
+
+ for (var column = 0; column < ColumnsCount; column++)
+ {
+ var action = new ActionVM
+ {
+ Label = $"{(column == 0 ? "Alle wiederh." : $"EP{column} wiederh.")}",
+ Visibility = Visibility.Collapsed,
+ State = TaskState.None,
+ Parameter = column,
+ Column = column,
+ Row = row,
+ };
+ action.Executed += this.Action_Executed;
+ this.tasks[row, column] = action;
+
+ this.Tasks.Add(this.tasks[row, column]);
+ }
+
+ this.model.Load();
+ this.model.Run();
+ }
+
+ private void Model_OnProgress(TaskModel task)
+ {
+ this.DispatcherInvoke(() =>
+ {
+ var _task = this.tasks[task.Row, task.Column];
+ _task.Row = task.Row;
+ _task.Column = task.Column;
+ _task.Label = task.Label;
+ _task.State = task.State;
+ });
+ }
+
+ private void Model_Done()
+ {
+ var row = RowsCount - 1;
+
+ for (var column = 0; column < ColumnsCount; column++)
+ {
+ if (this.tasks[row, column] is ActionVM action)
+ {
+ action.Visibility = Visibility.Visible;
+ }
+ }
+ }
+
+ private void Action_Executed(Int32 slotno)
+ {
+ if (0 < slotno && slotno < RowsCount)
+ {
+ var column = slotno;
+ var rowsCount = RowsCount - 1;
+
+ for (var row = 1; row < rowsCount; row++)
+ {
+ var task = this.tasks[row, column];
+ task.State = TaskState.None;
+ task.Label = String.Empty;
+ }
+
+ this.model.Load(slotno);
+ this.model.Run(slotno);
+ }
+ else
+ {
+ this.ExecuteAllTasks();
+ }
+ }
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Views/MainWindowView.xaml b/Common/Ui/Common.UI.WPF/Views/MainWindowView.xaml
new file mode 100644
index 00000000..166b2cd4
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Views/MainWindowView.xaml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/Common/Ui/Common.UI.WPF/Views/MainWindowView.xaml.cs b/Common/Ui/Common.UI.WPF/Views/MainWindowView.xaml.cs
new file mode 100644
index 00000000..02ef5da4
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Views/MainWindowView.xaml.cs
@@ -0,0 +1,9 @@
+namespace Common.UI.WPF.Views
+{
+ using System.Windows.Controls;
+
+ public partial class MainWindowView : Grid
+ {
+ public MainWindowView() => this.InitializeComponent();
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/Views/eRegisterPruefungInitialisierungView.xaml b/Common/Ui/Common.UI.WPF/Views/eRegisterPruefungInitialisierungView.xaml
new file mode 100644
index 00000000..23d8094b
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Views/eRegisterPruefungInitialisierungView.xaml
@@ -0,0 +1,104 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Common/Ui/Common.UI.WPF/Views/eRegisterPruefungInitialisierungView.xaml.cs b/Common/Ui/Common.UI.WPF/Views/eRegisterPruefungInitialisierungView.xaml.cs
new file mode 100644
index 00000000..a8c34c39
--- /dev/null
+++ b/Common/Ui/Common.UI.WPF/Views/eRegisterPruefungInitialisierungView.xaml.cs
@@ -0,0 +1,9 @@
+namespace Common.UI.WPF.Views
+{
+ using System.Windows.Controls;
+
+ public partial class eRegisterPruefungInitialisierungView : Grid
+ {
+ public eRegisterPruefungInitialisierungView() => this.InitializeComponent();
+ }
+}
diff --git a/Common/Ui/Common.UI.WPF/app.config b/Common/Ui/Common.UI.WPF/app.config
index 02230d72..57e33b68 100644
--- a/Common/Ui/Common.UI.WPF/app.config
+++ b/Common/Ui/Common.UI.WPF/app.config
@@ -1,8 +1,9 @@
+
+
-
diff --git a/Common/Ui/Common.UI.WPFConnector/EregisterConnector.cs b/Common/Ui/Common.UI.WPFConnector/EregisterConnector.cs
deleted file mode 100644
index e494f2cd..00000000
--- a/Common/Ui/Common.UI.WPFConnector/EregisterConnector.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-namespace Common.UI.WPFConnector
-{
- using Common.UI.WPF;
- using Common.UI.WPF.ViewModels;
- using Hardware.WaterMeter.eRegister;
-
- using System;
- using System.Threading;
- using System.Windows;
-
- public class EregisterConnector
- {
- private readonly ProgrammingBatch programmingBatch;
-
- public EregisterConnector() : this("COM6", 1000)
- {
- }
-
- public EregisterConnector(String portName, Int32 rwTimeout) => this.programmingBatch = new ProgrammingBatch(portName, rwTimeout);
-
- public void Add(Int32 slotno, UInt32 serialno, UInt32 address) => this.programmingBatch.Add(slotno, (Int32)serialno, address);
-
- public void AddHexCommand(Int32 slotno, String command) => this.programmingBatch.AddHexCommand(slotno, command);
-
- public void InitInspection()
- {
- var manualResetEventSlim = new ManualResetEventSlim();
- var threadStartCallback = new ParameterizedThreadStart((object parameter) =>
- {
- if (parameter is ProgrammingBatch programmingBatch)
- {
- var app = new App();
- var window = new EregisterInit();
-
- if (window.DataContext is EregisterInitVM vm)
- {
- vm.Activate(programmingBatch);
- }
-
- app.Run(window);
- manualResetEventSlim.Set();
- }
- });
- var staThread = new Thread(threadStartCallback);
- staThread.SetApartmentState(ApartmentState.STA);
- staThread.Start(this.programmingBatch);
- manualResetEventSlim.Wait();
- }
-
- public void RunCommands()
- {
- var manualResetEventSlim = new ManualResetEventSlim();
- var threadStartCallback = new ParameterizedThreadStart((object parameter) =>
- {
- if (parameter is ProgrammingBatch programmingBatch)
- {
- var app = new App();
- var window = new EregisterRunCommands();
-
- if (window.DataContext is EregisterRunCommandsVM vm)
- {
- vm.Activate(programmingBatch);
- }
-
- app.Run(window);
- manualResetEventSlim.Set();
- }
- });
- var staThread = new Thread(threadStartCallback);
- staThread.SetApartmentState(ApartmentState.STA);
- staThread.Start(this.programmingBatch);
- manualResetEventSlim.Wait();
- }
-
- public static EregisterConnector CreateNew(String portName, Int32 rwTimeout) => new EregisterConnector(portName, rwTimeout);
- }
-}
diff --git a/Common/Ui/GenesisToolBox/FrmAlarmMng.Designer.cs b/Common/Ui/GenesisToolBox/FrmAlarmMng.Designer.cs
index a12ef8e4..951a51b1 100644
--- a/Common/Ui/GenesisToolBox/FrmAlarmMng.Designer.cs
+++ b/Common/Ui/GenesisToolBox/FrmAlarmMng.Designer.cs
@@ -445,7 +445,7 @@
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(59, 87);
this.button5.TabIndex = 21;
- this.button5.Text = "button5";
+ this.button5.Text = "Reset All Alarms";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
diff --git a/Common/Ui/GenesisToolBox/FrmLowLevelTools.cs b/Common/Ui/GenesisToolBox/FrmLowLevelTools.cs
index 792fa2c3..d9375b87 100644
--- a/Common/Ui/GenesisToolBox/FrmLowLevelTools.cs
+++ b/Common/Ui/GenesisToolBox/FrmLowLevelTools.cs
@@ -1121,6 +1121,9 @@ namespace Xylem.Common.Ui.GenesisToolBox
///
/// - Initial
///
+ ///
+ /// - Store configuration of POWERMON.
+ ///
private void btnFixBattery_Click(Object sender, EventArgs e)
{
if (_currentGenesis == null)
@@ -1150,6 +1153,9 @@ namespace Xylem.Common.Ui.GenesisToolBox
SetActualProcessAndLog(@"Set meter battery quantity to 2");
_currentGenesis.WriteRegister("POWERMON_BatteryQuantity", (UInt32)2);
+ SetActualProcessAndLog(@"Store configuration POWERMON");
+ _currentGenesis.WriteRegister("POWERMON_StoreConfiguration", (UInt32)1);
+
SetActualProcessAndLog(@"Trigger idle to release function to normal operation");
_currentGenesis.WriteRegister("GENESISFLOW_TriggerIdle", (UInt32)0);
diff --git a/Common/Ui/GenesisToolBox/GenesisToolBox.csproj b/Common/Ui/GenesisToolBox/GenesisToolBox.csproj
index 371c288c..7ce6dadf 100644
--- a/Common/Ui/GenesisToolBox/GenesisToolBox.csproj
+++ b/Common/Ui/GenesisToolBox/GenesisToolBox.csproj
@@ -13,9 +13,8 @@
512
true
- false
- C:\Users\SZLATEV\Desktop\GenesisToolBox\
- false
+ publish\
+ true
Disk
false
Foreground
@@ -24,10 +23,10 @@
false
false
true
- 5
+ 0
1.0.0.%2a
+ false
false
- true
true
@@ -81,12 +80,6 @@
false
true
-
- 14673934DFE995F28E9579F4A18DBDA05F7C1AFE
-
-
- GenesisToolBox_TemporaryKey.pfx
-
true
@@ -107,9 +100,7 @@
LocalIntranet
-
- Properties\app.manifest
-
+
true
bin\x64\Debug\
@@ -158,6 +149,9 @@
false
true
+
+ Properties\app.manifest
+
@@ -617,13 +611,12 @@
status.json
Always
+
-
PreserveNewest
-
@@ -783,9 +776,9 @@
-
+
False
- Microsoft .NET Framework 4 %28x86 and x64%29
+ Microsoft .NET Framework 4.8 %28x86 and x64%29
true
@@ -793,13 +786,7 @@
.NET Framework 3.5 SP1
false
-
- False
- Windows Installer 4.5
- true
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
\ No newline at end of file
+
+
diff --git a/Common/Ui/MagFluxToolBox/FrmSetup.Designer.cs b/Common/Ui/MagFluxToolBox/FrmSetup.Designer.cs
index 1b5b7b3a..8a920a47 100644
--- a/Common/Ui/MagFluxToolBox/FrmSetup.Designer.cs
+++ b/Common/Ui/MagFluxToolBox/FrmSetup.Designer.cs
@@ -48,10 +48,10 @@
this.tabPage1 = new System.Windows.Forms.TabPage();
this.btnAddRow = new System.Windows.Forms.Button();
this.dgvConfig = new System.Windows.Forms.DataGridView();
- this.tabControl1 = new System.Windows.Forms.TabControl();
this.cbxSlot = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.cbxRequestPort = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.cbxStreamingPort = new System.Windows.Forms.DataGridViewComboBoxColumn();
+ this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage4.SuspendLayout();
this.tabPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvConfig)).BeginInit();
@@ -264,16 +264,6 @@
this.dgvConfig.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DgvConfig_CellContentClick);
this.dgvConfig.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dgvConfig_DataError);
//
- // tabControl1
- //
- this.tabControl1.Controls.Add(this.tabPage1);
- this.tabControl1.Controls.Add(this.tabPage4);
- this.tabControl1.Location = new System.Drawing.Point(12, 74);
- this.tabControl1.Name = "tabControl1";
- this.tabControl1.SelectedIndex = 0;
- this.tabControl1.Size = new System.Drawing.Size(768, 387);
- this.tabControl1.TabIndex = 17;
- //
// cbxSlot
//
this.cbxSlot.HeaderText = "Slot";
@@ -289,6 +279,16 @@
this.cbxStreamingPort.HeaderText = "StreamingPort";
this.cbxStreamingPort.Name = "cbxStreamingPort";
//
+ // tabControl1
+ //
+ this.tabControl1.Controls.Add(this.tabPage1);
+ this.tabControl1.Controls.Add(this.tabPage4);
+ this.tabControl1.Location = new System.Drawing.Point(12, 74);
+ this.tabControl1.Name = "tabControl1";
+ this.tabControl1.SelectedIndex = 0;
+ this.tabControl1.Size = new System.Drawing.Size(768, 387);
+ this.tabControl1.TabIndex = 17;
+ //
// FrmSetup
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
@@ -299,7 +299,7 @@
this.Controls.Add(this.btnReload);
this.MinimumSize = new System.Drawing.Size(755, 410);
this.Name = "FrmSetup";
- this.Text = "Setup";
+ this.Text = "MagFlux ToolBox Setup";
this.Load += new System.EventHandler(this.FrmSetup_Load);
this.tabPage4.ResumeLayout(false);
this.tabPage4.PerformLayout();
diff --git a/Common/Ui/MagFluxToolBox/FrmTest.Designer.cs b/Common/Ui/MagFluxToolBox/FrmTest.Designer.cs
index 7444f704..adbc7bf9 100644
--- a/Common/Ui/MagFluxToolBox/FrmTest.Designer.cs
+++ b/Common/Ui/MagFluxToolBox/FrmTest.Designer.cs
@@ -30,10 +30,11 @@
{
this.components = new System.ComponentModel.Container();
this.grpSetup = new System.Windows.Forms.GroupBox();
+ this.btnInitPcb = new System.Windows.Forms.Button();
this.btnConnect = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.cbComSlot = new System.Windows.Forms.ComboBox();
- this.lblSensorNo = new System.Windows.Forms.Label();
+ this.lblPcbId = new System.Windows.Forms.Label();
this.tbxSensorNo = new System.Windows.Forms.TextBox();
this.lblWaitingForMeterResponse = new System.Windows.Forms.Label();
this.lblOverall = new System.Windows.Forms.Label();
@@ -42,7 +43,7 @@
this.barOverallProgressUpdate = new System.Windows.Forms.ProgressBar();
this.tmrProgressUpdate = new System.Windows.Forms.Timer(this.components);
this.dlgOpenLuFile = new System.Windows.Forms.OpenFileDialog();
- this.lblFwUpdateInfo = new System.Windows.Forms.Label();
+ this.lblSoftwareVersion = new System.Windows.Forms.Label();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.label9 = new System.Windows.Forms.Label();
this.lblUpdateTime = new System.Windows.Forms.Label();
@@ -64,6 +65,10 @@
this.tbxUniqueId = new System.Windows.Forms.TextBox();
this.lblUniqueId = new System.Windows.Forms.Label();
this.grpInfo = new System.Windows.Forms.GroupBox();
+ this.lblBoardCalibration = new System.Windows.Forms.Label();
+ this.tbxBoardCalibration = new System.Windows.Forms.TextBox();
+ this.btnChangeMeterSize = new System.Windows.Forms.Button();
+ this.btnChangeSensorNo = new System.Windows.Forms.Button();
this.lblMeterSize = new System.Windows.Forms.Label();
this.tbxMeterSize = new System.Windows.Forms.TextBox();
this.lblFwGitHash = new System.Windows.Forms.Label();
@@ -80,6 +85,9 @@
this.grpCalibration = new System.Windows.Forms.GroupBox();
this.gridViewCalib = new System.Windows.Forms.DataGridView();
this.grpStatus = new System.Windows.Forms.GroupBox();
+ this.cbxStatus12 = new System.Windows.Forms.CheckBox();
+ this.cbxStatus11 = new System.Windows.Forms.CheckBox();
+ this.cbxStatus10 = new System.Windows.Forms.CheckBox();
this.cbxStatus9 = new System.Windows.Forms.CheckBox();
this.cbxStatus8 = new System.Windows.Forms.CheckBox();
this.cbxStatus7 = new System.Windows.Forms.CheckBox();
@@ -90,8 +98,11 @@
this.cbxStatus2 = new System.Windows.Forms.CheckBox();
this.cbxStatus1 = new System.Windows.Forms.CheckBox();
this.cbxStatus0 = new System.Windows.Forms.CheckBox();
- this.btnChangeSensorNo = new System.Windows.Forms.Button();
- this.btnChangeMeterSize = new System.Windows.Forms.Button();
+ this.lblMagFluxApi = new System.Windows.Forms.Label();
+ this.groupBox1 = new System.Windows.Forms.GroupBox();
+ this.cbxIgnoreEmptyPipeStatus = new System.Windows.Forms.CheckBox();
+ this.cbxSimulatedFlow = new System.Windows.Forms.CheckBox();
+ this.lblSharedCode = new System.Windows.Forms.Label();
this.grpSetup.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picLogo)).BeginInit();
@@ -100,14 +111,16 @@
this.grpCalibration.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.gridViewCalib)).BeginInit();
this.grpStatus.SuspendLayout();
+ this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// grpSetup
//
+ this.grpSetup.Controls.Add(this.btnInitPcb);
this.grpSetup.Controls.Add(this.btnConnect);
this.grpSetup.Controls.Add(this.label2);
this.grpSetup.Controls.Add(this.cbComSlot);
- this.grpSetup.Controls.Add(this.lblSensorNo);
+ this.grpSetup.Controls.Add(this.lblPcbId);
this.grpSetup.Location = new System.Drawing.Point(100, 2);
this.grpSetup.Name = "grpSetup";
this.grpSetup.Size = new System.Drawing.Size(208, 99);
@@ -115,6 +128,17 @@
this.grpSetup.TabStop = false;
this.grpSetup.Text = "Setup";
//
+ // btnInitPcb
+ //
+ this.btnInitPcb.Location = new System.Drawing.Point(136, 58);
+ this.btnInitPcb.Name = "btnInitPcb";
+ this.btnInitPcb.Size = new System.Drawing.Size(63, 25);
+ this.btnInitPcb.TabIndex = 46;
+ this.btnInitPcb.Text = "Init Pcb";
+ this.btnInitPcb.UseVisualStyleBackColor = true;
+ this.btnInitPcb.Visible = false;
+ this.btnInitPcb.Click += new System.EventHandler(this.btnInitPcb_Click);
+ //
// btnConnect
//
this.btnConnect.Location = new System.Drawing.Point(83, 18);
@@ -165,14 +189,14 @@
this.cbComSlot.Text = "1";
this.cbComSlot.SelectedIndexChanged += new System.EventHandler(this.cbComSlot_SelectedIndexChanged);
//
- // lblSensorNo
+ // lblPcbId
//
- this.lblSensorNo.AutoSize = true;
- this.lblSensorNo.Location = new System.Drawing.Point(37, 64);
- this.lblSensorNo.Name = "lblSensorNo";
- this.lblSensorNo.Size = new System.Drawing.Size(100, 13);
- this.lblSensorNo.TabIndex = 23;
- this.lblSensorNo.Text = "NOT CONNECTED";
+ this.lblPcbId.AutoSize = true;
+ this.lblPcbId.Location = new System.Drawing.Point(6, 64);
+ this.lblPcbId.Name = "lblPcbId";
+ this.lblPcbId.Size = new System.Drawing.Size(100, 13);
+ this.lblPcbId.TabIndex = 23;
+ this.lblPcbId.Text = "NOT CONNECTED";
//
// tbxSensorNo
//
@@ -236,15 +260,18 @@
//
this.dlgOpenLuFile.Filter = "metrology lookup tables (*.lut)|*.lut";
//
- // lblFwUpdateInfo
+ // lblSoftwareVersion
//
- this.lblFwUpdateInfo.AutoSize = true;
- this.lblFwUpdateInfo.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.lblFwUpdateInfo.Location = new System.Drawing.Point(690, 66);
- this.lblFwUpdateInfo.Name = "lblFwUpdateInfo";
- this.lblFwUpdateInfo.Size = new System.Drawing.Size(72, 13);
- this.lblFwUpdateInfo.TabIndex = 27;
- this.lblFwUpdateInfo.Text = "Version: 0.0.0";
+ this.lblSoftwareVersion.AutoSize = true;
+ this.lblSoftwareVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
+ this.lblSoftwareVersion.Location = new System.Drawing.Point(698, 80);
+ this.lblSoftwareVersion.MaximumSize = new System.Drawing.Size(120, 13);
+ this.lblSoftwareVersion.MinimumSize = new System.Drawing.Size(120, 13);
+ this.lblSoftwareVersion.Name = "lblSoftwareVersion";
+ this.lblSoftwareVersion.Size = new System.Drawing.Size(120, 13);
+ this.lblSoftwareVersion.TabIndex = 27;
+ this.lblSoftwareVersion.Text = "ToolBox 0.0.0.0000";
+ this.lblSoftwareVersion.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// openFileDialog1
//
@@ -280,10 +307,10 @@
//
// picLogo
//
- this.picLogo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
+ this.picLogo.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picLogo.Image = global::Xylem.Common.Ui.MagFluxToolBox.Properties.Resources.MjK_LogoSmall;
this.picLogo.InitialImage = null;
- this.picLogo.Location = new System.Drawing.Point(687, 5);
+ this.picLogo.Location = new System.Drawing.Point(727, 5);
this.picLogo.Name = "picLogo";
this.picLogo.Size = new System.Drawing.Size(91, 58);
this.picLogo.TabIndex = 34;
@@ -305,7 +332,7 @@
this.grpMeasurements.Controls.Add(this.label11);
this.grpMeasurements.Location = new System.Drawing.Point(6, 103);
this.grpMeasurements.Name = "grpMeasurements";
- this.grpMeasurements.Size = new System.Drawing.Size(302, 213);
+ this.grpMeasurements.Size = new System.Drawing.Size(302, 179);
this.grpMeasurements.TabIndex = 37;
this.grpMeasurements.TabStop = false;
this.grpMeasurements.Text = "Measurements";
@@ -315,9 +342,10 @@
this.tbxFwdVolume.Location = new System.Drawing.Point(112, 45);
this.tbxFwdVolume.Name = "tbxFwdVolume";
this.tbxFwdVolume.ReadOnly = true;
- this.tbxFwdVolume.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
+ this.tbxFwdVolume.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tbxFwdVolume.Size = new System.Drawing.Size(80, 20);
this.tbxFwdVolume.TabIndex = 39;
+ this.tbxFwdVolume.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// label4
//
@@ -333,9 +361,10 @@
this.tbxTime.Location = new System.Drawing.Point(112, 147);
this.tbxTime.Name = "tbxTime";
this.tbxTime.ReadOnly = true;
- this.tbxTime.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
+ this.tbxTime.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tbxTime.Size = new System.Drawing.Size(80, 20);
this.tbxTime.TabIndex = 37;
+ this.tbxTime.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// label3
//
@@ -351,9 +380,10 @@
this.tbxRevVolume.Location = new System.Drawing.Point(112, 71);
this.tbxRevVolume.Name = "tbxRevVolume";
this.tbxRevVolume.ReadOnly = true;
- this.tbxRevVolume.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
+ this.tbxRevVolume.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tbxRevVolume.Size = new System.Drawing.Size(80, 20);
this.tbxRevVolume.TabIndex = 35;
+ this.tbxRevVolume.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// label1
//
@@ -369,9 +399,10 @@
this.tbxStatus.Location = new System.Drawing.Point(112, 121);
this.tbxStatus.Name = "tbxStatus";
this.tbxStatus.ReadOnly = true;
- this.tbxStatus.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
+ this.tbxStatus.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tbxStatus.Size = new System.Drawing.Size(80, 20);
this.tbxStatus.TabIndex = 33;
+ this.tbxStatus.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// lblStatus
//
@@ -387,18 +418,20 @@
this.tbxVolume.Location = new System.Drawing.Point(112, 19);
this.tbxVolume.Name = "tbxVolume";
this.tbxVolume.ReadOnly = true;
- this.tbxVolume.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
+ this.tbxVolume.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tbxVolume.Size = new System.Drawing.Size(80, 20);
this.tbxVolume.TabIndex = 31;
+ this.tbxVolume.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// tbxFlowRate
//
this.tbxFlowRate.Location = new System.Drawing.Point(112, 96);
this.tbxFlowRate.Name = "tbxFlowRate";
this.tbxFlowRate.ReadOnly = true;
- this.tbxFlowRate.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
+ this.tbxFlowRate.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tbxFlowRate.Size = new System.Drawing.Size(80, 20);
this.tbxFlowRate.TabIndex = 29;
+ this.tbxFlowRate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// label7
//
@@ -437,6 +470,8 @@
//
// grpInfo
//
+ this.grpInfo.Controls.Add(this.lblBoardCalibration);
+ this.grpInfo.Controls.Add(this.tbxBoardCalibration);
this.grpInfo.Controls.Add(this.btnChangeMeterSize);
this.grpInfo.Controls.Add(this.btnChangeSensorNo);
this.grpInfo.Controls.Add(this.lblMeterSize);
@@ -451,13 +486,51 @@
this.grpInfo.Controls.Add(this.tbxUniqueId);
this.grpInfo.Controls.Add(this.tbxSensorNo);
this.grpInfo.Controls.Add(this.lblUniqueId);
- this.grpInfo.Location = new System.Drawing.Point(6, 316);
+ this.grpInfo.Location = new System.Drawing.Point(6, 285);
this.grpInfo.Name = "grpInfo";
- this.grpInfo.Size = new System.Drawing.Size(302, 176);
+ this.grpInfo.Size = new System.Drawing.Size(302, 207);
this.grpInfo.TabIndex = 25;
this.grpInfo.TabStop = false;
this.grpInfo.Text = "Info";
//
+ // lblBoardCalibration
+ //
+ this.lblBoardCalibration.AutoSize = true;
+ this.lblBoardCalibration.Location = new System.Drawing.Point(4, 173);
+ this.lblBoardCalibration.Name = "lblBoardCalibration";
+ this.lblBoardCalibration.Size = new System.Drawing.Size(86, 13);
+ this.lblBoardCalibration.TabIndex = 47;
+ this.lblBoardCalibration.Text = "PCB Calib [norm]";
+ //
+ // tbxBoardCalibration
+ //
+ this.tbxBoardCalibration.Location = new System.Drawing.Point(112, 172);
+ this.tbxBoardCalibration.Name = "tbxBoardCalibration";
+ this.tbxBoardCalibration.ReadOnly = true;
+ this.tbxBoardCalibration.RightToLeft = System.Windows.Forms.RightToLeft.No;
+ this.tbxBoardCalibration.Size = new System.Drawing.Size(112, 20);
+ this.tbxBoardCalibration.TabIndex = 46;
+ //
+ // btnChangeMeterSize
+ //
+ this.btnChangeMeterSize.Location = new System.Drawing.Point(230, 142);
+ this.btnChangeMeterSize.Name = "btnChangeMeterSize";
+ this.btnChangeMeterSize.Size = new System.Drawing.Size(63, 25);
+ this.btnChangeMeterSize.TabIndex = 45;
+ this.btnChangeMeterSize.Text = "Change";
+ this.btnChangeMeterSize.UseVisualStyleBackColor = true;
+ this.btnChangeMeterSize.Click += new System.EventHandler(this.btnChangeMeterSize_Click);
+ //
+ // btnChangeSensorNo
+ //
+ this.btnChangeSensorNo.Location = new System.Drawing.Point(230, 42);
+ this.btnChangeSensorNo.Name = "btnChangeSensorNo";
+ this.btnChangeSensorNo.Size = new System.Drawing.Size(63, 25);
+ this.btnChangeSensorNo.TabIndex = 43;
+ this.btnChangeSensorNo.Text = "Change";
+ this.btnChangeSensorNo.UseVisualStyleBackColor = true;
+ this.btnChangeSensorNo.Click += new System.EventHandler(this.btnChangeSensorNo_Click);
+ //
// lblMeterSize
//
this.lblMeterSize.AutoSize = true;
@@ -479,7 +552,7 @@
// lblFwGitHash
//
this.lblFwGitHash.AutoSize = true;
- this.lblFwGitHash.Location = new System.Drawing.Point(6, 123);
+ this.lblFwGitHash.Location = new System.Drawing.Point(4, 123);
this.lblFwGitHash.Name = "lblFwGitHash";
this.lblFwGitHash.Size = new System.Drawing.Size(76, 13);
this.lblFwGitHash.TabIndex = 42;
@@ -586,9 +659,9 @@
this.grpCalibration.Controls.Add(this.btnPrepareCalibration);
this.grpCalibration.Controls.Add(this.btnReadCalibration);
this.grpCalibration.Controls.Add(this.btnWriteCalibration);
- this.grpCalibration.Location = new System.Drawing.Point(314, 273);
+ this.grpCalibration.Location = new System.Drawing.Point(314, 285);
this.grpCalibration.Name = "grpCalibration";
- this.grpCalibration.Size = new System.Drawing.Size(366, 219);
+ this.grpCalibration.Size = new System.Drawing.Size(376, 207);
this.grpCalibration.TabIndex = 42;
this.grpCalibration.TabStop = false;
this.grpCalibration.Text = "Calibration";
@@ -610,6 +683,9 @@
//
// grpStatus
//
+ this.grpStatus.Controls.Add(this.cbxStatus12);
+ this.grpStatus.Controls.Add(this.cbxStatus11);
+ this.grpStatus.Controls.Add(this.cbxStatus10);
this.grpStatus.Controls.Add(this.cbxStatus9);
this.grpStatus.Controls.Add(this.cbxStatus8);
this.grpStatus.Controls.Add(this.cbxStatus7);
@@ -620,13 +696,46 @@
this.grpStatus.Controls.Add(this.cbxStatus2);
this.grpStatus.Controls.Add(this.cbxStatus1);
this.grpStatus.Controls.Add(this.cbxStatus0);
- this.grpStatus.Location = new System.Drawing.Point(472, 2);
+ this.grpStatus.Location = new System.Drawing.Point(479, 2);
this.grpStatus.Name = "grpStatus";
- this.grpStatus.Size = new System.Drawing.Size(209, 271);
+ this.grpStatus.Size = new System.Drawing.Size(211, 280);
this.grpStatus.TabIndex = 43;
this.grpStatus.TabStop = false;
this.grpStatus.Text = "Detailed Status";
//
+ // cbxStatus12
+ //
+ this.cbxStatus12.AutoCheck = false;
+ this.cbxStatus12.AutoSize = true;
+ this.cbxStatus12.Location = new System.Drawing.Point(10, 260);
+ this.cbxStatus12.Name = "cbxStatus12";
+ this.cbxStatus12.Size = new System.Drawing.Size(85, 17);
+ this.cbxStatus12.TabIndex = 12;
+ this.cbxStatus12.Text = "cbxStatus12";
+ this.cbxStatus12.UseVisualStyleBackColor = true;
+ //
+ // cbxStatus11
+ //
+ this.cbxStatus11.AutoCheck = false;
+ this.cbxStatus11.AutoSize = true;
+ this.cbxStatus11.Location = new System.Drawing.Point(10, 240);
+ this.cbxStatus11.Name = "cbxStatus11";
+ this.cbxStatus11.Size = new System.Drawing.Size(85, 17);
+ this.cbxStatus11.TabIndex = 11;
+ this.cbxStatus11.Text = "cbxStatus11";
+ this.cbxStatus11.UseVisualStyleBackColor = true;
+ //
+ // cbxStatus10
+ //
+ this.cbxStatus10.AutoCheck = false;
+ this.cbxStatus10.AutoSize = true;
+ this.cbxStatus10.Location = new System.Drawing.Point(10, 220);
+ this.cbxStatus10.Name = "cbxStatus10";
+ this.cbxStatus10.Size = new System.Drawing.Size(85, 17);
+ this.cbxStatus10.TabIndex = 10;
+ this.cbxStatus10.Text = "cbxStatus10";
+ this.cbxStatus10.UseVisualStyleBackColor = true;
+ //
// cbxStatus9
//
this.cbxStatus9.AutoCheck = false;
@@ -737,32 +846,76 @@
this.cbxStatus0.Text = "cbxStatus0";
this.cbxStatus0.UseVisualStyleBackColor = true;
//
- // btnChangeSensorNo
+ // lblMagFluxApi
//
- this.btnChangeSensorNo.Location = new System.Drawing.Point(230, 42);
- this.btnChangeSensorNo.Name = "btnChangeSensorNo";
- this.btnChangeSensorNo.Size = new System.Drawing.Size(63, 25);
- this.btnChangeSensorNo.TabIndex = 43;
- this.btnChangeSensorNo.Text = "Change";
- this.btnChangeSensorNo.UseVisualStyleBackColor = true;
- this.btnChangeSensorNo.Click += new System.EventHandler(this.btnChangeSensorNo_Click);
+ this.lblMagFluxApi.AutoSize = true;
+ this.lblMagFluxApi.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
+ this.lblMagFluxApi.Location = new System.Drawing.Point(698, 100);
+ this.lblMagFluxApi.MaximumSize = new System.Drawing.Size(120, 13);
+ this.lblMagFluxApi.MinimumSize = new System.Drawing.Size(120, 13);
+ this.lblMagFluxApi.Name = "lblMagFluxApi";
+ this.lblMagFluxApi.Size = new System.Drawing.Size(120, 13);
+ this.lblMagFluxApi.TabIndex = 44;
+ this.lblMagFluxApi.Text = "MagFlux API 0.0.0.00";
+ this.lblMagFluxApi.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
- // btnChangeMeterSize
+ // groupBox1
//
- this.btnChangeMeterSize.Location = new System.Drawing.Point(230, 142);
- this.btnChangeMeterSize.Name = "btnChangeMeterSize";
- this.btnChangeMeterSize.Size = new System.Drawing.Size(63, 25);
- this.btnChangeMeterSize.TabIndex = 45;
- this.btnChangeMeterSize.Text = "Change";
- this.btnChangeMeterSize.UseVisualStyleBackColor = true;
- this.btnChangeMeterSize.Click += new System.EventHandler(this.btnChangeMeterSize_Click);
+ this.groupBox1.Controls.Add(this.cbxIgnoreEmptyPipeStatus);
+ this.groupBox1.Controls.Add(this.cbxSimulatedFlow);
+ this.groupBox1.Location = new System.Drawing.Point(314, 2);
+ this.groupBox1.Name = "groupBox1";
+ this.groupBox1.Size = new System.Drawing.Size(159, 280);
+ this.groupBox1.TabIndex = 44;
+ this.groupBox1.TabStop = false;
+ this.groupBox1.Text = "Detailed Status";
+ //
+ // cbxIgnoreEmptyPipeStatus
+ //
+ this.cbxIgnoreEmptyPipeStatus.AutoSize = true;
+ this.cbxIgnoreEmptyPipeStatus.Location = new System.Drawing.Point(10, 40);
+ this.cbxIgnoreEmptyPipeStatus.Name = "cbxIgnoreEmptyPipeStatus";
+ this.cbxIgnoreEmptyPipeStatus.Size = new System.Drawing.Size(145, 17);
+ this.cbxIgnoreEmptyPipeStatus.TabIndex = 1;
+ this.cbxIgnoreEmptyPipeStatus.Text = "Ignore Empty Pipe Status";
+ this.cbxIgnoreEmptyPipeStatus.UseVisualStyleBackColor = true;
+ this.cbxIgnoreEmptyPipeStatus.Visible = false;
+ this.cbxIgnoreEmptyPipeStatus.CheckedChanged += new System.EventHandler(this.cbxIgnoreEmptyPipeStatus_CheckedChanged);
+ //
+ // cbxSimulatedFlow
+ //
+ this.cbxSimulatedFlow.AutoSize = true;
+ this.cbxSimulatedFlow.Location = new System.Drawing.Point(10, 20);
+ this.cbxSimulatedFlow.Name = "cbxSimulatedFlow";
+ this.cbxSimulatedFlow.Size = new System.Drawing.Size(130, 17);
+ this.cbxSimulatedFlow.TabIndex = 0;
+ this.cbxSimulatedFlow.Text = "Simulated Flow Active";
+ this.cbxSimulatedFlow.UseVisualStyleBackColor = true;
+ this.cbxSimulatedFlow.Visible = false;
+ this.cbxSimulatedFlow.CheckedChanged += new System.EventHandler(this.cbxSimulatedFlow_CheckedChanged);
+ //
+ // lblSharedCode
+ //
+ this.lblSharedCode.AutoSize = true;
+ this.lblSharedCode.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
+ this.lblSharedCode.Location = new System.Drawing.Point(698, 120);
+ this.lblSharedCode.MaximumSize = new System.Drawing.Size(120, 13);
+ this.lblSharedCode.MinimumSize = new System.Drawing.Size(120, 13);
+ this.lblSharedCode.Name = "lblSharedCode";
+ this.lblSharedCode.Size = new System.Drawing.Size(120, 13);
+ this.lblSharedCode.TabIndex = 45;
+ this.lblSharedCode.Text = "Shared Code 0.0.0.00";
+ this.lblSharedCode.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// FrmTest
//
this.AccessibleRole = System.Windows.Forms.AccessibleRole.Sound;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(784, 581);
+ this.ClientSize = new System.Drawing.Size(824, 581);
+ this.Controls.Add(this.lblSharedCode);
+ this.Controls.Add(this.groupBox1);
+ this.Controls.Add(this.lblMagFluxApi);
this.Controls.Add(this.grpStatus);
this.Controls.Add(this.grpCalibration);
this.Controls.Add(this.grpInfo);
@@ -773,14 +926,14 @@
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.lblWaitingForMeterResponse);
this.Controls.Add(this.lblOverall);
- this.Controls.Add(this.lblFwUpdateInfo);
+ this.Controls.Add(this.lblSoftwareVersion);
this.Controls.Add(this.barSingleProgressUpdate);
this.Controls.Add(this.lblActualProcess);
this.Controls.Add(this.grpSetup);
this.Controls.Add(this.barOverallProgressUpdate);
this.MaximizeBox = false;
- this.MaximumSize = new System.Drawing.Size(800, 620);
- this.MinimumSize = new System.Drawing.Size(800, 620);
+ this.MaximumSize = new System.Drawing.Size(840, 620);
+ this.MinimumSize = new System.Drawing.Size(840, 620);
this.Name = "FrmTest";
this.Text = "MagFlux Test";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmTest_FormClosing);
@@ -797,6 +950,8 @@
((System.ComponentModel.ISupportInitialize)(this.gridViewCalib)).EndInit();
this.grpStatus.ResumeLayout(false);
this.grpStatus.PerformLayout();
+ this.groupBox1.ResumeLayout(false);
+ this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
@@ -806,7 +961,7 @@
private System.Windows.Forms.GroupBox grpSetup;
private System.Windows.Forms.Button btnConnect;
- private System.Windows.Forms.Label lblSensorNo;
+ private System.Windows.Forms.Label lblPcbId;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbComSlot;
private System.Windows.Forms.ProgressBar barOverallProgressUpdate;
@@ -815,7 +970,7 @@
private System.Windows.Forms.Label lblOverall;
private System.Windows.Forms.ProgressBar barSingleProgressUpdate;
private System.Windows.Forms.OpenFileDialog dlgOpenLuFile;
- private System.Windows.Forms.Label lblFwUpdateInfo;
+ private System.Windows.Forms.Label lblSoftwareVersion;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Label lblWaitingForMeterResponse;
private System.Windows.Forms.Label label9;
@@ -867,5 +1022,16 @@
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button btnChangeMeterSize;
private System.Windows.Forms.Button btnChangeSensorNo;
+ private System.Windows.Forms.Label lblMagFluxApi;
+ private System.Windows.Forms.Button btnInitPcb;
+ private System.Windows.Forms.CheckBox cbxStatus12;
+ private System.Windows.Forms.CheckBox cbxStatus11;
+ private System.Windows.Forms.CheckBox cbxStatus10;
+ private System.Windows.Forms.Label lblBoardCalibration;
+ private System.Windows.Forms.TextBox tbxBoardCalibration;
+ private System.Windows.Forms.GroupBox groupBox1;
+ private System.Windows.Forms.CheckBox cbxIgnoreEmptyPipeStatus;
+ private System.Windows.Forms.CheckBox cbxSimulatedFlow;
+ private System.Windows.Forms.Label lblSharedCode;
}
}
\ No newline at end of file
diff --git a/Common/Ui/MagFluxToolBox/FrmTest.cs b/Common/Ui/MagFluxToolBox/FrmTest.cs
index 8c88bbbf..6cfc1e7e 100644
--- a/Common/Ui/MagFluxToolBox/FrmTest.cs
+++ b/Common/Ui/MagFluxToolBox/FrmTest.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Data;
+using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Reflection;
@@ -43,17 +44,22 @@ namespace Xylem.Common.Ui.MagFluxToolBox
private const String StrNotConnected = "NOT CONNECTED";
private const String StrOverallProcess = "Overall Process";
+ private const String StrEpbControlBit0 = @"Empty Pipe Detection OFF";
+ private const String StrEpbControlBit1 = @"Empty Pipe Detection flags only";
+ private const String StrEpbControlBit2 = @"Empty Pipe Detection active";
+
private UInt32 _lastState;
private DateTimeOffset _startTime;
- private Boolean _resetTimeMeasurement;
private readonly Boolean _updateGui = true;
- private Boolean _tryConnectPcb;
+ //private Boolean _tryConnectPcb;
+ private PcbAccess _pcbAccess = PcbAccess.None;
+ private Boolean _pcbIsInitialized;
// external update remarks form
// private readonly FrmHistory _frmHistory = new FrmHistory();
- private readonly Version _version;
+ //private readonly Version _version;
// status information
private static readonly Color ColorDefault = Color.Black;
@@ -67,7 +73,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
private const String StrSeparator = "-----------------------------------------------------" +
"-----------------------------------------------------";
#endregion
-
#region FormControls
///
/// Ctor FW update
@@ -78,7 +83,7 @@ namespace Xylem.Common.Ui.MagFluxToolBox
var cultureInfo = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
- _version = Assembly.GetExecutingAssembly().GetName().Version;
+ //_version = Assembly.GetExecutingAssembly().GetName().Version;
}
///
@@ -88,8 +93,10 @@ namespace Xylem.Common.Ui.MagFluxToolBox
{
ProcessViewControl(false);
_magFluxMeter?.StopStreamingCatcher();
- lblSensorNo.Text = StrNotConnected;
- lblSensorNo.ForeColor = Color.Red;
+ lblPcbId.Text = StrNotConnected;
+ lblPcbId.ForeColor = Color.Red;
+ btnInitPcb.Visible = false;
+ btnInitPcb.Enabled = false;
lblWaitingForMeterResponse.Visible = false;
btnConnect.Enabled = true;
SetControlDownloadsLocked();
@@ -124,17 +131,39 @@ namespace Xylem.Common.Ui.MagFluxToolBox
cbxStatus8.Text = errorStateInfos[8];
cbxStatus9.Text = errorStateInfos[9];
}
+ cbxStatus10.Text = StrEpbControlBit0;
+ cbxStatus11.Text = StrEpbControlBit1;
+ cbxStatus12.Text = StrEpbControlBit2;
+ CheckUpdateEnabled();
}
private void FrmTest_Load(Object sender, EventArgs e)
{
var version = Assembly.GetExecutingAssembly().GetName().Version;
- lblFwUpdateInfo.Text = $@"Version: {version.Major}.{version.Minor}.{version.Build}";
- _resetTimeMeasurement = true;
Init();
-
- LogText($"MagFluxToolBox: {_version.Major}.{_version.Minor}.{_version.Build}");
+ var strVersion = $@"ToolBox {version}";
+ lblSoftwareVersion.Text = strVersion;
+ LogText(strVersion);
LogText(StrSeparator);
+
+ try
+ {
+ var fileVersion = FileVersionInfo.GetVersionInfo("magflux_api.dll");
+ strVersion = $@"MagFlux API {fileVersion.FileVersion}";
+ lblMagFluxApi.Text = strVersion;
+ LogText(strVersion);
+ LogText(StrSeparator);
+
+ fileVersion = FileVersionInfo.GetVersionInfo("shared_code.dll");
+ strVersion = $"Shared Code {fileVersion.FileVersion}";
+ lblSharedCode.Text = strVersion;
+ LogText(strVersion);
+ LogText(StrSeparator);
+ }
+ catch (Exception ex)
+ {
+ LogText(ex.Message);
+ }
}
private void FrmTest_FormClosing(Object sender, FormClosingEventArgs e)
@@ -154,7 +183,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
private void cbComSlot_SelectedIndexChanged(Object sender, EventArgs e)
{
- _resetTimeMeasurement = true;
Init();
}
#endregion
@@ -192,7 +220,7 @@ namespace Xylem.Common.Ui.MagFluxToolBox
}
FillDataGridWithCalibInfos();
-
+
}
catch (Exception)
{
@@ -243,7 +271,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
}
}
#endregion --------------------------------------- Data Grid Calibration --------------------------------------
-
#region ActivationControls
private void SetControlDownloadsLocked()
@@ -255,6 +282,7 @@ namespace Xylem.Common.Ui.MagFluxToolBox
btnWriteCalibration.Enabled = false;
btnChangeSensorNo.Enabled = false;
btnChangeMeterSize.Enabled = false;
+ btnInitPcb.Enabled = false;
}
private void SetControlsDownloadIsOngoing()
@@ -266,6 +294,7 @@ namespace Xylem.Common.Ui.MagFluxToolBox
btnWriteCalibration.Enabled = false;
btnChangeSensorNo.Enabled = false;
btnChangeMeterSize.Enabled = false;
+ btnInitPcb.Enabled = false;
}
private void SetControlsDownloadIsFinished()
@@ -277,6 +306,7 @@ namespace Xylem.Common.Ui.MagFluxToolBox
btnWriteCalibration.Enabled = true;
btnChangeSensorNo.Enabled = true;
btnChangeMeterSize.Enabled = true;
+ btnInitPcb.Enabled = !_pcbIsInitialized;
}
private void SetControlsDownloadEnabled()
{
@@ -287,9 +317,9 @@ namespace Xylem.Common.Ui.MagFluxToolBox
btnWriteCalibration.Enabled = true;
btnChangeSensorNo.Enabled = true;
btnChangeMeterSize.Enabled = true;
+ btnInitPcb.Enabled = !_pcbIsInitialized;
}
#endregion
-
#region BoardControls
///
@@ -338,9 +368,14 @@ namespace Xylem.Common.Ui.MagFluxToolBox
cbxStatus7.Checked = StateDef.CheckStateMask(_lastState, 7);
cbxStatus8.Checked = StateDef.CheckStateMask(_lastState, 8);
cbxStatus9.Checked = StateDef.CheckStateMask(_lastState, 9);
-
}
+ ///
+ /// Connect to MagFlux and read out all needed information.
+ ///
+ ///
+ /// - PcbId taken to decide board initialization.
+ ///
private void Connect()
{
try
@@ -357,6 +392,8 @@ namespace Xylem.Common.Ui.MagFluxToolBox
Task.Factory.StartNew(() =>
{
+ _pcbAccess = PcbAccess.Connect;
+ tmrProgressUpdate.Interval = 200;
ViewProgressPcb(true);
//dispose old meter
@@ -380,22 +417,40 @@ namespace Xylem.Common.Ui.MagFluxToolBox
{
if (_magFluxMeter != null && _magFluxMeter.IsLoggedOn)
{
- lblSensorNo.Text = "";
+ if (!string.IsNullOrEmpty(_magFluxMeter.PcbId))
+ {
+ lblPcbId.Text = $@"PcbId: {_magFluxMeter.PcbId}";
+ lblPcbId.ForeColor = Color.Green;
+ btnInitPcb.Visible = false;
+ _pcbIsInitialized = true;
+ tbxBoardCalibration.Text = $@"{_magFluxMeter.BoardCalib:F4}";
+ }
+ else
+ {
+ lblPcbId.Text = @"PCB NOT INITIALIZED";
+ lblPcbId.ForeColor = Color.DarkOrange;
+ _pcbIsInitialized = false;
+ btnInitPcb.Visible = true;
+ tbxBoardCalibration.Text = @"?";
+ }
+
tbxUniqueId.Text = _magFluxMeter.UniqueId;
- tbxSensorNo.Text = _magFluxMeter.PcbId;
+ tbxSensorNo.Text = _magFluxMeter.SensorSerialNo;
tbxFwVersion.Text = _magFluxMeter.FwVersion;
tbxFwBuildDate.Text = _magFluxMeter.FwBuildDate;
tbxFwGitHash.Text = _magFluxMeter.FwGitHash;
tbxMeterSize.Text = _magFluxMeter.MeterSizeMm.ToString();
- lblSensorNo.ForeColor = Color.Green;
+ cbxStatus10.Checked = (_magFluxMeter.EpdControlBits & 0x01) == 0x01;
+ cbxStatus11.Checked = (_magFluxMeter.EpdControlBits & 0x02) == 0x02;
+ cbxStatus12.Checked = (_magFluxMeter.EpdControlBits & 0x04) == 0x04;
CheckUpdateEnabled();
- _magFluxMeter.StartStreamingCatcher();
- _magFluxMeter.Logout();
- LogInstalledMeterFw();
}
}));
}).ContinueWith(delegate
{
+ _magFluxMeter.StartStreamingCatcher();
+ _magFluxMeter.Logout();
+ _pcbAccess = PcbAccess.Done;
ViewProgressPcb(false);
});
}
@@ -406,9 +461,8 @@ namespace Xylem.Common.Ui.MagFluxToolBox
}
}
#endregion
-
#region ProcessControls
- private void ViewProgressPcb(Boolean isActive)
+ private void ViewProgressPcb(Boolean isActive, String msg = StrConnecting)
{
if (_updateGui)
{
@@ -416,9 +470,8 @@ namespace Xylem.Common.Ui.MagFluxToolBox
{
Invoke(new Action(() =>
{
- _tryConnectPcb = true;
ProcessViewControl(true);
- lblActualProcess.Text = StrConnecting;
+ lblActualProcess.Text = msg;
lblOverall.Text = StrOverallProcess;
}));
}
@@ -426,7 +479,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
{
Invoke(new Action(() =>
{
- _tryConnectPcb = false;
ProcessViewControl(false);
}));
}
@@ -470,94 +522,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
Update();
}
- private void StartStopDownload(Boolean isActive)
- {
- if (isActive)
- {
- Invoke(new Action(() =>
- {
- ProcessViewControl(true);
- tmrProgressUpdate.Enabled = true;
- }));
- }
- else
- {
- Invoke(new Action(() =>
- {
- ProcessViewControl(false);
- SetControlsDownloadIsFinished();
-
- //// update the display of the meter size, LUT CRC and region
- //tbxMeterFw.Text = _magFluxMeter.FwVersion;
- //tbxMeterMeterSize.Text = _magFluxMeter.MeterSizeMm;
- //tbxMeterLutCrc.Text = _magFluxMeter.LutCrc;
- //tbxRegion.Text = _magFluxMeter.Region;
-
- //if (!_lutFileSuccessfulWritten)
- //{
- // lblLutFileLoadedInfo.ForeColor = Color.Red;
- // lblLutFileLoadedInfo.Text = StrUpdateErrorMessage;
- // var txt = StrUpdateErrorMessage;
- // if (!string.IsNullOrEmpty(_meterLutUpdate?.ErrorMessage))
- // {
- // txt += "\n";
- // txt += _meterLutUpdate?.ErrorMessage;
- // }
-
- // LogErrorText(txt);
- // MessageBoxShow(txt, @"FAILED",
- // MessageBoxButtons.OK, MessageBoxIcon.Error);
- //}
- //else
- //{
- // LogSuccessText(StrUpdateSuccessMessage);
- // MessageBoxShow(StrUpdateSuccessMessage, @"SUCCESS",
- // MessageBoxButtons.OK, MessageBoxIcon.Information);
- //}
- }));
- }
- }
-
- ///
- /// Display installed meter FW.
- ///
- ///
- /// - Init.
- ///
- private void LogInstalledMeterFw()
- {
- //if (_magFluxMeter == null)
- // return;
- //LogText(StrSeparator);
- //LogText($"PCB ID: {_magFluxMeter.PcbId}");
- //LogText($"Core Version: {GenesisMeter.BuildFwVersionString(_magFluxMeter.CoreRevision)}");
- //LogText("");
- //LogText("Installed Applications:");
-
- //foreach (var app in _magFluxMeter.MeterAppListVersion)
- //{
- // var versionString = app.IsInstalled ? $"V: {app.StrVersion} - CRC: 0x{app.Crc:X4}" :
- // "App NOT Installed";
- // if (app.Status == MeterAppState.Unknown)
- // versionString = "COMMUNICATION ERROR";
- // LogText($"AppId: 0x{app.AppId:X2} - {versionString} - " + $"AppName: {app.AppName}");
-
- // if (app.IsInstalled)
- // {
- // var appVersion = new CordonelAppVersion(app.AppId, app.StrVersion);
-
- // // Copy metrology update permission
- // if (app.AppName == MeterFwUpdateCapability.MetrologyName &&
- // _magFluxMeter.MetrologyUpgradePermission != MeterFwUpdateCapability.MetrologyUpgradePermitted)
- // {
- // appVersion.IsUpdateable = false;
- // }
- // }
- //}
- //LogText(StrSeparator);
- }
-
-
///
/// Output exclusively to user update remarks text window.
///
@@ -605,7 +569,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
//}));
}
#endregion
-
#region Checks
private void CheckUpdateEnabled()
{
@@ -618,7 +581,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
SetControlDownloadsLocked();
}
#endregion
-
#region Events
///
@@ -635,45 +597,25 @@ namespace Xylem.Common.Ui.MagFluxToolBox
}
#endregion
-
#region TimerControls
private void tmrProgressUpdate_Tick(Object sender, EventArgs e)
{
- //cbxManualControl.Visible = true;
- if (_tryConnectPcb)
+ switch (_pcbAccess)
{
- barOverallProgressUpdate.Value = barOverallProgressUpdate.Value + 1 > 100 ? 0 :
- barOverallProgressUpdate.Value + 1;
- barSingleProgressUpdate.Value = barSingleProgressUpdate.Value + 4 > 100 ? 0 :
- barSingleProgressUpdate.Value + 4;
- lblOverall.Text = StrOverallProcess;
- }
- else
- {
- //lblOverall.Text = _meterLutUpdate?.GetLutUpdateStateOperation();
- //lblActualProcess.Text = _meterLutUpdate?.GetActualOperation();
-
- //var overallProgress = (Int32)(_meterLutUpdate?.OverallProcessCtrPercent ?? 0);
- //if (overallProgress < 0)
- // overallProgress = 0;
- //barOverallProgressUpdate.Value = overallProgress > 100 ? 100 : overallProgress;
- //barOverallProgressUpdate.Update();
-
- //var singleProgress = (Int32)(_meterLutUpdate?.SingleFileProcessCtrPercent ?? 0);
- //if (_meterLutUpdate?.GetActualOperation() != _lastState)
- //{
- // _lastState = _meterLutUpdate?.GetActualOperation();
- // lblWaitingForMeterResponse.Visible = false;
- //}
- //else
- //{
- // //if the communication gets frozen
- // lblWaitingForMeterResponse.Visible = _lastSingleProgress == singleProgress;
- //}
-
- //barSingleProgressUpdate.Value = singleProgress > 100 ? 100 : singleProgress;
- //_lastSingleProgress = singleProgress;
- //barSingleProgressUpdate.Update();
+ case PcbAccess.Connect:
+ barOverallProgressUpdate.Value = barOverallProgressUpdate.Value + 1 > 100 ? 0 :
+ barOverallProgressUpdate.Value + 1;
+ barSingleProgressUpdate.Value = barSingleProgressUpdate.Value + 4 > 100 ? 0 :
+ barSingleProgressUpdate.Value + 4;
+ lblOverall.Text = StrOverallProcess;
+ break;
+ case PcbAccess.InitPcb:
+ barOverallProgressUpdate.Value = barOverallProgressUpdate.Value + 1 > 100 ? 0 :
+ barOverallProgressUpdate.Value + 1;
+ barSingleProgressUpdate.Value = barSingleProgressUpdate.Value + 4 > 100 ? 0 :
+ barSingleProgressUpdate.Value + 4;
+ lblOverall.Text = StrOverallProcess;
+ break;
}
SetTimeDisplay();
Update();
@@ -686,7 +628,40 @@ namespace Xylem.Common.Ui.MagFluxToolBox
lblUpdateTime.Text = $@"{(UInt32)timeSpan.TotalMinutes}:{timeSpan.Seconds:00}";
}
#endregion
- #region Buttons
+ #region User Inputs
+
+ private void cbxIgnoreEmptyPipeStatus_CheckedChanged(Object sender, EventArgs e)
+ {
+ //_magFluxMeter?.SetIgnoreEmptyPipeStatus(cbxIgnoreEmptyPipeStatus.Checked);
+ }
+
+ private void cbxSimulatedFlow_CheckedChanged(Object sender, EventArgs e)
+ {
+ //_magFluxMeter?.SetSimulatedFlowActive(cbxSimulatedFlow.Checked);
+ }
+
+ private void btnInitPcb_Click(Object sender, EventArgs e)
+ {
+ SetControlsDownloadIsOngoing();
+ _startTime = DateTimeOffset.UtcNow;
+ _magFluxMeter?.StopStreamingCatcher();
+
+ Task.Factory.StartNew(() =>
+ {
+ tmrProgressUpdate.Interval = 500;
+ ViewProgressPcb(true, "Initialize PCB");
+ _pcbAccess = PcbAccess.InitPcb;
+
+ _magFluxMeter.SetPCBToDemoDefaults();
+ Invoke(new Action(CheckUpdateEnabled));
+ }).ContinueWith(delegate
+ {
+ ViewProgressPcb(false);
+ _pcbAccess = PcbAccess.Done;
+ Invoke(new Action(Connect));
+ });
+ }
+
private void btnChangeSensorNo_Click(Object sender, EventArgs e)
{
// enable edit and change text to button text to "Set"
@@ -699,9 +674,9 @@ namespace Xylem.Common.Ui.MagFluxToolBox
{
btnChangeSensorNo.Text = StrBtnChange;
tbxSensorNo.ReadOnly = true;
- if (UInt32.TryParse(tbxSensorNo.Text, out var pcbId))
+ if (UInt32.TryParse(tbxSensorNo.Text, out var sensorSerialNo))
{
- if (_magFluxMeter != null && _magFluxMeter.SetPcbId(pcbId))
+ if (_magFluxMeter != null && _magFluxMeter.SetSensorSerialNo(sensorSerialNo))
{
// reconnect to publish the new serial number to the streaming protocol
Connect();
@@ -742,7 +717,8 @@ namespace Xylem.Common.Ui.MagFluxToolBox
{
SetControlsDownloadIsOngoing();
_magFluxMeter?.ReadCalibration(out _calibPointsCmPerH);
- if (_calibPointsCmPerH == null) return;
+ if (_calibPointsCmPerH == null)
+ return;
_dataTableCalibPoints?.Clear();
FillDataGridWithCalibInfos();
@@ -754,7 +730,7 @@ namespace Xylem.Common.Ui.MagFluxToolBox
SetControlsDownloadIsOngoing();
if (_calibPointsCmPerH == null)
return;
-
+
//TOD O THW test start to increase calibrations above 6
//var calib = new Calibration();
//calib.dutFlowRate = 2;
@@ -798,17 +774,35 @@ namespace Xylem.Common.Ui.MagFluxToolBox
//calibPointsCmPerH.AddRange(calibPoint);
//_magFluxMeter?.WriteCalibration(calibPointsCmPerH);
////TOD O THW test end
-
- if (_resetTimeMeasurement)
- {
- _startTime = DateTimeOffset.UtcNow;
- _resetTimeMeasurement = false;
- }
+
+ _startTime = DateTimeOffset.UtcNow;
Connect();
}
#endregion
#region ExternalCalls
+ ///
+ /// Access to PCB
+ ///
+ public enum PcbAccess
+ {
+ ///
+ /// No access required
+ ///
+ None,
+ ///
+ /// Connect to the device
+ ///
+ Connect,
+ ///
+ /// Initialize the board
+ ///
+ InitPcb,
+ ///
+ /// Access has been executed and finished
+ ///
+ Done
+ }
///
///
///
@@ -853,7 +847,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
}
#endregion
-
}
}
diff --git a/Common/Ui/MagFluxToolBox/FrmTest.resx b/Common/Ui/MagFluxToolBox/FrmTest.resx
index 0a9e92ed..2aa2e415 100644
--- a/Common/Ui/MagFluxToolBox/FrmTest.resx
+++ b/Common/Ui/MagFluxToolBox/FrmTest.resx
@@ -127,6 +127,6 @@
432, 17
- 25
+ 146
\ No newline at end of file
diff --git a/Common/Ui/MagFluxToolBox/MagFluxToolBox.csproj b/Common/Ui/MagFluxToolBox/MagFluxToolBox.csproj
index e7aa59c9..0d0a3b41 100644
--- a/Common/Ui/MagFluxToolBox/MagFluxToolBox.csproj
+++ b/Common/Ui/MagFluxToolBox/MagFluxToolBox.csproj
@@ -11,7 +11,7 @@
v4.8
512
true
- true
+ false
@@ -24,6 +24,7 @@
prompt
4
false
+ bin\Debug\MagFluxToolBox.xml
AnyCPU
@@ -36,12 +37,19 @@
false
+
+ False
+ ..\..\Hardware\WaterMeter\MagFlux\MagFluxApi\magflux_api.dll
+
..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll
..\..\packages\NLog.5.2.2\lib\net46\NLog.dll
+
+ ..\..\Hardware\WaterMeter\MagFlux\MagFluxApi\shared_code.dll
+
diff --git a/Common/Ui/MagFluxToolBox/Properties/AssemblyInfo.cs b/Common/Ui/MagFluxToolBox/Properties/AssemblyInfo.cs
index 3d114edb..ec58b559 100644
--- a/Common/Ui/MagFluxToolBox/Properties/AssemblyInfo.cs
+++ b/Common/Ui/MagFluxToolBox/Properties/AssemblyInfo.cs
@@ -9,14 +9,14 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xylem")]
[assembly: AssemblyProduct("MagFluxToolBox")]
-[assembly: AssemblyCopyright("Copyright © Xylem 2023")]
+[assembly: AssemblyCopyright("Copyright © Xylem 2023..2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
+[assembly: ComVisible(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a5e7ce52-3101-4e9b-b896-c2c0fade4812")]
@@ -31,5 +31,4 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("2.0.0.0")]
-[assembly: AssemblyFileVersion("2.0.0.0")]
+[assembly: AssemblyVersion("2.1.0.*")]
diff --git a/Common/Ui/MagFluxToolBox/frmMainForm.Designer.cs b/Common/Ui/MagFluxToolBox/frmMainForm.Designer.cs
index aedad9dd..6fff1bce 100644
--- a/Common/Ui/MagFluxToolBox/frmMainForm.Designer.cs
+++ b/Common/Ui/MagFluxToolBox/frmMainForm.Designer.cs
@@ -60,11 +60,14 @@
// lblVersionNumber
//
this.lblVersionNumber.AutoSize = true;
- this.lblVersionNumber.Location = new System.Drawing.Point(296, 66);
+ this.lblVersionNumber.Location = new System.Drawing.Point(268, 66);
+ this.lblVersionNumber.MaximumSize = new System.Drawing.Size(120, 13);
+ this.lblVersionNumber.MinimumSize = new System.Drawing.Size(120, 13);
this.lblVersionNumber.Name = "lblVersionNumber";
- this.lblVersionNumber.Size = new System.Drawing.Size(72, 13);
+ this.lblVersionNumber.Size = new System.Drawing.Size(120, 13);
this.lblVersionNumber.TabIndex = 23;
- this.lblVersionNumber.Text = "Version: 0.0.0";
+ this.lblVersionNumber.Text = "ToolBox 0.0.0.0000";
+ this.lblVersionNumber.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// pictureBox1
//
diff --git a/Common/Ui/MagFluxToolBox/frmMainForm.cs b/Common/Ui/MagFluxToolBox/frmMainForm.cs
index fac0c46b..339f3868 100644
--- a/Common/Ui/MagFluxToolBox/frmMainForm.cs
+++ b/Common/Ui/MagFluxToolBox/frmMainForm.cs
@@ -1,4 +1,5 @@
using System;
+using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
@@ -22,8 +23,21 @@ namespace Xylem.Common.Ui.MagFluxToolBox
InitializeComponent();
var logger = NLogHelper.CreateOrGetLogger("MagFluxToolBox");
var version = Assembly.GetExecutingAssembly().GetName().Version;
- logger.Info($"MagFluxToolBox Version: {version.Major}.{version.Minor}.{version.Build}");
- lblVersionNumber.Text = $@"Version: {version.Major}.{version.Minor}.{version.Build}";
+ logger.Info($"MagFlux ToolBox Version:{version}");
+ lblVersionNumber.Text = $@"ToolBox {version}";
+
+ try
+ {
+ var fileVersion = FileVersionInfo.GetVersionInfo("magflux_api.dll");
+ logger.Info($"MagFlux API Version:{fileVersion.FileVersion}");
+
+ fileVersion = FileVersionInfo.GetVersionInfo("shared_code.dll");
+ logger.Info($"Shared Code Version:{fileVersion.FileVersion}");
+ }
+ catch (Exception ex)
+ {
+ logger.Debug(ex.Message);
+ }
}
private void Form_Closed(Object sender, EventArgs e)
@@ -68,11 +82,6 @@ namespace Xylem.Common.Ui.MagFluxToolBox
Close();
}
- if (System.Diagnostics.Debugger.IsAttached)
- {
- //btnFiles.Enabled = true;
- }
-
CheckConfigs();
}
diff --git a/Common/Utils/Common.Utils.Extensions/BytesExtensions.cs b/Common/Utils/Common.Utils.Extensions/BytesExtensions.cs
index 6889edc1..187d8d1c 100644
--- a/Common/Utils/Common.Utils.Extensions/BytesExtensions.cs
+++ b/Common/Utils/Common.Utils.Extensions/BytesExtensions.cs
@@ -2,10 +2,38 @@
{
using System;
using System.Collections.Generic;
- using System.Linq;
public static class BytesExtensions
{
+ public static Int32 Int32BigEndian(this Byte[] bytes, Int32 start)
+ {
+ var _bytes = new Byte[4];
+
+ if (bytes.Length >= start + 4)
+ {
+ Array.Copy(bytes, start, _bytes, 0, 4);
+ Array.Reverse(_bytes);
+ }
+
+ return BitConverter.ToInt32(_bytes, 0);
+ }
+
+ public static Byte Byte(this Byte[] bytes, Int32 start)
+ {
+ var _byte = default(Byte);
+
+ if (bytes.Length > start)
+ {
+ _byte = bytes[start];
+ }
+
+ return _byte;
+ }
+
+
+
+
+
public const Int32 Int16Size = sizeof(Int16);
public const Int32 Int32Size = sizeof(Int32);
public const Int32 Int64Size = sizeof(Int64);
diff --git a/Common/modbus_master_csharp/.gitignore b/Common/modbus_master_csharp/.gitignore
deleted file mode 100644
index 67681578..00000000
--- a/Common/modbus_master_csharp/.gitignore
+++ /dev/null
@@ -1,450 +0,0 @@
-## Ignore Visual Studio temporary files, build results, and
-## files generated by popular Visual Studio add-ons.
-##
-## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
-
-# User-specific files
-*.rsuser
-*.suo
-*.user
-*.userosscache
-*.sln.docstates
-
-# User-specific files (MonoDevelop/Xamarin Studio)
-*.userprefs
-
-# Mono auto generated files
-mono_crash.*
-
-# Build results
-[Dd]ebug/
-[Dd]ebugPublic/
-[Rr]elease/
-[Rr]eleases/
-x64/
-x86/
-[Ww][Ii][Nn]32/
-[Aa][Rr][Mm]/
-[Aa][Rr][Mm]64/
-bld/
-[Bb]in/
-[Oo]bj/
-[Ll]og/
-[Ll]ogs/
-*.cache
-
-# Visual Studio 2015/2017 cache/options directory
-.vs/
-# Uncomment if you have tasks that create the projects static files in wwwroot
-#wwwroot/
-
-# Visual Studio 2017 auto generated files
-Generated\ Files/
-
-# MSTest test Results
-[Tt]est[Rr]esult*/
-[Bb]uild[Ll]og.*
-
-# NUnit
-*.VisualState.xml
-TestResult.xml
-nunit-*.xml
-
-# Build Results of an ATL Project
-[Dd]ebugPS/
-[Rr]eleasePS/
-dlldata.c
-
-# Benchmark Results
-BenchmarkDotNet.Artifacts/
-
-# .NET Core
-project.lock.json
-project.fragment.lock.json
-artifacts/
-
-# ASP.NET Scaffolding
-ScaffoldingReadMe.txt
-
-# StyleCop
-StyleCopReport.xml
-
-# Files built by Visual Studio
-*_i.c
-*_p.c
-*_h.h
-*.ilk
-*.meta
-*.obj
-*.iobj
-*.pch
-*.pdb
-*.ipdb
-*.pgc
-*.pgd
-*.rsp
-*.sbr
-*.tlb
-*.tli
-*.tlh
-*.tmp
-*.tmp_proj
-*_wpftmp.csproj
-*.log
-*.tlog
-*.vspscc
-*.vssscc
-.builds
-*.pidb
-*.svclog
-*.scc
-*.cache
-
-# Chutzpah Test files
-_Chutzpah*
-
-# Visual C++ cache files
-ipch/
-*.aps
-*.ncb
-*.opendb
-*.opensdf
-*.sdf
-*.cachefile
-*.VC.db
-*.VC.VC.opendb
-
-# Visual Studio profiler
-*.psess
-*.vsp
-*.vspx
-*.sap
-
-# Visual Studio Trace Files
-*.e2e
-
-# TFS 2012 Local Workspace
-$tf/
-
-# Guidance Automation Toolkit
-*.gpState
-
-# ReSharper is a .NET coding add-in
-_ReSharper*/
-*.[Rr]e[Ss]harper
-*.DotSettings.user
-
-# TeamCity is a build add-in
-_TeamCity*
-
-# DotCover is a Code Coverage Tool
-*.dotCover
-
-# AxoCover is a Code Coverage Tool
-.axoCover/*
-!.axoCover/settings.json
-
-# Coverlet is a free, cross platform Code Coverage Tool
-coverage*.json
-coverage*.xml
-coverage*.info
-
-# Visual Studio code coverage results
-*.coverage
-*.coveragexml
-
-# NCrunch
-_NCrunch_*
-.*crunch*.local.xml
-nCrunchTemp_*
-
-# MightyMoose
-*.mm.*
-AutoTest.Net/
-
-# Web workbench (sass)
-.sass-cache/
-
-# Installshield output folder
-[Ee]xpress/
-
-# DocProject is a documentation generator add-in
-DocProject/buildhelp/
-DocProject/Help/*.HxT
-DocProject/Help/*.HxC
-DocProject/Help/*.hhc
-DocProject/Help/*.hhk
-DocProject/Help/*.hhp
-DocProject/Help/Html2
-DocProject/Help/html
-
-# Click-Once directory
-publish/
-
-# Publish Web Output
-*.[Pp]ublish.xml
-*.azurePubxml
-# Note: Comment the next line if you want to checkin your web deploy settings,
-# but database connection strings (with potential passwords) will be unencrypted
-*.pubxml
-*.publishproj
-
-# Microsoft Azure Web App publish settings. Comment the next line if you want to
-# checkin your Azure Web App publish settings, but sensitive information contained
-# in these scripts will be unencrypted
-PublishScripts/
-
-# NuGet Packages
-*.nupkg
-# NuGet Symbol Packages
-*.snupkg
-# The packages folder can be ignored because of Package Restore
-**/[Pp]ackages/*
-# except build/, which is used as an MSBuild target.
-!**/[Pp]ackages/build/
-# Uncomment if necessary however generally it will be regenerated when needed
-#!**/[Pp]ackages/repositories.config
-# NuGet v3's project.json files produces more ignorable files
-*.nuget.props
-*.nuget.targets
-
-# Nuget personal access tokens and Credentials
-nuget.config
-
-# Microsoft Azure Build Output
-csx/
-*.build.csdef
-
-# Microsoft Azure Emulator
-ecf/
-rcf/
-
-# Windows Store app package directories and files
-AppPackages/
-BundleArtifacts/
-Package.StoreAssociation.xml
-_pkginfo.txt
-*.appx
-*.appxbundle
-*.appxupload
-
-# Visual Studio cache files
-# files ending in .cache can be ignored
-*.[Cc]ache
-# but keep track of directories ending in .cache
-!?*.[Cc]ache/
-
-# Others
-ClientBin/
-~$*
-*~
-*.dbmdl
-*.dbproj.schemaview
-*.jfm
-*.pfx
-*.publishsettings
-orleans.codegen.cs
-
-# Including strong name files can present a security risk
-# (https://github.com/github/gitignore/pull/2483#issue-259490424)
-#*.snk
-
-# Since there are multiple workflows, uncomment next line to ignore bower_components
-# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
-#bower_components/
-
-# RIA/Silverlight projects
-Generated_Code/
-
-# Backup & report files from converting an old project file
-# to a newer Visual Studio version. Backup files are not needed,
-# because we have git ;-)
-_UpgradeReport_Files/
-Backup*/
-UpgradeLog*.XML
-UpgradeLog*.htm
-ServiceFabricBackup/
-*.rptproj.bak
-
-# SQL Server files
-*.mdf
-*.ldf
-*.ndf
-
-# Business Intelligence projects
-*.rdl.data
-*.bim.layout
-*.bim_*.settings
-*.rptproj.rsuser
-*- [Bb]ackup.rdl
-*- [Bb]ackup ([0-9]).rdl
-*- [Bb]ackup ([0-9][0-9]).rdl
-
-# Microsoft Fakes
-FakesAssemblies/
-
-# GhostDoc plugin setting file
-*.GhostDoc.xml
-
-# Node.js Tools for Visual Studio
-.ntvs_analysis.dat
-node_modules/
-
-# Visual Studio 6 build log
-*.plg
-
-# Visual Studio 6 workspace options file
-*.opt
-
-# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
-*.vbw
-
-# Visual Studio LightSwitch build output
-**/*.HTMLClient/GeneratedArtifacts
-**/*.DesktopClient/GeneratedArtifacts
-**/*.DesktopClient/ModelManifest.xml
-**/*.Server/GeneratedArtifacts
-**/*.Server/ModelManifest.xml
-_Pvt_Extensions
-
-# Paket dependency manager
-.paket/paket.exe
-paket-files/
-
-# FAKE - F# Make
-.fake/
-
-# CodeRush personal settings
-.cr/personal
-
-# Python Tools for Visual Studio (PTVS)
-__pycache__/
-*.pyc
-
-# Cake - Uncomment if you are using it
-# tools/**
-# !tools/packages.config
-
-# Tabs Studio
-*.tss
-
-# Telerik's JustMock configuration file
-*.jmconfig
-
-# BizTalk build output
-*.btp.cs
-*.btm.cs
-*.odx.cs
-*.xsd.cs
-
-# OpenCover UI analysis results
-OpenCover/
-
-# Azure Stream Analytics local run output
-ASALocalRun/
-
-# MSBuild Binary and Structured Log
-*.binlog
-
-# NVidia Nsight GPU debugger configuration file
-*.nvuser
-
-# MFractors (Xamarin productivity tool) working folder
-.mfractor/
-
-# Local History for Visual Studio
-.localhistory/
-
-# BeatPulse healthcheck temp database
-healthchecksdb
-
-# Backup folder for Package Reference Convert tool in Visual Studio 2017
-MigrationBackup/
-
-# Ionide (cross platform F# VS Code tools) working folder
-.ionide/
-
-# Fody - auto-generated XML schema
-FodyWeavers.xsd
-
-# VS Code files for those working on multiple tools
-.vscode/*
-!.vscode/settings.json
-!.vscode/tasks.json
-!.vscode/launch.json
-!.vscode/extensions.json
-*.code-workspace
-
-# Local History for Visual Studio Code
-.history/
-
-# Windows Installer files from build outputs
-*.cab
-*.msi
-*.msix
-*.msm
-*.msp
-
-# JetBrains Rider
-.idea/
-*.sln.iml
-© 2021 GitHub, Inc.# These are some examples of commonly ignored file patterns.
-
-# You should customize this list as applicable to your project.
-# Learn more about .gitignore:
-# https://www.atlassian.com/git/tutorials/saving-changes/gitignore
-
-# Node artifact files
-node_modules/
-dist/
-
-# Compiled Java class files
-*.class
-
-# Compiled Python bytecode
-*.py[cod]
-
-# Log files
-*.log
-
-# Package files
-*.jar
-
-# Maven
-target/
-dist/
-
-# JetBrains IDE
-.idea/
-
-# Unit test reports
-TEST*.xml
-
-# Generated by MacOS
-.DS_Store
-
-# Generated by Windows
-Thumbs.db
-
-# Applications
-*.app
-*.exe
-*.war
-
-# Large media files
-*.mp4
-*.tiff
-*.avi
-*.flv
-*.mov
-*.wmv
-
-/src/.vs/modbus_master_csharp/v17/
-/src/.vs/modbus_master_csharp/FileContentIndex
-/src/modbus_master_csharp/obj/Debug
-/src/modbus_master_csharp/bin/Debug
-/src/.vs/modbus_master_csharp/v15
-
-/src/.vs/slnx.sqlite
-/src/_ReSharper.Caches/
-/_ReSharper.Caches/
diff --git a/Common/modbus_master_csharp/.vscode/extensions.json b/Common/modbus_master_csharp/.vscode/extensions.json
deleted file mode 100644
index bd092209..00000000
--- a/Common/modbus_master_csharp/.vscode/extensions.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "recommendations": [
- "mhutchie.git-graph",
- "eamodio.gitlens",
- "streetsidesoftware.code-spell-checker",
- "ms-vscode.cpptools",
- "alefragnani.bookmarks",
- "cschlosser.doxdocgen",
- "gruntfuggly.todo-tree"
- ]
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/App.config b/Common/modbus_master_csharp/App.config
deleted file mode 100644
index 193aecc6..00000000
--- a/Common/modbus_master_csharp/App.config
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Base/AppConst.cs b/Common/modbus_master_csharp/Base/AppConst.cs
deleted file mode 100644
index 9d974cff..00000000
--- a/Common/modbus_master_csharp/Base/AppConst.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-using XYLEM.Base.Files;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Reflection;
-
-namespace XYLEM.Base
-{
- internal static class AppConst
- {
- static ProgramLogCSVFileClass _Logger = new ProgramLogCSVFileClass();
-
- internal static ProgramLogCSVFileClass Logger { get { return _Logger; } }
-
- internal static bool IsBeta
- {
- get
- {
- return true;
- //return false;
- }
- }
-
- //
- // Summary:
- // Gets the product version associated with this application.
- //
- // Returns:
- // The product version.
- internal static string ProductVersion
- {
- get { return "1.0.0.1"; }
- }
-
-
- ///
- /// Return application MJK No.
- /// Have to be manuel changed by programmer for every application to fit install!
- ///
- /// return ex. "840126"
- internal static string ProductMainMJKNo()
- {
- return "MJK_MAGFLUX_MODBUS";
- }
-
- ///
- /// Return MJK Programs standard folder in My documents.
- ///
- /// return ex. "c:\...\My Documents\MJK Automation\"
- internal static string ProgramsUserFolderRootPath()
- {
- return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MJK Automation\\");
- }
-
-
- ///
- /// Return application folder in My documents.
- /// Have to be manuel changed by programmer for every application to fit install!
- ///
- /// return ex. "c:\...\My Documents\MJK Automation\840126\"
- internal static string ProgramUserFolderRootPath()
- {
- return Path.Combine(ProgramsUserFolderRootPath(), ProductMainMJKNo() + "\\");
- }
-
- ///
- /// Return application folder to use for user files.
- /// Have to be manuel changed by programmer for every application to fit install!
- ///
- /// return ex. "c:\...\My Documents\MJK Automation\- UserFileSave\"
- internal static string UserFileSavePath()
- {
- return Path.Combine(ProgramsUserFolderRootPath(), "- UserFileSave\\");
- }
-
- ///
- /// Return application folder to use for program user settings .
- /// Have to be manual changed by programmer for every application to fit install!
- ///
- /// return ex. "c:\...\My Documents\MJK Automation\840126\UserSettings\"
- internal static string UserFileSettingsPath()
- {
- return Path.Combine(ProgramUserFolderRootPath(), "UserSettings\\");
- }
-
- ///
- /// Try Create UserFileSavePath and SettingPath
- ///
- internal static void CreateStandardUserFolders()
- {
- try
- {
- if (!Directory.Exists(UserFileSavePath()))
- {
- Directory.CreateDirectory(UserFileSavePath());
- }
- if (!Directory.Exists(ProgramUserFolderRootPath()))
- {
- Directory.CreateDirectory(ProgramUserFolderRootPath());
- }
- }
- catch (Exception ex)
- {
- Logger.AddToProgramLogFile(true, "Error creating default user folders ", ex.Message);
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Base/ByteArrayExtensionClass.cs b/Common/modbus_master_csharp/Base/ByteArrayExtensionClass.cs
deleted file mode 100644
index ce2c4631..00000000
--- a/Common/modbus_master_csharp/Base/ByteArrayExtensionClass.cs
+++ /dev/null
@@ -1,314 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- internal static class ByteArrayExtensionClass
- {
- ///
- /// Compare if values in to array's is equal
- ///
- ///
- ///
- ///
- public static bool Compare(this byte[] b1, byte[] b2)
- {
- // Validate buffers are the same length.
- // This also ensures that the count does not exceed the length of either buffer.
- return b1.SequenceEqual(b2);
- }
-
- ///
- /// Copy a chunk of bytes from start index to a specific LongLength
- ///
- ///
- /// start offset 0..x
- /// LongLength of returned byte data array
- /// Return copy of byte data
- public static byte[] Copy(this byte[] from, long startIndex, long LongLength)
- {
- try
- {
- byte[] bArray = new byte[LongLength];
- Array.Copy(from, startIndex, bArray, 0, LongLength);
- return bArray;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "Copy()"));
- }
- }
-
- ///
- /// Copy a chunk of bytes to the end of array, starting from start offset
- ///
- ///
- /// start offset 0..x
- /// Return copy of byte data
- public static byte[] Copy(this byte[] from, long startIndex)
- {
- try
- {
- long LongLength = from.LongLength - startIndex;
- byte[] bArray = new byte[LongLength];
- Array.Copy(from, startIndex, bArray, 0, LongLength);
- return bArray;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "Copy()"));
- }
- }
-
- ///
- /// Remove a chunk of bytes at the end of array, staring from offset index
- ///
- ///
- /// offset 0..x
- /// Return copy of byte data
- public static byte[] Remove(this byte[] from, long fromIndex)
- {
- try
- {
- byte[] bArray = new byte[fromIndex];
- if (bArray.LongLength < fromIndex)
- {
- return from;
- }
- Array.Copy(from, 0, bArray, 0, fromIndex);
- return bArray;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "Remove()"));
- }
- }
-
-
- ///
- /// Copy bytes until this character
- ///
- /// bytes to find character in
- /// detection character
- ///
- internal static IEnumerable CopyUntil(this IEnumerable toInSeach, char untilThisCharacter)
- {
- try
- {
- if (toInSeach != null)
- {
- var withCharacter = toInSeach.TakeWhile(ch => ch != untilThisCharacter);
- // has any data after this
- if (withCharacter.Count() > 1)
- {
- return withCharacter;
- }
- }
- return null; // nothing to return
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "CopyUntil()"));
- }
- }
-
- ///
- /// Copy bytes after this character
- ///
- /// bytes to find character in
- /// detection character
- ///
- internal static IEnumerable CopyAfterThis(this IEnumerable toInSeach, char afterFirstCharacterOfThis)
- {
- try
- {
- if (toInSeach != null)
- {
- var withCharacter = toInSeach.SkipWhile(ch => ch != afterFirstCharacterOfThis);
- // has any data after this
- if (withCharacter.Count() > 1)
- {
- return withCharacter.Skip(1);
- }
- }
- return null; // nothing to return
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "CopyAfterThis()"));
- }
- }
-
- ///
- /// Copy bytes after this sequence of bytes
- ///
- /// bytes to find character in
- /// detection sequence
- ///
- internal static IEnumerable CopyAfterThis(this IEnumerable toSeachIn, IEnumerable afterSequenceThis)
- {
- try
- {
- var toSeachNow = toSeachIn;
- while ((toSeachNow != null) && (toSeachNow.Count() > 0) && (afterSequenceThis != null))
- {
- var startCh = afterSequenceThis.First();
- var sequenceLng = afterSequenceThis.Count();
- toSeachNow = toSeachNow.SkipWhile(ch => ch != startCh);
- // If there is data after a possible sequence.. check if it have sequnece
- if ((toSeachNow.Count() > sequenceLng) && afterSequenceThis.SequenceEqual(toSeachNow.Take(sequenceLng)))
- {
- if (toSeachNow.Count() > sequenceLng)
- {
- return toSeachNow.Skip(afterSequenceThis.Count());
- }
- return null; // nothing after sequence to return
- }
- // Not found
- if ((toSeachNow == null) || (toSeachNow.Count() == 0))
- {
- return null; // nothing to return
- }
- // increase to next to find next start
- toSeachNow = toSeachNow.Skip(1);
- }
- return null; // nothing to return
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "CopyAfterThis()"));
- }
- }
-
- ///
- /// Swap high and low byte in a word(16bit) for all words in a byte array (use ex. to a line data correct for conversion to computer U16 from modbus u16)
- ///
- /// Data to swap (SWAP IS NOT DONE ON A COPY, BUT ON THE ARRAY GIVEN AS INPUT
- /// return swapped input array reference (done to help supporting single line code use ex. "var data = byteArrayNeedingSwap.SwapByteInWord();")
- public static byte[] SwapByteInWord(this byte[] data)
- {
- try
- {
- if (data != null)
- {
- for (long i = 0; i < data.LongLength; i += 2)
- {
- byte b = data[i];
- data[i] = data[i + 1];
- data[i + 1] = b;
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "SwapByteInWord()"));
- }
- }
-
-
- ///
- /// Compare if to array's has the same content (like array1 == array2)
- ///
- ///
- ///
- /// return true if the same
- public static bool IsEqual(this byte[] array1, byte[] array2)
- {
- try
- {
- if ((array1 != null) && (array2 != null) && (array1.LongLength == array2.LongLength))
- {
- // To speed up
- var result = array1.SequenceEqual(array2);
- //{
- //#if (!DEBUG)
- //#error Test code!!!
- //#endif
- //if (!result) {
- // var test = "Not the same!!";
- // }
- //}
- return result;
- }
- return false;// not the same
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "IsEqual()"));
- }
- }
-
- ///
- /// Slice an array of bytes in the same sizes
- ///
- /// Data to slice an array of bytes from
- /// start in data for beginning slice of bytes
- /// The length of each slice of bytes
- /// List of byte slices with the same size
- public static List SliceSameSize(this byte[] source, long startIndex, long eachSliceLength)
- {
- try
- {
- if (source == null)
- {
- return null;
- }
- var LongLength = source.LongLength;
- var slices = new List();
- for (long offset = startIndex; offset < LongLength; offset += eachSliceLength)
- {
- slices.Add(Copy(source, offset, eachSliceLength));
- }
- return slices;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "SliceSameSize()"));
- }
- }
-
- ///
- /// Slice a single array with a specific length
- ///
- /// Data to slice an array of bytes from
- /// start in data for beginning slice of bytes
- /// how long is the slice from start index
- ///
- public static byte[] Slice(this byte[] source, long startIndex, long length)
- {
- try
- {
- var returnValue = new byte[length];
- Array.Copy(source, startIndex, returnValue, 0, length);
- return returnValue;
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "Slice()"));
- }
- }
-
-
- ///
- /// Fill or pad array with a specific value
- ///
- ///
- ///
- ///
- public static byte[] Fill(this byte[] data, byte valueForFill)
- {
- if (data != null)
- {
- for (long i = 0; i < data.LongLength; i++)
- {
- data[i] = valueForFill;
- }
- }
- return data;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Base/Convert1970SecToTime.cs b/Common/modbus_master_csharp/Base/Convert1970SecToTime.cs
deleted file mode 100644
index 6dfa2ad8..00000000
--- a/Common/modbus_master_csharp/Base/Convert1970SecToTime.cs
+++ /dev/null
@@ -1,153 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- internal enum TimeType
- {
- UTC,
- Local
- };
-
- internal static class TimeConvertClass
- {
- ///
- /// convert to a text showing file time ex. [20151201-135917]
- ///
- ///
- ///
- internal static string ToFileTimeTxt(this DateTime time)
- {
- return String.Format("[{0}{1:00}{2:00}-{3:00}{4:00}{5:00}]", time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
- }
-
- ///
- /// Convert 1970Sec to 32-bit time to Time
- ///
- ///
- ///
- internal static TimeSpan ConvertTimeSpan(this UInt32 timeSec)
- {
- return new TimeSpan((int)(timeSec/3600), (int)(timeSec%3600/60), (int)(timeSec%60));
- }
-
- internal static string ConvertSecondsToTimeSpanTxt(this Int32 timeSec)
- {
- return (timeSec >= 0 ? "" : "-") + ((UInt32)Math.Abs(timeSec)).ConvertSecondsToTimeSpanTxt();
- }
-
- internal static string ConvertToTimeSpanTxt(this TimeSpan time)
- {
- if (time.Days > 0)
- {
- return string.Format((time.Days > 1 ? "{0} days " : "1 day ") + "{1:00}:{2:00}:{3:00}", time.Days, time.Hours, time.Minutes, time.Seconds);
- }
- return string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
- }
-
- internal static string ConvertSecondsToTimeSpanTxt(this UInt32 timeSec)
- {
- TimeSpan time = new TimeSpan((int)(timeSec / 3600), (int)(timeSec % 3600 / 60), (int)(timeSec % 60));
- return time.ConvertToTimeSpanTxt();
- }
-
- internal static string ConvertSecondsToTimeSpanTxt(this Int16 timeSec)
- {
- return ConvertSecondsToTimeSpanTxt((Int32)timeSec);
- }
-
- internal static string ConvertSecondsToTimeSpanTxt(this UInt16 timeSec)
- {
- return ConvertSecondsToTimeSpanTxt((UInt32)timeSec);
- }
-
- internal static string ConvertMinuteToTimeSpanTxt(this Int16 timeMin)
- {
- return ConvertSecondsToTimeSpanTxt((Int32)timeMin * 60);
- }
-
- internal static string ConvertMinuteToTimeSpanTxt(this UInt16 timeMin)
- {
- return ConvertSecondsToTimeSpanTxt((UInt32)timeMin * 60);
- }
-
- internal static string ConvertHourToTimeSpanTxt(this Int16 timeHour)
- {
- return ConvertSecondsToTimeSpanTxt((Int32)timeHour * 3600);
- }
-
- internal static string ConvertHourToTimeSpanTxt(this UInt16 timeHour)
- {
- return ConvertSecondsToTimeSpanTxt((UInt32)timeHour * 3600);
- }
-
-
-
- ///
- /// Convert 1970Sec to 32-bit time to Time
- ///
- ///
- ///
- internal static DateTime Convert1970SecToTime(this UInt32 timeSec1970, TimeType timetype)
- {
- return timetype == TimeType.Local ?
- (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).AddSeconds(timeSec1970)
- : (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(timeSec1970);
- }
-
- ///
- /// Convert Time to 1970Sec
- ///
- ///
- ///
- internal static UInt32 ConvertTimeTo1970Sec(this DateTime time, TimeType timetype)
- {
- TimeSpan ts = timetype == TimeType.Local ?
- (time - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local))
- : (time.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
- return Convert.ToUInt32(ts.TotalSeconds);
- }
-
- ///
- /// Convert 2000Sec to 32-bit time to Time
- ///
- ///
- ///
- internal static DateTime Convert2000SecToTime(this UInt32 timeSec2000)
- {
- return (new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(timeSec2000);
- }
-
- ///
- /// Convert Time to 2000Sec
- ///
- ///
- ///
- internal static UInt32 ConvertTimeTo2000Sec(this DateTime time, TimeType timetype)
- {
- TimeSpan ts = timetype == TimeType.Local ?
- (time - new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Local))
- : (time.ToUniversalTime() - new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc));
- return Convert.ToUInt32(ts.TotalSeconds);
- }
-
- ///
- /// Convert time to a String
- ///
- ///
- ///
- public static String ToLocalDateTimeString(this DateTime time)
- {
- DateTime localTime;
- localTime = (time.Kind == DateTimeKind.Utc) ? time.ToLocalTime() : time;
- return (localTime.Year.ToString().PadLeft(4, '0') + "/" + localTime.Month.ToString().PadLeft(2, '0') + "/" + localTime.Day.ToString().PadLeft(2, '0') + " "
- + localTime.Hour.ToString().PadLeft(2, '0') + ":" + localTime.Minute.ToString().PadLeft(2, '0') + ":" + localTime.Second.ToString().PadLeft(2, '0'));
- }
-
- public static readonly bool IsLocalHourFormatAM_PM = new DateTime(2000, 1, 1, 13, 0, 0).ToLongTimeString().ToLower().Contains("pm");
- }
-}
-
diff --git a/Common/modbus_master_csharp/Base/DataUnion.cs b/Common/modbus_master_csharp/Base/DataUnion.cs
deleted file mode 100644
index e4c7c0f1..00000000
--- a/Common/modbus_master_csharp/Base/DataUnion.cs
+++ /dev/null
@@ -1,459 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- public static class DataUnionTools
- {
- public static byte[] Reverse(this byte[] data)
- {
- Array.Reverse(data);
- return data;
- }
- }
-
- ///
- /// Convert DataObjClass.DataType to Byte
- ///
- [StructLayout(LayoutKind.Explicit)]
- public struct DataUnion
- {
- //----------------------------- Data String to Convert Rx to ----------------------
- #region ---- Inset Data Bytes in union --------
- public enum DataByteLayoutType
- {
- Normal,
- SwapAll,
- SwapWords // KellerType
- }
-
- internal UInt32 Conv32BitToLowAdrHighValue(UInt32 input)
- {
- return (input >> 16) | (input << 16);
- }
-
- ///
- /// Convert input byte data to union data
- ///
- ///
- ///
- public DataUnion PutByteArray(Byte[] bInputArray, DataByteLayoutType byteType)
- {
- if (byteType == DataByteLayoutType.SwapAll)
- {
- Array.Reverse(bInputArray);
- }
- //dataRxText = "";
- if ((bInputArray == null) || (bInputArray.Length == 0))
- {
- u64Data = 0;
- return this;
- }
- bData = bInputArray[0];
- if (bInputArray.Length == 1)
- {
- return this;
- }
-
- bData1 = bInputArray[1];
- if (bInputArray.Length == 2)
- { // 16bit / 2 x 8bit
- return this;
- }
-
- bData2 = bInputArray[2];
- if (bInputArray.Length == 3)
- {
- if (byteType == DataByteLayoutType.SwapWords)
- {
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- bData3 = bInputArray[3];
- if (bInputArray.Length == 4)
- {// 32bit / 4 x 8bit
- if (byteType == DataByteLayoutType.SwapWords)
- {
- u32Data = Conv32BitToLowAdrHighValue(u32Data);
- }
- return this;
- }
-
- bData4 = bInputArray[4];
- if (bInputArray.Length == 5)
- {
- if (byteType == DataByteLayoutType.SwapWords)
- {
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- bData5 = bInputArray[5];
- if (bInputArray.Length == 6)
- {
- if (byteType == DataByteLayoutType.SwapWords)
- {
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- bData6 = bInputArray[6];
- if (bInputArray.Length == 7)
- {
- if (byteType == DataByteLayoutType.SwapWords)
- {
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- bData7 = bInputArray[7];
- if (byteType == DataByteLayoutType.SwapWords)
- { // 64bit / 8 x 8bit
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- #endregion
-
- #region ---- Put data as Value in to union -----
- public void PutValue(UInt32 u32DataIn)
- {
- u32Data = u32DataIn;
- }
-
- public void PutValue(Int32 s32DataIn)
- {
- s32Data = s32DataIn;
- }
-
- public void PutValue(Single f32DataIn)
- {
- f32Data = f32DataIn;
- }
-
- public void PutValue(UInt64 u64DataIn)
- {
- u64Data = u64DataIn;
- }
-
- public void PutValue(Int64 s64DataIn)
- {
- s64Data = s64DataIn;
- }
-
- public void PutValue(double f64DataIn)
- {
- f64Data = f64DataIn;
- }
- #endregion
-
- #region ---- Get ByteArray from input as a value ----
- public byte[] GetByteArray()
- {
- return new byte[] { bData, bData1, bData2, bData3, bData4, bData5, bData6, bData7 };
- }
-
-
- void DoTxByteLayout(ref byte[] txData, DataByteLayoutType type)
- {
- try
- {
- if ((txData == null) || (txData.Length == 0))
- {
- throw new Exception("Has no txData");
- }
- switch (type)
- {
- case DataByteLayoutType.SwapAll: Array.Reverse(txData); break;
- case DataByteLayoutType.SwapWords:
- if (txData.Length == 4)
- { // 32bit / 2 x word
- byte[] firstWord = new byte[2];
- Array.Copy(txData, firstWord, 2);
- Array.Copy(txData, 2, txData, 0, 2);
- Array.Copy(firstWord, 0, txData, 2, 2);
- }
- else if (txData.Length == 8)
- { // 64bit / 2 x word
- throw new Exception("SwapWords Not Supported!");
- }
- break;
- case DataByteLayoutType.Normal: break; // Do nothing
- default: throw new Exception("Unkown type = " + type.ToString());
- }
- }
- catch (Exception ex)
- {
- throw new Exception("Error in " + this + " in func. DoTxByteLayout()! message = " + ex.Message);
- }
- }
-
-
- ///
- /// Convert to Tx data to unsigned 16bit
- ///
- ///
- ///
- public byte[] GetByteArray(UInt16 u16DataIn, DataByteLayoutType byteType)
- {
- byte[] bDataRet = new byte[2];
- u16Data = u16DataIn;
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to signed 16bit
- ///
- ///
- ///
- public byte[] GetByteArray(Int16 s16DataIn, DataByteLayoutType byteType)
- {
- byte[] bDataRet = new byte[2];
- s16Data = s16DataIn;
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to unsigned 32bit
- ///
- ///
- ///
- public byte[] GetByteArray(UInt32 u32DataIn, DataByteLayoutType byteType)
- {
- PutValue(u32DataIn);
- byte[] bDataRet = new byte[4];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to sign 32bit
- ///
- ///
- ///
- public byte[] GetByteArray(Int32 s32DataIn, DataByteLayoutType byteType)
- {
- PutValue(s32DataIn);
- byte[] bDataRet = new byte[4];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to Single 32bit
- ///
- ///
- ///
- public byte[] GetByteArray(Single f32DataIn, DataByteLayoutType byteType)
- {
- PutValue(f32DataIn);
- byte[] bDataRet = new byte[4];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to unsigned 64bit
- ///
- ///
- ///
- public byte[] GetByteArray(UInt64 u64DataIn, DataByteLayoutType byteType)
- {
- PutValue(u64DataIn);
- byte[] bDataRet = new byte[8];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- bDataRet[4] = bData4;
- bDataRet[5] = bData5;
- bDataRet[6] = bData6;
- bDataRet[7] = bData7;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to double (F64bit)
- ///
- ///
- ///
- public byte[] GetByteArray(Int64 s64DataIn, DataByteLayoutType byteType)
- {
- PutValue(s64DataIn);
- byte[] bDataRet = new byte[8];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- bDataRet[4] = bData4;
- bDataRet[5] = bData5;
- bDataRet[6] = bData6;
- bDataRet[7] = bData7;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to unsigned 64bit
- ///
- ///
- ///
- public byte[] GetByteArray(double f64DataIn, DataByteLayoutType byteType)
- {
- PutValue(f64DataIn);
- byte[] bDataRet = new byte[8];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- bDataRet[4] = bData4;
- bDataRet[5] = bData5;
- bDataRet[6] = bData6;
- bDataRet[7] = bData7;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- #endregion
-
- #region ---- Return Union data as a value ----
- public byte U8Data { get { return bData; } set { u16Data = bData; } }
- public byte U8Data0 { get { return bData; } }
- public byte U8Data1 { get { return bData1; } }
- public byte U8Data2 { get { return bData2; } }
- public byte U8Data3 { get { return bData3; } }
- public byte U8Data4 { get { return bData4; } }
- public byte U8Data5 { get { return bData5; } }
- public byte U8Data6 { get { return bData6; } }
- public byte U8Data7 { get { return bData7; } }
-
- public UInt16 U16Data { get { return u16Data; } set { u16Data = value; } }
- public UInt16 U16Data0 { get { return u16Data; } }
- public UInt16 U16Data1 { get { return u16Data1; } }
- public UInt16 U16Data2 { get { return u16Data2; } }
- public UInt16 U16Data3 { get { return u16Data3; } }
-
- public Int16 S16Data { get { return s16Data; } }
- public Int16 S16Data0 { get { return s16Data; } }
- public Int16 S16Data1 { get { return s16Data1; } }
- public Int16 S16Data2 { get { return s16Data2; } }
- public Int16 S16Data3 { get { return s16Data3; } }
-
- public UInt32 U32Data { get { return u32Data; } set { u32Data = value; } }
- public UInt32 U32Data0 { get { return u32Data; } }
- public UInt32 U32Data1 { get { return u32Data1; } }
-
- public Int32 S32Data { get { return s32Data; } set { s32Data = value; } }
- public Int32 S32Data0 { get { return s32Data; } }
- public Int32 S32Data1 { get { return s32Data1; } }
-
- public Single F32Data { get { return f32Data; } set { f32Data = value; } }
-
- public UInt64 U64Data { get { return u64Data; } }
- public Int64 S64Data { get { return s64Data; } }
- public double F64Data { get { return f64Data; } }
- #endregion
-
- ///
- /// Clear all data and return emptyunion
- ///
- ///
- public DataUnion ClearData()
- {
- u64Data = 0;
- return this;
- }
-
- #region ---- Field Union Array ----
- //----------------------------- Field Union array -----------------------------
- [FieldOffset(0)]
- private byte bData;
- [FieldOffset(1)]
- private byte bData1;
- [FieldOffset(2)]
- private byte bData2;
- [FieldOffset(3)]
- private byte bData3;
- [FieldOffset(4)]
- private byte bData4;
- [FieldOffset(5)]
- private byte bData5;
- [FieldOffset(6)]
- private byte bData6;
- [FieldOffset(7)]
- private byte bData7;
-
- [FieldOffset(0)]
- private UInt16 u16Data;
- [FieldOffset(2)]
- private UInt16 u16Data1;
- [FieldOffset(4)]
- private UInt16 u16Data2;
- [FieldOffset(6)]
- private UInt16 u16Data3;
-
- [FieldOffset(0)]
- private Int16 s16Data;
- [FieldOffset(2)]
- private Int16 s16Data1;
- [FieldOffset(4)]
- private Int16 s16Data2;
- [FieldOffset(6)]
- private Int16 s16Data3;
-
- [FieldOffset(0)]
- private UInt32 u32Data;
- [FieldOffset(4)]
- private UInt32 u32Data1;
-
- [FieldOffset(0)]
- private Int32 s32Data;
- [FieldOffset(4)]
- private Int32 s32Data1;
-
- [FieldOffset(0)]
- private Single f32Data;
- [FieldOffset(4)]
- private Single f32Data1;
-
- [FieldOffset(0)]
- private UInt64 u64Data;
-
- [FieldOffset(0)]
- private Int64 s64Data;
-
- [FieldOffset(0)]
- private double f64Data;
- #endregion
-
- };
-}
diff --git a/Common/modbus_master_csharp/Base/Files/PathTools.cs b/Common/modbus_master_csharp/Base/Files/PathTools.cs
deleted file mode 100644
index 912c9e0b..00000000
--- a/Common/modbus_master_csharp/Base/Files/PathTools.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base.Files
-{
- internal class PathTools
- {
- ///
- /// File path trunk
- ///
- /// ex. c:\mainDir\subDir\text.text
- /// ex. 12 char
- /// ex. will return "...\subDir\text.text" because "subDir\text.text" is > 12
- public static string FilePathStartTrunk(string dirPath, int trunkLength)
- {
- try
- {
- if (!String.IsNullOrEmpty(dirPath) && (dirPath.Length > 40))
- { // if to big .. then trunk it
- var pathSplits = dirPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
- if (pathSplits.Length > 0)
- { // are able to trunk
- dirPath = "";
- foreach (var item in pathSplits.Reverse())
- {
- dirPath = CombineDirAndFileSubPath(item, dirPath);
- if (dirPath.Length > 40)
- {
- dirPath = CombineDirAndFileSubPath("...", dirPath);
- break; // max length is now then just exit loop
- }
- }
- }
- }
- return dirPath;
- }
- catch (Exception ex)
- {
- AppConst.Logger.AddFuncLog(true, "PathTools", "FilePathStartTrunk()", ex);
- }
- return "?";
- }
-
- ///
- /// Create the directory path
- ///
- ///
- ///
- public static Boolean CreateDirPath(string dirPath)
- {
- try
- {
- // Determine whether the directory exists.
- if (Directory.Exists(dirPath))
- {
- //That path exists already
- return false;
- }
-
- // Try to create the directory.
- DirectoryInfo di = Directory.CreateDirectory(dirPath);
- return false;
- }
- catch
- {
- return true;
- }
- }
-
- ///
- /// Create the directory for a file path
- ///
- ///
- /// return true on error
- public static bool CreateDirPathForFile(string pathForFile)
- {
- try
- {
- return CreateDirPath(GetDirPath(pathForFile));
- }
- catch
- {
- return true;
- }
- }
-
- ///
- /// Combine a directory path and sub path to a compleate path
- ///
- ///
- ///
- ///
- public static string CombineDirAndFileSubPath(string dirPath, string subFilePath)
- {
- dirPath = dirPath.Trim().EndsWith("\\") ?
- dirPath.Trim().Remove(dirPath.LastIndexOf("\\")) :
- dirPath.Trim();
- return Path.Combine(dirPath, subFilePath.Trim());
- }
-
- ///
- /// Get directory path
- ///
- ///
- /// return true on error
- public static string GetDirPath(string filePath)
- {
- return filePath.Remove(filePath.Trim().LastIndexOf("\\"));
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Base/Files/ProgramLogCSVFileClass.cs b/Common/modbus_master_csharp/Base/Files/ProgramLogCSVFileClass.cs
deleted file mode 100644
index 3a573247..00000000
--- a/Common/modbus_master_csharp/Base/Files/ProgramLogCSVFileClass.cs
+++ /dev/null
@@ -1,232 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading.Tasks;
-
-
-namespace XYLEM.Base.Files
-{
- public class ProgramLogCSVFileClass
- {
- private int _LogCountErrors = -1;
- private int _LogCountTotal = -1;
-
- public int LogCountErrors { get { return _LogCountErrors; } }
- public int LogCountTotal { get { return _LogCountTotal; } }
-
- public string StdLogFilePath = null;
-
- public event EventHandler OnErrorIsAdded;
-
-#if (!DEBUG)
- public bool DoTimeStamp = false;
-#else
- /*#warning DoTimeStamp is true!!!!!!!!!!!!!!!!
- public bool DoTimeStamp = true;*/
- public bool DoTimeStamp = false;
-#endif
- ///
- /// init standard program logger
- ///
- /// use a custom log folder or null if use default
- /// set a custom log file name without extension (ex. "UserCustomLogFile") or null if use default
- public ProgramLogCSVFileClass(string stdLogFolderPath = null, string filename = null)
- {
- if (String.IsNullOrEmpty(filename))
- {
- filename = $"{AppConst.ProductVersion}_program_log";
- }
- if (!string.IsNullOrEmpty(stdLogFolderPath))
- {
- if (!Directory.Exists(stdLogFolderPath))
- {
- PathTools.CreateDirPath(stdLogFolderPath);
- }
- StdLogFilePath=Path.Combine(stdLogFolderPath, filename + ".txt");
- }
- else
- {
- this.StdLogFilePath = Path.Combine(AppConst.ProgramUserFolderRootPath(), filename + ".txt");
-#if (DEBUG)
- Console.WriteLine($"Using standard program log path:\n{this.StdLogFilePath}");
-#endif
- }
- }
-
- ///
- /// Automated get function name for the function calling this
- /// Used for automating getting a function name to write in a log
- ///
- /// Add extra message to log with function name
- /// "[CALLING_FUNCTION_NAME]() -> [inclMsg]"
- [MethodImpl(MethodImplOptions.NoInlining)]
- public string GetCurrentMethod(string inclMsg = null)
- {
- var st = new StackTrace();
- var sf = st.GetFrame(1);
-
- var nameTxt = $"{sf.GetMethod().Name}()";
- if (!String.IsNullOrEmpty(inclMsg))
- {
- nameTxt += " -> " + inclMsg;
- }
- return nameTxt;
- }
-
- ///
- /// Automated get function name for the function calling this
- /// Used for automating getting a function name to write in a log
- ///
- /// Add extra message to log with function name
- /// "[CALLING_FUNCTION_NAME]() -> [inclMsg]"
- [MethodImpl(MethodImplOptions.NoInlining)]
- public static string GetCurrentStaticMethod(string inclMsg = null)
- {
- var st = new StackTrace();
- var sf = st.GetFrame(1);
-
- var nameTxt = $"{sf.GetMethod().Name}()";
- if (!String.IsNullOrEmpty(inclMsg))
- {
- nameTxt += " -> " + inclMsg;
- }
- return nameTxt;
- }
-
- internal void AddToLogFile(bool isError, string nameSingleLine, string infoMultibleLines)
- {
- AddToLogFile(isError, StdLogFilePath, nameSingleLine, infoMultibleLines);
- }
-
- internal void AddToLogFile(bool isError, string LogFilePath, string nameSingleLine, string infoMultibleLines)
- {
- try
- {
- if (isError)
- {
- _LogCountErrors++;
- try
- {
- if (OnErrorIsAdded != null)
- {
- OnErrorIsAdded(null, null);
- }
- }
- catch { } // Don't handle this if something breaks down
- }
- _LogCountTotal++;
- if (System.IO.File.Exists(LogFilePath))
- {
- FileInfo f = new FileInfo(LogFilePath);
- if (f.Length > (DoTimeStamp ? 1000000 : 10000))
- {
- f.Delete();
- }
- }
- else
- {
- PathTools.CreateDirPathForFile(LogFilePath);
- }
- var message = infoMultibleLines;
- var length = message.Length;
- File.AppendAllText(LogFilePath, "¤¤¤ " + nameSingleLine.Trim() + " \"" + DateTime.Now.ToString() + "\" ¤¤¤ " + Environment.NewLine
- + message + Environment.NewLine);
-#if (DEBUG)
- System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff ") +
- " ¤¤¤ " + nameSingleLine.Trim() + " ¤¤¤ " + Environment.NewLine
- + message
- );
-#endif
- }
- catch (Exception ex)
- { // Ups just to make sure that this don't result in program is closed
- string test = ex.ToMessageText();
- }
- }
-
- ///
- /// Add a time stamp in program log file.. used to time differend code / controls load time
- ///
- /// class or window / control obkject to make time stamp for
- /// description text
- /// Force making log and ignore DoTimeStamp setting
- internal void AddToTimestampLog(object processObj, string desc, bool forceLog = false)
- {
- try
- {
- if (DoTimeStamp || forceLog)
- {
- AddToLogFile(false, StdLogFilePath, processObj.ToString() + DateTime.Now.ToString(" [HH:mm:ss fff]"), desc);
- }
- }
- catch { }
- }
-
- internal void AddToProgramLogFile(bool isError, string nameSingleLine, string infoMultibleLines)
- {
- AddToLogFile(isError, StdLogFilePath, nameSingleLine, infoMultibleLines);
- }
-
- ///
- /// Add to program log
- ///
- /// Exception to log
- /// Is an error or just as log
- /// what class or where function is located in
- /// what function it was in like "myFunc()" and null if not used
- /// Additional information also to include like "while doing x and y..."
- internal void ToLog(Exception ex, bool isError, string className, string functionName = null, string dataInfo = null)
- {
- AddToProgramLogFile(isError, LogMessageTool.ToFuncText(isError, className, functionName),
- (String.IsNullOrEmpty(dataInfo) ? "" : dataInfo + ((ex != null) ? Environment.NewLine : "")) // Add data info if used
- + ((ex != null) ? ex.ToMessageText() : ""));
- }
-
- internal void AddFuncLog(bool isError, string className, string functionName, string dataInfo, Exception ex)
- {
- ToLog(ex, isError, className, functionName, dataInfo);
- }
-
- internal void AddFuncLog(bool isError, string className, string functionName, Exception ex)
- {
- AddFuncLog(isError, className, functionName, null, ex);
- }
-
- internal void AddFuncLog(bool isError, string className, string functionName, string dataInfo)
- {
- AddFuncLog(isError, className, functionName, dataInfo, null);
- }
-
- internal void AddClassInitLog(bool isError, string className, Exception ex)
- {
- AddToProgramLogFile(isError, LogMessageTool.ToInitText(isError, className), ((ex != null) ? ex.ToMessageText() : ""));
- }
-
- internal void AddClassInitLog(bool isError, string className, string dataInfo, Exception ex)
- {
- AddToProgramLogFile(isError, LogMessageTool.ToInitText(isError, className, dataInfo), ((ex != null) ? ex.ToMessageText() : ""));
- }
-
- internal void OpenProgramLogFile()
- {
- OpenLogFile(StdLogFilePath);
- }
-
-
- internal void OpenLogFile(string LogFilePath)
- {
- try
- {
- Process.Start(LogFilePath);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error Open Log " + Environment.NewLine + ex.ToMessageText());
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Base/LogMessageTool.cs b/Common/modbus_master_csharp/Base/LogMessageTool.cs
deleted file mode 100644
index 5229e356..00000000
--- a/Common/modbus_master_csharp/Base/LogMessageTool.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- public static class LogMessageTool
- {
- ///
- /// Return Type Name as a string
- ///
- ///
- ///
- ///
- static public string TypeName(this T obj)
- {
- Type t;
- if (obj == null)
- {
- t = typeof(T);
- }
- else
- {
- t = obj.GetType();
- }
- return t.Name;
- }
-
- public static string ToMessageText(this Exception ex)
- {
- if (ex != null)
- {
- var message = "";
- var innerMessage = "";
- if (ex.InnerException != null)
- {
- innerMessage = ToMessageText(ex.InnerException);
- }
- if ((ex.Message != null) && !String.IsNullOrEmpty(ex.Message))
- {
- message = ex.Message;
- }
- if (!String.IsNullOrEmpty(innerMessage))
- {
- message += (!String.IsNullOrEmpty(message) ? Environment.NewLine : "") + innerMessage;
- }
- return message;
- }
- return "";
- }
-
- public static string ToFuncText(bool isError, string className, string functionName)
- {
- var message = (isError ? "Error in class" : "Class ") + className + " and func. " + functionName;
-#if(DEBUG)
- System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff ") + message);
-#endif
- return message;
- }
-
- public static string ToInitText(bool isError, string className)
- {
- var message = (isError ? "Error in init of " : "Init of ") + className;
-#if(DEBUG)
- System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff ") + message);
-#endif
- return message;
- }
-
- public static string ToInitText(bool isError, string className, string dataInfo)
- {
- return ToInitText(isError, className + " info = " + dataInfo);
- }
-
- public static string ToFuncErrorText(this Exception ex, string className, string functionName)
- {
- return ToFuncText(true, className, functionName + ((ex == null) ? "" : Environment.NewLine + "Message = " + ex.ToMessageText()));
- }
-
- public static string ToFuncErrorText(this Exception ex, string className, string functionName, string dataInfo)
- {
- return ToFuncText(true, className, functionName + Environment.NewLine + dataInfo + ((ex == null) ? "" : Environment.NewLine + "Message = " + ex.ToMessageText()));
- }
-
- public static string ToFuncErrorText(string className, string functionName, string dataInfo)
- {
- return ToFuncText(true, className, functionName + Environment.NewLine + dataInfo);
- }
-
- public static string ToFuncErrorText(string className, string functionName)
- {
- return ToFuncText(true, className, functionName);
- }
-
- public static string ToInitErrorText(this Exception ex, string className)
- {
- return ToInitText(true, className + ((ex == null) ? "" : Environment.NewLine + "Message = " + ex.ToMessageText()));
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Base/NumberConvert.cs b/Common/modbus_master_csharp/Base/NumberConvert.cs
deleted file mode 100644
index 6d8b975d..00000000
--- a/Common/modbus_master_csharp/Base/NumberConvert.cs
+++ /dev/null
@@ -1,602 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- public static class NumberConvert
- {
- public static readonly string ColumnSeperatorCSV = ((2.3).ToString().Contains(".") ? "," : ";");
- private static readonly int base10 = 10;
- private static readonly char[] cHexa = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
- private static readonly int[] iHexaNumeric = new int[] { 10, 11, 12, 13, 14, 15 };
- private static readonly int[] iHexaIndices = new int[] { 0, 1, 2, 3, 4, 5 };
- private static readonly int asciiDiff = 48;
-
- public static string PadLeft(this String text, int minLength)
- {
- int iCount = minLength - text.Length;
- String textRet = "";
- if (iCount > 0)
- {
- textRet = new String('0', iCount);
- }
- return textRet + text;
- }
-
- ///
- /// Tag for values input is done as "decimal" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsDecimalTag = "decimal";
-
- ///
- /// Tag for values input is done as "binary" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsBinaryTag = "binary";
-
-
- ///
- /// Tag for values input is done as "octal" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsOctalEndTag = "octal";
-
- ///
- /// Tag for values input is done as "0o" and is placed ex. in front the value that needs to be converted
- ///
- public static readonly string ValueInputAsOctalFrontTag = "0o";
-
- ///
- /// Tag for values input is done as "hex" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsHexEndTag = "hex";
-
- ///
- /// Tag for values input is done as "0x" and is placed ex. in front the value that needs to be converted
- ///
- public static readonly string ValueInputAsHexFrontTag = "0x";
-
-
- ///
- /// Tag for values input is done as "bin" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsBinaryEndTag = "bin";
-
- ///
- /// Tag for values input is done as "0b" and is placed ex. in front the value that needs to be converted
- ///
- public static readonly string ValueInputAsBinaryFrontTag = "0b";
-
- ///
- /// Convert byte values as in a string byte array
- ///
- /// must be like "0x12, 0x12, 0x12" or "1010bin; 1010bin; 1010bin" or "decimal 123, 123, 123"
- ///
- public static byte[] ValuesToBytes(this string byteValues)
- {
- try
- {
- List ret = new List();
- var isHexadecimal = false;
- var isDecimal = false;
- var isBinary = false;
- byteValues = byteValues.Trim().ToLower();
- bool isBinaryMatch = (new Regex(@"^[01 ]+$")).IsMatch(byteValues);
- bool isHexMatch = (new Regex(@"^[0-9a-f ]+$")).IsMatch(byteValues);
- if (!string.IsNullOrEmpty(byteValues) && (byteValues.Contains(ValueInputAsHexEndTag) || byteValues.Contains("0x") || (isHexMatch && !isBinaryMatch)))
- {
- byteValues = byteValues.ToLower().Replace(ValueInputAsHexEndTag, "");
- isHexadecimal = true;
- }
- else if (!string.IsNullOrEmpty(byteValues) && (byteValues.Contains(ValueInputAsDecimalTag) || isBinaryMatch))
- {
- byteValues = byteValues.Replace(ValueInputAsDecimalTag, "");
- isDecimal = true;
- }
- else if (!string.IsNullOrEmpty(byteValues) && byteValues.Contains(ValueInputAsBinaryTag))
- {
- byteValues = byteValues.Replace(ValueInputAsBinaryTag, "");
- isBinary = true;
- }
- var chunks = byteValues.Trim(new char[] { ' ' }).Split(new string[] { ",", ";", " ", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
- foreach (var value in chunks)
- {
- var toConvert = value.Trim();
- if (!string.IsNullOrEmpty(toConvert))
- {
- if (isHexadecimal || !isBinary && !isDecimal && (toConvert.StartsWith(ValueInputAsHexFrontTag) || toConvert.ToLower().Contains(ValueInputAsHexEndTag)))
- {
- ret.Add(Convert.ToByte(toConvert.Replace(ValueInputAsHexFrontTag, "").ToLower().Replace(ValueInputAsHexEndTag, ""), 16));
- }
- else if (isBinary || !isDecimal && (toConvert.StartsWith(ValueInputAsBinaryFrontTag) || toConvert.ToLower().Contains(ValueInputAsBinaryEndTag)))
- {
- ret.Add(Convert.ToByte(toConvert.Replace(ValueInputAsBinaryFrontTag, "").ToLower().Replace(ValueInputAsBinaryEndTag, ""), 2));
- }
- else
- {
- ret.Add(Convert.ToByte(toConvert, 10));
- }
- }
- }
- return ret.ToArray();
- }
- catch
- {
- return null; // Error
- }
- }
-
- public static string UnsignedHexToDecimal(this string Hex)
- {
- try
- {
- return Convert.ToUInt64(Hex, 16).ToString();
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToHex(this string iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return UnsignedDecimalToHex(Convert.ToUInt64(iDec), padLeft, Add_0x);
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToHex(this UInt32 iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return ((Add_0x) ? ValueInputAsHexFrontTag : "") + String.Format("{0:X}", iDec).PadLeft(padLeft, '0');
- }
- catch
- {
- return "?";
- }
- }
-
- public static string DecimalToHex(this Int32 iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return ((Add_0x) ? ValueInputAsHexFrontTag : "") + String.Format("{0:X}", iDec).PadLeft(padLeft, '0');
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToHex(this UInt64 iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return ((Add_0x) ? ValueInputAsHexFrontTag : "") + String.Format("{0:X}", iDec).PadLeft(padLeft, '0');
- }
- catch
- {
- return "?";
- }
- }
-
- public static string DecimalToHex(this Int64 iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return ((Add_0x) ? ValueInputAsHexFrontTag : "") + String.Format("{0:X}", iDec).PadLeft(padLeft, '0');
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToBin(this string dec, bool Add_0b)
- {
- try
- {
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + UnsignedDecimalToBase(Convert.ToUInt64(dec), 2);
- }
- catch
- {
- return "?";
- }
- }
-
- static string DoAutoPadLeft(this string valueAsStr)
- {
- var numberToPad = (valueAsStr.Length <= 8) ? 8 : (valueAsStr.Length <= 16) ? 16 : (valueAsStr.Length <= 32) ? 32 : 64;
- return valueAsStr.PadLeft(numberToPad, '0');
- }
-
- static string DoAutoSpcaePadEvery4Char(this string ValueAsStr)
- {
- if (String.IsNullOrEmpty(ValueAsStr))
- {
- return ValueAsStr;
- }
- else
- {
- ValueAsStr = ValueAsStr.Trim();
- var MissingChar = ValueAsStr.Length % 4;
- ValueAsStr = ValueAsStr.PadLeft(ValueAsStr.Length + 4 - MissingChar, '0');
- return Regex.Replace(ValueAsStr.Trim(), @"(.{4})", "$1 ").Trim();
- }
- }
-
- public static string ToUnsignedBin(this int value, bool Add_0b)
- {
- try
- {
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + UnsignedDecimalToBase((UInt32)value, 2).DoAutoPadLeft();
- }
- catch
- {
- return "?";
- }
- }
-
- public static string ToUnsignedBin(this uint value, bool Add_0b)
- {
- try
- {
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + UnsignedDecimalToBase(value, 2).DoAutoPadLeft();
- }
- catch
- {
- return "?";
- }
- }
-
- public static string ToUnsignedBin(this Int64 value)
- {
- try
- {
- return UnsignedDecimalToBase((UInt32)value, 2).DoAutoPadLeft();
- }
- catch
- {
- return "?";
- }
- }
-
- ///
- /// To string like 0bxxxxxxx depending of selection
- ///
- /// what value to show
- /// add 0b in front to indicate it is binary
- /// "true" if pad left front with all 0 for the actual value type else "false" only pad with up to 4 bits 0 to easy read
- ///
- public static string ToUnsignedBin(this UInt64 value, bool Add_0b, bool DoAutoPadLeft = true)
- {
- try
- {
- var ret = UnsignedDecimalToBase(value, 2);
- if (ret.Length == 0)
- {
- ret += "0"; // Always show 0 if no 1 is set
- }
- if (DoAutoPadLeft)
- {
- ret = ret.DoAutoPadLeft();
- }
- else
- {
- ret = ret.DoAutoSpcaePadEvery4Char();
- }
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + ret;
- }
- catch
- {
- return "?";
- }
- }
-
- public static string ToBin(this byte value, bool Add_0b)
- {
- try
- {
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + UnsignedDecimalToBase(value, 2).DoAutoPadLeft();
- }
- catch
- {
- return "?";
- }
- }
-
- public static string ToDec(this byte value)
- {
- return value.ToString("D3");
- }
-
- public static string ToHex(this byte value, bool Add_0x)
- {
- return DecimalToHex(value, 2, Add_0x);
- }
-
- public static string ToHex(this byte[] values, bool Add_0x, bool seperatorForCSV)
- {
- if (values == null) { return "Array is empty!"; }
- string ret = "";
- foreach (var value in values)
- {
- ret += (!String.IsNullOrEmpty(ret) ? (seperatorForCSV ? ColumnSeperatorCSV + " " : ", ") : "") + value.ToHex(Add_0x);
- }
- return ret;
- }
-
- public static string ToDec(this byte[] values)
- {
- if (values == null) { return "Array is empty!"; }
- string ret = "";
- foreach (var value in values)
- {
- ret += (!String.IsNullOrEmpty(ret) ? ", " : "") + value.ToDec();
- }
- return ret;
- }
-
- public static string ToBin(this byte[] values, bool Add_0b)
- {
- if (values == null) { return "Array is empty!"; }
- string ret = "";
- foreach (var value in values)
- {
- ret += (!String.IsNullOrEmpty(ret) ? ", " : "") + value.ToBin(Add_0b);
- }
- return ret;
- }
-
-
- public static string ToHex(this Int16 value, bool Add_0x)
- {
- return DecimalToHex(value, 4, Add_0x);
- }
-
- public static string ToHex(this UInt16 value, bool Add_0x)
- {
- return UnsignedDecimalToHex(value, 4, Add_0x);
- }
-
- public static string ToHex(this Int32 value, bool Add_0x)
- {
- return DecimalToHex(value, 8, Add_0x);
- }
-
- public static string ToHex(this UInt32 value, bool Add_0x)
- {
- return UnsignedDecimalToHex(value, 8, Add_0x);
- }
-
- public static string ToHex(this Int64 value, bool Add_0x)
- {
- return DecimalToHex(value, 16, Add_0x);
- }
-
- public static string ToHex(this UInt64 value, bool Add_0x)
- {
- return UnsignedDecimalToHex(value, 16, Add_0x);
- }
-
- public static string UnsignedDecimalToBase(this string iDec, int numbase)
- {
- try
- {
- return UnsignedDecimalToBase(Convert.ToUInt64(iDec), numbase);
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToBase(this UInt64 iDec, int numbase)
- {
- try
- {
- String strBin = "";
- int[] result = new int[64];
- int MaxBit = 64;
- for (; iDec > 0; iDec /= (UInt64)numbase)
- {
- int rem = (int)(iDec % Convert.ToUInt64(numbase));
- result[--MaxBit] = rem;
- }
- for (int i = 0; i < result.Length; i++)
- {
- if ((int)result.GetValue(i) >= base10)
- {
- strBin += cHexa[(int)result.GetValue(i) % base10];
- }
- else
- {
- strBin += result.GetValue(i);
- }
- }
- strBin = strBin.TrimStart(new char[] { '0' });
- return strBin;
- }
- catch
- {
- return "?";
- }
- }
-
- ///
- /// Converter string to a value (0x or 0b is not legal)
- ///
- ///
- ///
- ///
- public static UInt64 UnsignedBaseToDecimal(this String sBase, int numbase)
- {
- UInt64 result = 0;
- UInt64 b;
- UInt64 iProduct = 1;
- String sHexa = "";
- if (numbase > base10)
- {
- for (int i = 0; i < cHexa.Length; i++)
- {
- sHexa += cHexa.GetValue(i).ToString();
- }
- }
- for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= (UInt64)numbase)
- {
- String sValue = sBase[i].ToString();
- if (sValue.IndexOfAny(cHexa) >= 0)
- {
- b = (UInt64)iHexaNumeric[sHexa.IndexOf(sBase[i])];
- }
- else
- {
- b = (UInt64)sBase[i] - (UInt64)asciiDiff;
- }
- result += (b * iProduct);
- }
- return result;
- }
-
- ///
- /// Converter string to a value use 0x or 0b
- ///
- ///
- ///
- ///
- public static UInt64 ToUInt64(this String sBase)
- {
- UInt64 result = 0;
- UInt64 b;
- UInt64 iProduct = 1;
- String sHexa = "";
- int numbase;
- sBase = sBase.Trim().ToLower();
- if (sBase.StartsWith(ValueInputAsOctalFrontTag))
- {
- numbase = 8;
- sBase = sBase.Replace(ValueInputAsOctalFrontTag, "");
- }
- else if (sBase.StartsWith(ValueInputAsHexFrontTag))
- {
- numbase = 16;
- sBase = sBase.Replace(ValueInputAsHexFrontTag, "");
- }
- else if (sBase.StartsWith(ValueInputAsBinaryFrontTag))
- {
- numbase = 2;
- sBase = sBase.Replace(ValueInputAsBinaryFrontTag, "");
- }
- else
- {
- return Convert.ToUInt64(sBase);
- }
- if (numbase > base10)
- {
- for (int i = 0; i < cHexa.Length; i++)
- {
- sHexa += cHexa.GetValue(i).ToString();
- }
- }
- for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= (UInt64)numbase)
- {
- String sValue = sBase[i].ToString();
- if (sValue.IndexOfAny(cHexa) >= 0)
- {
- b = (UInt64)iHexaNumeric[sHexa.IndexOf(sBase[i])];
- }
- else
- {
- b = (UInt64)sBase[i] - (UInt64)asciiDiff;
- }
- result += (b * iProduct);
- }
- return result;
- }
-
- ///
- /// Converter string to a value use 0x or 0b
- ///
- ///
- ///
- ///
- public static Int64 ToInt64(this String sBase)
- {
- Int64 result = 0;
- Int64 b;
- Int64 iProduct = 1;
- String sHexa = "";
- int numbase;
- bool isNegative = false;
- sBase = sBase.Trim().ToLower();
- if (sBase.StartsWith("-"))
- {
- sBase = sBase.TrimStart('-');
- isNegative = true;
- }
- else if (sBase.StartsWith("+"))
- {
- sBase = sBase.TrimStart('+');
- }
- if (sBase.StartsWith(ValueInputAsOctalFrontTag))
- {
- numbase = 8;
- sBase = sBase.Replace(ValueInputAsOctalFrontTag, "");
- }
- else if (sBase.StartsWith(ValueInputAsHexFrontTag))
- {
- numbase = 16;
- sBase = sBase.Replace(ValueInputAsHexFrontTag, "");
- }
- else if (sBase.StartsWith(ValueInputAsBinaryFrontTag))
- {
- numbase = 2;
- sBase = sBase.Replace(ValueInputAsBinaryFrontTag, "");
- }
- else
- {
- return isNegative ? -Convert.ToInt64(sBase) : Convert.ToInt64(sBase);
- }
- if (numbase > base10)
- {
- for (int i = 0; i < cHexa.Length; i++)
- {
- sHexa += cHexa.GetValue(i).ToString();
- }
- }
- for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= (Int64)numbase)
- {
- String sValue = sBase[i].ToString();
- if (sValue.IndexOfAny(cHexa) >= 0)
- {
- b = (Int64)iHexaNumeric[sHexa.IndexOf(sBase[i])];
- }
- else
- {
- b = (Int64)sBase[i] - (Int64)asciiDiff;
- }
- result += (b * iProduct);
- }
- return isNegative ? -result : result;
- }
-
- public static UInt16 SwapByte(this UInt16 value)
- {
- return (UInt16)(value >> 8 | (value & 0xFF) << 8);
- }
-
- public static UInt64 SwapWord(this UInt64 value)
- {
- return (UInt64)(value >> 16 | (value & 0xFFFF) << 16);
- }
-
- }
-}
diff --git a/Common/modbus_master_csharp/Base/StringConvert.cs b/Common/modbus_master_csharp/Base/StringConvert.cs
deleted file mode 100644
index 27bc320f..00000000
--- a/Common/modbus_master_csharp/Base/StringConvert.cs
+++ /dev/null
@@ -1,474 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-
-namespace XYLEM.Base {
- #region ---- SMS Char Convert ----
-
- internal class UniCode {
- internal UInt32 Value { get; set; }
- internal char Ch {
- get { return (char)Value; }
- set { Value = (UInt32)value; }
- }
-
- internal string InfoTxt { get; set; }
- public UniCode(UInt32 value, string infoTxt) {
- Value = value;
- InfoTxt = infoTxt;
- }
-
- public override string ToString( ) {
- return String.Format( "\"{0}\"=0x{1x} ({2})", (char)Value, Value, InfoTxt );
- }
- }
-
- // Look at /DOC/Siemens MC55i GSM-charset.pdf
- // And http://www.unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT
- static class StringConvertToSMSClass {
- readonly static Dictionary ConvTable = new Dictionary( ){
- //{ new Byte[]{0x00}, new UniCode( 0x0040 , "COMMERCIAL AT") }, TMO NOT IN USE
- { new Byte[]{0x40}, new UniCode( 0x0040, "@ Converted to \"INVERTED EXCLAMATION MARK\", Device then TX \"0x00\"") },
- //{ new Byte[]{0x40}, new UniCode( 0x00A1 , "INVERTED EXCLAMATION MARK") }, TMO NOT IN USE
- { new Byte[]{0x21,0x2A}, new UniCode( 0x00A1 , "INVERTED EXCLAMATION MARK to \"!*\"") },
- { new Byte[]{0x00}, new UniCode( 0x0000 , "NULL (see note above)") },
- { new Byte[]{0x01}, new UniCode( 0x00A3 , "POUND SIGN") },
- { new Byte[]{0x02}, new UniCode( 0x0024 , "DOLLAR SIGN") },
- { new Byte[]{0x03}, new UniCode( 0x00A5 , "YEN SIGN") },
- { new Byte[]{0x04}, new UniCode( 0x00E8 , "LATIN SMALL LETTER E WITH GRAVE") },
- { new Byte[]{0x05}, new UniCode( 0x00E9 , "LATIN SMALL LETTER E WITH ACUTE") },
- { new Byte[]{0x06}, new UniCode( 0x00F9 , "LATIN SMALL LETTER U WITH GRAVE") },
- { new Byte[]{0x07}, new UniCode( 0x00EC , "LATIN SMALL LETTER I WITH GRAVE") },
- { new Byte[]{0x08}, new UniCode( 0x00F2 , "LATIN SMALL LETTER O WITH GRAVE") },
- { new Byte[]{0x09}, new UniCode( 0x00E7 , "LATIN SMALL LETTER C WITH CEDILLA") },
- { new Byte[]{0x09}, new UniCode( 0x00C7 , "LATIN CAPITAL LETTER C WITH CEDILLA (see note above)") },
- { new Byte[]{0x0A}, new UniCode( 0x000A , "LINE FEED") },
- { new Byte[]{0x0B}, new UniCode( 0x00D8 , "LATIN CAPITAL LETTER O WITH STROKE") },
- { new Byte[]{0x0C}, new UniCode( 0x00F8 , "LATIN SMALL LETTER O WITH STROKE") },
- { new Byte[]{0x0D}, new UniCode( 0x000D , "CARRIAGE RETURN") },
- { new Byte[]{0x0E}, new UniCode( 0x00C5 , "LATIN CAPITAL LETTER A WITH RING ABOVE") },
- { new Byte[]{0x0F}, new UniCode( 0x00E5 , "LATIN SMALL LETTER A WITH RING ABOVE") },
- { new Byte[]{0x10}, new UniCode( 0x0394 , "GREEK CAPITAL LETTER DELTA") },
- { new Byte[]{0x11}, new UniCode( 0x005F , "LOW LINE") },
- { new Byte[]{0x12}, new UniCode( 0x03A6 , "GREEK CAPITAL LETTER PHI") },
- { new Byte[]{0x13}, new UniCode( 0x0393 , "GREEK CAPITAL LETTER GAMMA") },
- { new Byte[]{0x14}, new UniCode( 0x039B , "GREEK CAPITAL LETTER LAMDA") },
- { new Byte[]{0x15}, new UniCode( 0x03A9 , "GREEK CAPITAL LETTER OMEGA") },
- { new Byte[]{0x16}, new UniCode( 0x03A0 , "GREEK CAPITAL LETTER PI") },
- { new Byte[]{0x17}, new UniCode( 0x03A8 , "GREEK CAPITAL LETTER PSI") },
- { new Byte[]{0x18}, new UniCode( 0x03A3 , "GREEK CAPITAL LETTER SIGMA") },
- { new Byte[]{0x19}, new UniCode( 0x0398 , "GREEK CAPITAL LETTER THETA") },
- { new Byte[]{0x1A}, new UniCode( 0x039E , "GREEK CAPITAL LETTER XI") },
- { new Byte[]{0x1B}, new UniCode( 0x00A0 , "ESCAPE TO EXTENSION TABLE (or displayed as NBSP, see note above)") },
- { new Byte[]{0x1B,0x0A}, new UniCode( 0x000C , "FORM FEED") },
- { new Byte[]{0x1B,0x14}, new UniCode( 0x005E , "CIRCUMFLEX ACCENT") },
- { new Byte[]{0x1B,0x28}, new UniCode( 0x007B , "LEFT CURLY BRACKET") },
- { new Byte[]{0x1B,0x29}, new UniCode( 0x007D , "RIGHT CURLY BRACKET") },
- { new Byte[]{0x1B,0x2F}, new UniCode( 0x005C , "REVERSE SOLIDUS") },
- { new Byte[]{0x1B,0x3C}, new UniCode( 0x005B , "LEFT SQUARE BRACKET") },
- { new Byte[]{0x1B,0x3D}, new UniCode( 0x007E , "TILDE") },
- { new Byte[]{0x1B,0x3E}, new UniCode( 0x005D , "RIGHT SQUARE BRACKET") },
- { new Byte[]{0x1B,0x40}, new UniCode( 0x007C , "VERTICAL LINE") },
- { new Byte[]{0x1B,0x65}, new UniCode( 0x20AC , "EURO SIGN") },
- { new Byte[]{0x1C}, new UniCode( 0x00C6 , "LATIN CAPITAL LETTER AE") },
- { new Byte[]{0x1D}, new UniCode( 0x00E6 , "LATIN SMALL LETTER AE") },
- { new Byte[]{0x1E}, new UniCode( 0x00DF , "LATIN SMALL LETTER SHARP S (German)") },
- { new Byte[]{0x1F}, new UniCode( 0x00C9 , "LATIN CAPITAL LETTER E WITH ACUTE") },
- { new Byte[]{0x20}, new UniCode( 0x0020 , "SPACE") },
- { new Byte[]{0x21}, new UniCode( 0x0021 , "EXCLAMATION MARK") },
- { new Byte[]{0x22}, new UniCode( 0x0022 , "QUOTATION MARK") },
- { new Byte[]{0x23}, new UniCode( 0x0023 , "NUMBER SIGN") },
- { new Byte[]{0x24}, new UniCode( 0x00A4 , "CURRENCY SIGN") },
- { new Byte[]{0x25}, new UniCode( 0x0025 , "PERCENT SIGN") },
- { new Byte[]{0x26}, new UniCode( 0x0026 , "AMPERSAND") },
- { new Byte[]{0x27}, new UniCode( 0x0027 , "APOSTROPHE") },
- { new Byte[]{0x28}, new UniCode( 0x0028 , "LEFT PARENTHESIS") },
- { new Byte[]{0x29}, new UniCode( 0x0029 , "RIGHT PARENTHESIS") },
- { new Byte[]{0x2A}, new UniCode( 0x002A , "ASTERISK") },
- { new Byte[]{0x2B}, new UniCode( 0x002B , "PLUS SIGN") },
- { new Byte[]{0x2C}, new UniCode( 0x002C , "COMMA") },
- { new Byte[]{0x2D}, new UniCode( 0x002D , "HYPHEN-MINUS") },
- { new Byte[]{0x2E}, new UniCode( 0x002E , "FULL STOP") },
- { new Byte[]{0x2F}, new UniCode( 0x002F , "SOLIDUS") },
- { new Byte[]{0x30}, new UniCode( 0x0030 , "DIGIT ZERO") },
- { new Byte[]{0x31}, new UniCode( 0x0031 , "DIGIT ONE") },
- { new Byte[]{0x32}, new UniCode( 0x0032 , "DIGIT TWO") },
- { new Byte[]{0x33}, new UniCode( 0x0033 , "DIGIT THREE") },
- { new Byte[]{0x34}, new UniCode( 0x0034 , "DIGIT FOUR") },
- { new Byte[]{0x35}, new UniCode( 0x0035 , "DIGIT FIVE") },
- { new Byte[]{0x36}, new UniCode( 0x0036 , "DIGIT SIX") },
- { new Byte[]{0x37}, new UniCode( 0x0037 , "DIGIT SEVEN") },
- { new Byte[]{0x38}, new UniCode( 0x0038 , "DIGIT EIGHT") },
- { new Byte[]{0x39}, new UniCode( 0x0039 , "DIGIT NINE") },
- { new Byte[]{0x3A}, new UniCode( 0x003A , "COLON") },
- { new Byte[]{0x3B}, new UniCode( 0x003B , "SEMICOLON") },
- { new Byte[]{0x3C}, new UniCode( 0x003C , "LESS-THAN SIGN") },
- { new Byte[]{0x3D}, new UniCode( 0x003D , "EQUALS SIGN") },
- { new Byte[]{0x3E}, new UniCode( 0x003E , "GREATER-THAN SIGN") },
- { new Byte[]{0x3F}, new UniCode( 0x003F , "QUESTION MARK") },
-
- { new Byte[]{0x41}, new UniCode( 0x0041 , "LATIN CAPITAL LETTER A") },
- { new Byte[]{0x41}, new UniCode( 0x0391 , "GREEK CAPITAL LETTER ALPHA") },
- { new Byte[]{0x42}, new UniCode( 0x0042 , "LATIN CAPITAL LETTER B") },
- { new Byte[]{0x42}, new UniCode( 0x0392 , "GREEK CAPITAL LETTER BETA") },
- { new Byte[]{0x43}, new UniCode( 0x0043 , "LATIN CAPITAL LETTER C") },
- { new Byte[]{0x44}, new UniCode( 0x0044 , "LATIN CAPITAL LETTER D") },
- { new Byte[]{0x45}, new UniCode( 0x0045 , "LATIN CAPITAL LETTER E") },
- { new Byte[]{0x45}, new UniCode( 0x0395 , "GREEK CAPITAL LETTER EPSILON") },
- { new Byte[]{0x46}, new UniCode( 0x0046 , "LATIN CAPITAL LETTER F") },
- { new Byte[]{0x47}, new UniCode( 0x0047 , "LATIN CAPITAL LETTER G") },
- { new Byte[]{0x48}, new UniCode( 0x0048 , "LATIN CAPITAL LETTER H") },
- { new Byte[]{0x48}, new UniCode( 0x0397 , "GREEK CAPITAL LETTER ETA") },
- { new Byte[]{0x49}, new UniCode( 0x0049 , "LATIN CAPITAL LETTER I") },
- { new Byte[]{0x49}, new UniCode( 0x0399 , "GREEK CAPITAL LETTER IOTA") },
- { new Byte[]{0x4A}, new UniCode( 0x004A , "LATIN CAPITAL LETTER J") },
- { new Byte[]{0x4B}, new UniCode( 0x004B , "LATIN CAPITAL LETTER K") },
- { new Byte[]{0x4B}, new UniCode( 0x039A , "GREEK CAPITAL LETTER KAPPA") },
- { new Byte[]{0x4C}, new UniCode( 0x004C , "LATIN CAPITAL LETTER L") },
- { new Byte[]{0x4D}, new UniCode( 0x004D , "LATIN CAPITAL LETTER M") },
- { new Byte[]{0x4D}, new UniCode( 0x039C , "GREEK CAPITAL LETTER MU") },
- { new Byte[]{0x4E}, new UniCode( 0x004E , "LATIN CAPITAL LETTER N") },
- { new Byte[]{0x4E}, new UniCode( 0x039D , "GREEK CAPITAL LETTER NU") },
- { new Byte[]{0x4F}, new UniCode( 0x004F , "LATIN CAPITAL LETTER O") },
- { new Byte[]{0x4F}, new UniCode( 0x039F , "GREEK CAPITAL LETTER OMICRON") },
- { new Byte[]{0x50}, new UniCode( 0x0050 , "LATIN CAPITAL LETTER P") },
- { new Byte[]{0x50}, new UniCode( 0x03A1 , "GREEK CAPITAL LETTER RHO") },
- { new Byte[]{0x51}, new UniCode( 0x0051 , "LATIN CAPITAL LETTER Q") },
- { new Byte[]{0x52}, new UniCode( 0x0052 , "LATIN CAPITAL LETTER R") },
- { new Byte[]{0x53}, new UniCode( 0x0053 , "LATIN CAPITAL LETTER S") },
- { new Byte[]{0x54}, new UniCode( 0x0054 , "LATIN CAPITAL LETTER T") },
- { new Byte[]{0x54}, new UniCode( 0x03A4 , "GREEK CAPITAL LETTER TAU") },
- { new Byte[]{0x55}, new UniCode( 0x0055 , "LATIN CAPITAL LETTER U") },
- { new Byte[]{0x56}, new UniCode( 0x0056 , "LATIN CAPITAL LETTER V") },
- { new Byte[]{0x57}, new UniCode( 0x0057 , "LATIN CAPITAL LETTER W") },
- { new Byte[]{0x58}, new UniCode( 0x0058 , "LATIN CAPITAL LETTER X") },
- { new Byte[]{0x58}, new UniCode( 0x03A7 , "GREEK CAPITAL LETTER CHI") },
- { new Byte[]{0x59}, new UniCode( 0x0059 , "LATIN CAPITAL LETTER Y") },
- { new Byte[]{0x59}, new UniCode( 0x03A5 , "GREEK CAPITAL LETTER UPSILON") },
- { new Byte[]{0x5A}, new UniCode( 0x005A , "LATIN CAPITAL LETTER Z") },
- { new Byte[]{0x5A}, new UniCode( 0x0396 , "GREEK CAPITAL LETTER ZETA") },
- { new Byte[]{0x5B}, new UniCode( 0x00C4 , "LATIN CAPITAL LETTER A WITH DIAERESIS") },
- { new Byte[]{0x5C}, new UniCode( 0x00D6 , "LATIN CAPITAL LETTER O WITH DIAERESIS") },
- { new Byte[]{0x5D}, new UniCode( 0x00D1 , "LATIN CAPITAL LETTER N WITH TILDE") },
- { new Byte[]{0x5E}, new UniCode( 0x00DC , "LATIN CAPITAL LETTER U WITH DIAERESIS") },
- { new Byte[]{0x5F}, new UniCode( 0x00A7 , "SECTION SIGN") },
- { new Byte[]{0x60}, new UniCode( 0x00BF , "INVERTED QUESTION MARK") },
- { new Byte[]{0x61}, new UniCode( 0x0061 , "LATIN SMALL LETTER A") },
- { new Byte[]{0x62}, new UniCode( 0x0062 , "LATIN SMALL LETTER B") },
- { new Byte[]{0x63}, new UniCode( 0x0063 , "LATIN SMALL LETTER C") },
- { new Byte[]{0x64}, new UniCode( 0x0064 , "LATIN SMALL LETTER D") },
- { new Byte[]{0x65}, new UniCode( 0x0065 , "LATIN SMALL LETTER E") },
- { new Byte[]{0x66}, new UniCode( 0x0066 , "LATIN SMALL LETTER F") },
- { new Byte[]{0x67}, new UniCode( 0x0067 , "LATIN SMALL LETTER G") },
- { new Byte[]{0x68}, new UniCode( 0x0068 , "LATIN SMALL LETTER H") },
- { new Byte[]{0x69}, new UniCode( 0x0069 , "LATIN SMALL LETTER I") },
- { new Byte[]{0x6A}, new UniCode( 0x006A , "LATIN SMALL LETTER J") },
- { new Byte[]{0x6B}, new UniCode( 0x006B , "LATIN SMALL LETTER K") },
- { new Byte[]{0x6C}, new UniCode( 0x006C , "LATIN SMALL LETTER L") },
- { new Byte[]{0x6D}, new UniCode( 0x006D , "LATIN SMALL LETTER M") },
- { new Byte[]{0x6E}, new UniCode( 0x006E , "LATIN SMALL LETTER N") },
- { new Byte[]{0x6F}, new UniCode( 0x006F , "LATIN SMALL LETTER O") },
- { new Byte[]{0x70}, new UniCode( 0x0070 , "LATIN SMALL LETTER P") },
- { new Byte[]{0x71}, new UniCode( 0x0071 , "LATIN SMALL LETTER Q") },
- { new Byte[]{0x72}, new UniCode( 0x0072 , "LATIN SMALL LETTER R") },
- { new Byte[]{0x73}, new UniCode( 0x0073 , "LATIN SMALL LETTER S") },
- { new Byte[]{0x74}, new UniCode( 0x0074 , "LATIN SMALL LETTER T") },
- { new Byte[]{0x75}, new UniCode( 0x0075 , "LATIN SMALL LETTER U") },
- { new Byte[]{0x76}, new UniCode( 0x0076 , "LATIN SMALL LETTER V") },
- { new Byte[]{0x77}, new UniCode( 0x0077 , "LATIN SMALL LETTER W") },
- { new Byte[]{0x78}, new UniCode( 0x0078 , "LATIN SMALL LETTER X") },
- { new Byte[]{0x79}, new UniCode( 0x0079 , "LATIN SMALL LETTER Y") },
- { new Byte[]{0x7A}, new UniCode( 0x007A , "LATIN SMALL LETTER Z") },
- { new Byte[]{0x7B}, new UniCode( 0x00E4 , "LATIN SMALL LETTER A WITH DIAERESIS") },
- { new Byte[]{0x7C}, new UniCode( 0x00F6 , "LATIN SMALL LETTER O WITH DIAERESIS") },
- { new Byte[]{0x7D}, new UniCode( 0x00F1 , "LATIN SMALL LETTER N WITH TILDE") },
- { new Byte[]{0x7E}, new UniCode( 0x00FC , "LATIN SMALL LETTER U WITH DIAERESIS") },
- { new Byte[]{0x7F}, new UniCode( 0x00E0 , "LATIN SMALL LETTER A WITH GRAVE") },
- };
-
- readonly static string[][] ConvertCh = new string[][]{
- new string[]{ "\r", ""},
- new string[]{ Environment.NewLine, "\n"},
- };
-
- internal static string RemoveIllegalATCh(this string value) {
- string ret = value;
- foreach (string[] replaceTxt in ConvertCh) {
- if (!String.IsNullOrEmpty( replaceTxt[ 0 ] )) {
- ret = ret.Replace( replaceTxt[ 0 ], "" );
- }
- }
- return ret;
- }
-
- internal static string ReplaceIllegalATCh(this string value) {
- string ret = value;
- foreach (string[] replaceTxt in ConvertCh) {
- if (!String.IsNullOrEmpty( replaceTxt[ 0 ] )) {
- ret = ret.Replace( replaceTxt[ 0 ], replaceTxt[ 1 ] );
- }
- }
- return ret;
- }
-
- internal static UniCode[] GetUniCodes(this byte[] data) {
- try {
- List list = new List( );
- for (int offset = 0; offset < data.Length; offset++) {
- bool found = false;
- // check if byte sequens is in convert table
- foreach (var code in ConvTable) {
- if (data[ offset ] == code.Key.First( )) {
- if (code.Key.Length == 1) {
- list.Add( code.Value );
- found = true;
- break;
- // Check if it is a combination of to bytes
- } else if ((code.Key.Length == 2) && (offset + 1 < data.Length) && (data[ offset + 1 ] == code.Key[ 1 ])) {
- offset++;
- list.Add( code.Value );
- found = true;
- break;
- }
- }
- }
- if (!found) {
- list.Add( new UniCode( data[ offset ], "(The Same)" ) );
- }
- }
- return list.ToArray( );
- } catch (Exception ex) {
- throw new Exception( "Unable to convert data to " + typeof( UniCode ).ToString( ), ex );
- }
- }
-
-
- internal static string ToPcChFromSmsTxt(this byte[] data) {
- string txt = "";
- try {
- for (int offset = 0; offset < data.Length; offset++) {
- bool found = false;
- // check if byte sequens is in convert table
- foreach (var code in ConvTable) {
- if (data[ offset ] == code.Key.First( )) {
- if (code.Key.Length == 1) {
- txt += code.Value.Ch;
- found = true;
- break;
- // Check if it is a combination of to bytes
- } else if ((code.Key.Length == 2) && (offset + 1 < data.Length) && (data[ offset + 1 ] == code.Key[ 1 ])) {
- offset++;
- txt += code.Value.Ch;
- found = true;
- break;
- }
- }
- }
- if (!found) {
- txt += (char)data[ offset ];
- }
- }
- return txt.Replace( "\n", Environment.NewLine );
- } catch (Exception ex) {
- throw new Exception( "Unable to convert char after this \"" + txt + "\"", ex );
- }
- }
-
- internal static byte[] ToByteFromPcChSMS(this String Txt) {
- List ret = new List( );
- try {
- foreach (var ch in Txt.ReplaceIllegalATCh( )) {
- bool found = false;
- // check if byte sequens is in convert table
- foreach (var code in ConvTable) {
- if (ch == code.Value.Ch) {
- ret.AddRange( code.Key );
- found = true;
- break;
- }
- }
- if (!found) {
- ret.AddRange( ASCIIEncoding.Default.GetBytes( ch.ToString( ) ) );
- }
- }
- return ret.ToArray( );
- } catch (Exception ex) {
- throw new Exception( "Unable to convert char after this \"" + (ret.Count > 0 ? ret.ToArray( ).ToPcChFromSmsTxt( ) : "None, Is Empty!!") + "\"", ex );
- }
- }
-
- internal static string ToStringFromPcChSMS(this String Txt) {
- string ret = "";
- try {
- foreach (var ch in Txt.ReplaceIllegalATCh( )) {
- bool found = false;
- // check if byte sequens is in convert table
- foreach (var code in ConvTable) {
- if (ch == code.Value.Ch) {
- foreach (var cdByte in code.Key) {
- ret += (char)cdByte;
- }
- found = true;
- break;
- }
- }
- if (!found) {
- foreach (var cdByte in ASCIIEncoding.Default.GetBytes( ch.ToString( ) )) {
- ret += (char)cdByte;
- }
- }
- }
- return ret;
- } catch (Exception ex) {
- throw new Exception( "Unable to convert char after this \"" + ret + "\"", ex );
- }
- }
-
-
- #region ---- To String ----
- private static string ToInfoTxt(byte[] data, UniCode unicode) {
- return string.Format( "SMS Ch = 0x{0x}{1} \t\t unicode Ch = {2}",
- data.First( ), // 0
- ((data.Length > 1) ? string.Format( "0x{0x}", data[ 0 ] ) : ""), //1
- unicode.ToString( ) ); // 2
- }
-
- public static string GetInfoTable( ) {
- string txt = "";
- foreach (var data in ConvTable) {
- txt += ToInfoTxt( data.Key, data.Value ) + Environment.NewLine;
- }
- return txt;
- }
- #endregion
- }
-
- #endregion
-
- internal static class StringConvert {
- ///
- /// Combine string array to a single text
- ///
- /// items that is null or empty will be removed
- /// inset string to join between to items (set to null if none)
- ///
- internal static string ToSingleString(this string[] array, string joinWithText) {
- string ret = "";
- if ((array != null) && (array.Length > 0)) {
- ret = array.Select( item => (String.IsNullOrEmpty( item ) ? "" : item) ).Aggregate( (current, next) => current + ((joinWithText != null) ? joinWithText : "") + next );
- }
- return ret;
- }
-
-
- ///
- /// Combine string array to a single text
- ///
- /// items that is null or empty will be removed
- /// new line or a single space is use to join between to item
- ///
- internal static string ToSingleString(this string[] array, bool addNewLine) {
- return ToSingleString( array, (addNewLine ? Environment.NewLine : " ") );
- }
-
-
- internal static string ToSingleString(this List list, bool addNewLine) {
- return ToSingleString( list.ToArray( ), addNewLine );
- }
-
- internal static string ToSingleString(this IEnumerable list, bool addNewLine) {
- return ToSingleString( list.ToArray( ), addNewLine );
- }
-
- internal static byte[] ToBytes(this string value) {
- return ASCIIEncoding.Default.GetBytes( value );
- }
-
- ///
- /// Convert PC string to at AT OK string (No new line)
- ///
- ///
- ///
- internal static byte[] ToBytesOkATCh(this string value) {
- return ASCIIEncoding.Default.GetBytes( value.RemoveIllegalATCh( ) );
- }
-
- internal static string ToPcCh(this byte[] value) {
- return ASCIIEncoding.Default.GetString( value );
- }
-
- ///
- /// Convert and remove all none printable char
- ///
- ///
- ///
- internal static string ToPcPrintableCh(this byte[] value) {
- return ToPcPrintableCh( value as IEnumerable );
- }
-
- ///
- /// Convert and remove all none printable char
- ///
- ///
- ///
- internal static string ToPcPrintableCh(this IEnumerable value) {
- string ret = "";
- if (value != null) {
- foreach (var b in value) {
- if (b >= 32) {
- ret += ASCIIEncoding.Default.GetString( new byte[] { b } );
- } else if (b == '\r') {
- ret += Environment.NewLine;
- }
- }
- }
- return ret;
- }
-
- internal static string ToPcChFromATCh(this byte[] value) {
- return ASCIIEncoding.Default.GetString( value ).Replace( "\r", "" ).Replace( "\n", Environment.NewLine );
- }
-
- ///
- /// Get all digit sequence in a string and return it as strings
- ///
- ///
- ///
- internal static string[] GetDecValues(this string values) {
- //http://regexhero.net/tester/
- //COM8.45 78.463 -676,67 6.454.54.45,4545,4545 (Selecting only the values)
- //
- MatchCollection matches = Regex.Matches( values, @"[-]|[.]|[-.]|[0-9][0-9]*[.]|[,]*[0-9]+" ); // ([0,1]|([0,1]?\.[0-9]+)) or "^[0-9]*[.]?[0-9]+$"
- if (matches.Count != 0) {
- List ret = new List( );
- foreach (Match value in matches) {
- ret.Add( value.Value );
- }
- return ret.ToArray( );
- }
- return null;
- }
-
- ///
- /// Get first digit sequence in a string and return it as strings
- ///
- ///
- ///
- internal static string GetDecValue(this string value) {
- string[] values = GetDecValues( value );
- if (values != null) {
- return values.First( );
- }
- return null;
- }
-
- internal static string RemoveZeroTerm(this string value) {
- if (!string.IsNullOrEmpty( value ) && value.Contains( '\0' )) {
- return value.Remove( value.IndexOf( '\0' ) );
- }
- return value;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Base/XML/XMLStringClass.cs b/Common/modbus_master_csharp/Base/XML/XMLStringClass.cs
deleted file mode 100644
index 69fb1e0a..00000000
--- a/Common/modbus_master_csharp/Base/XML/XMLStringClass.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base.XML
-{
- public static class XMLStringClass
- {
- public enum XMLVersion
- {
- V1_0,
- V1_1
- }
-
- ///
- /// Strips non-printable ascii characters
- /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
- ///
- ///
- ///
- public static string StripIllegalXMLChars(this string txtToClean)
- {
- return StripIllegalXMLChars(txtToClean, XMLVersion.V1_1);
- }
-
- ///
- /// Strips non-printable ascii characters
- /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
- /// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
- ///
- ///
- ///
- ///
- public static string StripIllegalXMLChars(this string txtToClean, XMLVersion version)
- {
- try
- {
- string pattern = String.Empty;
- txtToClean = txtToClean.
- Replace("&", "&").
- Replace("<", "<").
- Replace(">", ">").
- Replace("\"", """).
- Replace("'", "'").
- Replace("\r", "
").
- Replace("\n", "
");
- switch (version)
- {
- case XMLVersion.V1_0:
- pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])";
- break;
- case XMLVersion.V1_1:
- pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])";
- break;
- }
-
- Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
- if (regex.IsMatch(txtToClean))
- {
- txtToClean = regex.Replace(txtToClean, String.Empty);
- }
- if (txtToClean.Contains('\0'))
- {
- txtToClean = txtToClean.Remove(txtToClean.IndexOf('\0'));
- }
- if (txtToClean.Contains((char)0x1E))
- {
- txtToClean = txtToClean.Replace((char)0x1E, ' ');
- }
- {
- // Replace any character that has survived this done before
- // Replace illegal character in XML documents with blank
- // See here for reference http://www.w3.org/TR/xml/#charsets
- txtToClean = Regex.Replace(txtToClean, "[\x00-\x08\x0B\x0C\x0E-\x1F]", String.Empty, RegexOptions.Compiled);
- }
- return txtToClean;
- }
- catch (Exception ex)
- {
- throw new Exception("Error in XMLFileIOClass and StripIllegalXMLChars() " + (txtToClean != null ? " txtToClean = " + txtToClean.ToString() : "txtToClean is null"), ex);
- }
- }
-
- ///
- /// reinset non-printable ascii characters
- /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
- ///
- ///
- ///
- public static string ReinsetIllegalXMLChars(this string txtToClean)
- {
- return ReinsetIllegalXMLChars(txtToClean, XMLVersion.V1_1);
- }
-
- ///
- /// reinset non-printable ascii characters
- /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
- /// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
- ///
- ///
- ///
- ///
- public static string ReinsetIllegalXMLChars(string txtToReinset, XMLVersion version)
- {
- try
- {
- string pattern = String.Empty;
- txtToReinset = txtToReinset.
- Replace("&", "&").
- Replace("<", "<").
- Replace(">", ">").
- Replace(""", "\"").
- Replace("'", "'").
- Replace("
", "\r").
- Replace("
", "\n");
- return txtToReinset;
- }
- catch (Exception ex)
- {
- throw new Exception("Error in XMLFileIOClass and StripIllegalXMLChars() " + (txtToReinset != null ? " txtToClean = " + txtToReinset.ToString() : "txtToClean is null"), ex);
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Base/XML/XMLWriteFuncClass.cs b/Common/modbus_master_csharp/Base/XML/XMLWriteFuncClass.cs
deleted file mode 100644
index 4f7d60be..00000000
--- a/Common/modbus_master_csharp/Base/XML/XMLWriteFuncClass.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Xml.Serialization;
-using System.Xml;
-using System.Net.Sockets;
-using XYLEM.Base.Files;
-
-namespace XYLEM.Base.XML
-{
- internal class XMLWriteFuncClass
- {
- ///
- /// Writes the given object instance to an XML file.
- /// Only Public properties and variables will be written to the file. These can be any type though, even other classes.
- /// If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.
- /// Object type must have a parameterless constructor.
- ///
- /// The type of object being written to the file.
- /// The file path to write the object instance to.
- /// The object instance to write to the file.
- /// If false the file will be overwritten if it already exists. If true the contents will be appended to the file.
- public static void WriteToXmlFile(string filePath, T objectToWrite, bool append = false) where T : new()
- {
- // from https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
- TextWriter writer = null;
- try
- {
- writer = new StreamWriter(filePath, append);
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- xmlSerializer.Serialize(writer, objectToWrite);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(XMLWriteFuncClass).ToString(), ProgramLogCSVFileClass.GetCurrentStaticMethod()));
- }
- finally
- {
- if (writer != null)
- writer.Close();
- }
- }
-
- ///
- /// Reads an object instance from an XML file.
- /// Object type must have a parameterless constructor.
- ///
- /// The type of object to read from the file.
- /// The file path to read the object instance from.
- /// Returns a new instance of the object read from the XML file.
- public static T ReadFromXmlFile(string filePath) where T : new()
- {
- // from https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
-
- TextReader reader = null;
- try
- {
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- reader = new StreamReader(filePath);
- return (T)xmlSerializer.Deserialize(reader);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(XMLWriteFuncClass).ToString(), ProgramLogCSVFileClass.GetCurrentStaticMethod()));
- }
- finally
- {
- if (reader != null)
- reader.Close();
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/DeviceExceptionData.cs b/Common/modbus_master_csharp/Communication/DeviceExceptionData.cs
deleted file mode 100644
index e8895bc2..00000000
--- a/Common/modbus_master_csharp/Communication/DeviceExceptionData.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Communication
-{
- ///
- /// Class to contain data for a exception
- ///
- public struct DeviceExceptionData
- {
- ///
- /// Special function has to be done when this com
- /// https://mjksvn.world.fluidtechnology.net:4443/svn/development/- MJK Standards/- Communication protocols/Modbus/Modbus Specifications.doc
- /// "2.2.1 MODBUS Exception Responses:"
- ///
- public enum SpecialType
- {
- DriverError = -1,
- WaitForReset = 14, // Wait x sec befor next tx
- WaitForFinishMax5s = 252, // Wait Exception OK (max 5s)
- OnlyAnInforead = 253, // Used internal to only make an info read about data to read / write (Not intentet for normal TX)
- WaitForFinishMax60s = 254, // Wait Exception OK (max 60s)
- WaitForFinishMax5Min = 255, // Wait Exception OK (max 5min)
- }
-
- ///
- /// Exception No.
- ///
- private int _ExcNo;
-
- ///
- /// Exception Info
- ///
- private string _Info;
- ///
- /// Preload All data.. used when init data array
- ///
- ///
- ///
- public DeviceExceptionData(int excNo, string info)
- {
- this._ExcNo = excNo;
- this._Info = info;
- }
-
- ///
- /// Exception code number
- ///
- public int ExcNo
- {
- get { return _ExcNo; }
- set { _ExcNo = value; }
- }
-
- ///
- /// Info text to exception no.
- ///
- public String Info
- {
- get { return _Info; }
- set { _Info = value; }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/FuncTypes.cs b/Common/modbus_master_csharp/Communication/FuncTypes.cs
deleted file mode 100644
index 00e940f5..00000000
--- a/Common/modbus_master_csharp/Communication/FuncTypes.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Communication
-{
- public enum Func_RD : int
- {
- NoSupport = -1,
- No3 = 3,
- No4 = 4,
- };
-
- public enum Func_WR : int
- {
- NoSupport = -1,
- No15 = 15,
- No16 = 16,
- };
-}
diff --git a/Common/modbus_master_csharp/Communication/ModbusCom.cs b/Common/modbus_master_csharp/Communication/ModbusCom.cs
deleted file mode 100644
index e33716aa..00000000
--- a/Common/modbus_master_csharp/Communication/ModbusCom.cs
+++ /dev/null
@@ -1,634 +0,0 @@
-using MagFlux6200_metrology_reg_list;
-using XYLEM.Device;
-using XYLEM.Communication.ValueEncoders;
-using System;
-using System.Collections.Generic;
-using System.IO.Ports;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Numerics;
-using System.Xml.Linq;
-using static System.Net.Mime.MediaTypeNames;
-using XYLEM.Base;
-using System.Text.RegularExpressions;
-using System.Data;
-using System.Security.Policy;
-using System.Threading;
-
-namespace XYLEM.Communication
-{
- ///
- /// Modbus read and write return data type
- ///
- ///
- public class ModbusDataResult where T : IComparable, IFormattable, IComparable, IEquatable/*, IConvertible is not compatible with BigInteger*/
- {
- ///
- /// Has the task succeded
- ///
- internal bool IsOkay;
-
- ///
- /// Data readed from or written to device
- ///
- internal T Data;
-
- ///
- /// What device value info for Data
- ///
- internal Device_value Info;
-
- public ModbusDataResult(bool IsOkay, T DataRW, Device_value Info)
- {
- this.IsOkay = IsOkay;
- this.Data = DataRW;
- this.Info = Info;
- }
- }
-
- public class ModbusDataRequest
- {
- ///
- /// Has the task succeded
- ///
- internal bool IsOkay;
-
- ///
- /// Data for return read in from device
- ///
- internal object Data;
-
- ///
- /// What device value info for Data
- ///
- internal Device_value Info;
-
- public ModbusDataRequest(bool IsOkay, object returnReadIn, Device_value Info)
- {
- this.IsOkay = IsOkay;
- this.Data = returnReadIn;
- this.Info = Info;
- }
- }
-
-
- public class ModbusCom
- {
- const int ch_lng_dv = -15;
- const int ch_lng_Version = -3;
- const int ch_lng_MD_adr = -7;
- const int dig_value = 10;
-
- ///
- /// Min delay before a DUT message is expected faild
- // Is 1s for testing out that default modbus settings com don't fail
- ///
- private readonly int _MaxWaitForComRX_ms = 1000;
-
- ///
- /// Message ended detection delay
- /// Min delay before bytes count received and haven't changed result in modbus message ended
- /// The 50ms is found to be needed when using DUT RS485 and modbus messages is transparent to Metrology
- ///
- private readonly int _DelayBetweenRxByteCheck_ms = 50;
- SerialPort _serial;
- int _retry;
-
-
- public int MsgErrorCount { get; private set; }
- public int MsgCount { get; private set; }
-
- public void ResetMsgCounters()
- {
- MsgCount = MsgErrorCount = 0;
- }
-
- public ModbusCom(string serial_port, int baudRate, Parity parity, int retry = 3)
- {
- ResetMsgCounters();
- this._serial = new SerialPort();
- _serial.PortName = serial_port;
- _serial.BaudRate = baudRate;
- _serial.Parity= parity;
- _serial.DtrEnable = _serial.RtsEnable = true; // Need to be on for Application USB Serial com to detect a connection
- //_serial.Handshake = Handshake.RequestToSendXOnXOff;
- _serial.ReadTimeout = 100;
- if (!_serial.IsOpen)
- {
- _serial.Open();
- }
- _retry=retry;
- Console.WriteLine($"Serial connection {_serial.PortName}, {_serial.BaudRate}, {_serial.Parity}, retry = {_retry}");
- }
-
-
- ///
- /// Is communication port connected
- ///
- ///
- public bool IsConnected()
- {
- return _serial.IsOpen;
- }
-
- ///
- /// Generic value Read of a modbus value ex. "var ret = await Read(_serial, _device_id, req, new Single());"
- ///
- /// UInt16, Single ...
- /// device ID to use for read
- /// device value to read
- /// a new value of the type to read, to use for init and return
- /// as ModbusDataResult where Item1 is true if okay and Item2 is the value read
- public ModbusDataResult Read(int device_id, Device_value dv, T retValue) where T : IComparable, IFormattable, IComparable, IEquatable/*, IConvertible is not compatible with BigInteger*/
- {
- ModbusDataResult ret = null;
- try
- {
- byte[] answer = Read_bytes(device_id, dv.MD_adr, dv.Datatype.Length());
- retValue = (T)DeviceValueEncoder.Decode(answer, dv.Datatype);
- ret = new ModbusDataResult(true, retValue, dv); // Okay
- }
- catch (Exception ex)
- {
- var message = $"Read error! from ID={device_id} name={dv.Name} adr={dv.MD_adr} with {dv.Datatype.Length()}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Read()", message);
- ret = new ModbusDataResult(false, retValue, dv); // Error
- }
- return ret;
- }
-
- ///
- /// Read multiple value optimized in one or more telegrams from device
- ///
- /// Device ID to use for read
- /// A list of values to read
- /// List with read okay or failed values
- public List Read(int device_id, List dvList)
- {
- List ret = null;
- try
- {
- // ----------- Generate blocks to read -----------
- dvList.Sort((dvA, dvB) =>
- {
- return dvA.MD_adr.CompareTo(dvB.MD_adr);
- });
- List> blocks = new List>();
- foreach (var dv in dvList)
- {
- // if first item, just add it
- if ((blocks.Count == 0) || (blocks.Last().Count == 0))
- {
- if (blocks.Count == 0)
- {
- blocks.Add(new List());
- }
- blocks.Last().Add(new ModbusDataRequest(false, null, dv));
- }
- else
- {
- var dvLast = blocks.Last().Last().Info;
- // Only add it if a new value not already to be read
- if (dvLast.Name != dv.Name)
- {
- var nextAdr = dvLast.MD_adr + (dvLast.Datatype.Length()/2);
- // If not next to read in current block
- if (dv.MD_adr != nextAdr)
- {
- // then add it to the next read block
- blocks.Add(new List());
- }
- blocks.Last().Add(new ModbusDataRequest(false, null, dv));
- }
- }
- }
- // ----------- Read blocks -----------
- foreach (var dv_group in blocks)
- {
- try
- {
- var dvi_first = dv_group.First().Info;
- var dvi_last = dv_group.Last().Info;
- var startAdr = dvi_first.MD_adr;
- var LenBytes = (dvi_last.MD_adr+(dvi_last.Datatype.Length()/2)-startAdr)*2;
- if ((LenBytes < 0) || (LenBytes > 250))
- {
- throw new Exception($"Block length limit Error is {LenBytes}");
- }
- byte[] answer = Read_bytes(device_id, startAdr, LenBytes);
- if (answer == null)
- {
- throw new Exception($"Read block error! from ID={device_id} from {dvi_first} to {dvi_last}");
- }
- foreach (var dv_data in dv_group)
- {
- var dv = dv_data.Info;
- var start_idx = (dv.MD_adr-startAdr)*2;
- var value_bytes = answer.Copy(start_idx, dv.Datatype.Length());
- var value = DeviceValueEncoder.Decode(value_bytes, dv.Datatype);
- if (ret == null)
- {
- ret = new List();
- }
- ret.Add(new ModbusDataRequest(true, value, dv)); // Okay
- }
- }
- //catch (Exception ex)
- catch
- {
- // Retry read it as single values
- foreach (var dv_data in dv_group)
- {
- var dv = dv_data.Info;
- byte[] answer = Read_bytes(device_id, dv.MD_adr, dv.Datatype.Length());
- var value = DeviceValueEncoder.Decode(answer, dv.Datatype);
- if (ret == null)
- {
- ret = new List();
- }
- ret.Add(new ModbusDataRequest(true, value, dv)); // Okay
- }
- }
- }
- return ret;
- }
- catch (Exception ex)
- {
- if ((dvList != null) && (dvList.Count() > 0))
- {
- foreach (var dv in dvList)
- {
- var message = $"Read error! from ID={device_id} name={dv.Name} adr={dv.MD_adr}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Read()", message);
- }
- }
- else
- {
- var message = $"Read error! from ID={device_id}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Read()", message);
- }
- ret = null; // Error
- }
- return ret;
- }
-
-
- ///
- /// Generic value Write of a modbus value ex. "await Write(_serial, _device_id, req, value)"
- ///
- /// UInt16, Single ..
- /// device ID to use for write
- /// device value to write
- /// the value to write
- ///
- public bool Write(int device_id, Device_value dv, T value) where T : IComparable, IFormattable, IConvertible, IComparable, IEquatable
- {
- bool isOkay = true;
- try
- {
- byte[] tx_data = DeviceValueEncoder.Encode(value, dv.Datatype);
- if (!Write_bytes(device_id, dv.MD_adr, tx_data))
- {
- var message = $"Write failed={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={value,dig_value}";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write()", message);
- isOkay = false;
- }
- }
- catch (Exception ex)
- {
- var message = $"Write error! to ID={device_id} name={dv.Name} adr={dv.MD_adr} with {dv.Datatype.Length()}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write()", message);
- isOkay = false;
- }
- return isOkay;
- }
-
- ///
- /// Write multiple value optimized in one or more telegrams to device
- ///
- /// device ID to use for write
- /// a list of values to write
- /// A list of values written okay or failed to device
- public List Write(int device_id, List reqList)
- {
- List ret = null;
- try
- {
- // ----------- Generate blocks to write -----------
- reqList.Sort((dvA, dvB) =>
- {
- return dvA.Info.MD_adr.CompareTo(dvB.Info.MD_adr);
- });
- List> blocks = new List>();
- foreach (var req in reqList)
- {
- // if first item, just add it
- if ((blocks.Count == 0) || (blocks.Last().Count == 0))
- {
- if (blocks.Count == 0)
- {
- blocks.Add(new List());
- }
- blocks.Last().Add(req);
- }
- else
- {
- var req_Last = blocks.Last().Last();
- // Only add it if a new value not already written
- if (req_Last.Info.Name != req.Info.Name)
- {
- var nextAdr = req_Last.Info.MD_adr + (req_Last.Info.Datatype.Length()/2);
- // If not next to read in current block
- if (req.Info.MD_adr != nextAdr)
- {
- // then add it to the next read block
- blocks.Add(new List());
- }
- blocks.Last().Add(req);
- }
- else
- {
- throw new Exception($"Only a single Write object to {req_Last.Info.Name} is allowed!");
- }
- }
- }
- // ----------- Write blocks -----------
- foreach (var req_group in blocks)
- {
- try
- {
- var dvi_first = req_group.First().Info;
- var dvi_last = req_group.Last().Info;
- var startAdr = dvi_first.MD_adr;
- var LenBytes = (dvi_last.MD_adr+(dvi_last.Datatype.Length()/2)-startAdr)*2;
- if ((LenBytes < 0) || (LenBytes > 250))
- {
- throw new Exception($"Block length limit Error is {LenBytes}");
- }
- var tx_group_data = new List();
- foreach (var wr in req_group)
- {
- byte[] tx_data = DeviceValueEncoder.Encode(wr.Data, wr.Info.Datatype);
- if (tx_data == null)
- {
- throw new Exception($"Fail getting write byte data for {wr.Info.Name}");
- }
- tx_group_data.AddRange(tx_data);
- }
- if (LenBytes != tx_group_data.Count)
- {
- throw new Exception($"Group write from {dvi_first.Name} to {dvi_last.Name} expected={LenBytes} bytes, encoded was={tx_group_data.Count} bytes");
- }
- var isOkay = Write_bytes(device_id, startAdr, tx_group_data.ToArray());
- if (!isOkay)
- {
- throw new Exception($"Write block error! from ID={device_id} from {dvi_first} to {dvi_last}");
- }
- ret = new List();
- foreach (var req in req_group)
- {
- req.IsOkay = true;
- ret.Add(req); // add request that succeed
- }
- }
- //catch (Exception ex) //For debugging
- catch
- {
- ret = new List();
- // Retry write as single values
- foreach (var req in req_group)
- {
- var dv = req.Info;
- byte[] tx_data = DeviceValueEncoder.Encode(req.Data, req.Info.Datatype);
- req.IsOkay = Write_bytes(device_id, dv.MD_adr, tx_data);
- ret.Add(req); //
- }
- }
- }
- return ret;
- }
- catch (Exception ex)
- {
- if ((reqList != null) && (reqList.Count() > 0))
- {
- foreach (var dv in reqList)
- {
- var message = $"Write error! from ID={device_id} name={dv.Info.Name} adr={dv.Info.MD_adr}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write()", message);
- }
- }
- else
- {
- var message = $"Write error! from ID={device_id}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write()", message);
- }
- ret = null; // Error
- }
- return ret;
- }
-
- ///
- /// A general modbus read function for just a bunch of bytes
- ///
- /// device ID to use for modbus command
- /// Start address to data accessed
- /// Number of bytes to request
- /// byte data read from device and is null if none / error
- public byte[] Read_bytes(int device_id, int md_adr, int num_of_bytes)
- {
- var is_write = false;
- try
- {
- // Read address 0 device
- var p_transate = new ProtocolTranslateModbusRTUClass();
- byte[] tx_data = p_transate.CreateTxData(device_id, (int)Func_RD.No3, md_adr, num_of_bytes, null, is_write);
- return modbus_com(md_adr, tx_data, is_write, p_transate);
- }
- catch (Exception ex)
- {
- var message = $"!error No data received from ID={device_id} adr={md_adr} with {num_of_bytes} to {(is_write ? "Write" : "Read")}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Read_bytes()", message);
- return null;
- }
- }
-
- ///
- /// A general modbus write function for just a bunch of bytes
- ///
- /// device ID to use for modbus command
- /// Start address to data accessed
- /// Byte data to Write
- /// Is true on write is okay
- public bool Write_bytes(int device_id, int md_adr, byte[] write_data)
- {
- var is_write = true;
- try
- {
- // Read address 0 device
- var p_transate = new ProtocolTranslateModbusRTUClass();
- byte[] tx_data = p_transate.CreateTxData(device_id, (int)Func_WR.No16, md_adr, write_data.Length, write_data, is_write);
- var result = modbus_com(md_adr, tx_data, is_write, p_transate);
- if (result != null)
- {
- return true; // Okay
- }
- }
- catch (Exception ex)
- {
- var message = $"!error writting data to ID={device_id} adr={md_adr} to {(is_write ? "Write" : "Read")}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write_bytes()", message);
- }
- return false; // Error
- }
-
- ///
- /// A general modbus read / write function for just a bunch of bytes
- ///
- /// Start address to data accessed
- /// a complet modbus telegram byte data to transmit
- /// is the modbus telegram a write or read type to use for eval received result
- /// Modbus protocol translater for eval received result
- /// will return null on error or received message on okay
- public byte[] modbus_com(int md_adr, byte[] tx_data, bool is_write, ProtocolTranslateModbusRTUClass p_transate)
- {
- lock (_serial)
- {
- try
- {
- byte[] answer = null;
- var retry = 0;
- do
- {
- MsgCount++;
- if (!_serial.IsOpen)
- {
- _serial.Open();
- }
- _serial.DiscardInBuffer();
- _serial.Write(tx_data, 0, tx_data.Length);
-
- int received = 0;
- int max_count = _MaxWaitForComRX_ms/_DelayBetweenRxByteCheck_ms;
- do
- {
- received = _serial.BytesToRead;
- Thread.Sleep(_DelayBetweenRxByteCheck_ms);
- } while (((received == 0) || (received != _serial.BytesToRead)) && (--max_count>0));
- if (_serial.BytesToRead <= 0)
- {
- MsgErrorCount++;
- }
- } while ((_serial.BytesToRead <= 0) && (++retry < _retry));
- if (_serial.BytesToRead <= 0)
- {
- throw new Exception("!error No data received from device");
- }
-#if (DEBUG)
- // TODO just testing
- if (retry > 1)
- {
- Console.WriteLine($"Warning modbus com {retry-1} retry needed for ID={md_adr} to {(is_write ? "Write" : "Read")}");
- }
-#endif //#if (DEBUG)
- var bytesToRead = _serial.BytesToRead;
- var rx_data = new byte[bytesToRead];
- var rx_data_len = _serial.Read(rx_data, 0, bytesToRead);
- bool isRxRW = p_transate.IsDataRW(rx_data, true);
- // Check data func is Read or write
- if (isRxRW)
- {
- // Read
- if (!is_write)
- {
- if (p_transate.IsRead(rx_data, true))
- {
- answer = p_transate.GetReadData(rx_data, true);
- //buf.CallBackOK(bDataTemp, txData, CallBackOK_Single);
- }
- else
- {
- throw new Exception("Data Rx Wrong");
- }
- }
- else // Write
- {
- bool isWrite = p_transate.IsWrite(rx_data, true);
- int adr = p_transate.GetRxAdr(rx_data, true);
- if (isWrite && (!p_transate.IsAdrPossible(rx_data, true) ? true : (adr == md_adr)))
- {
- //buf.CallBackOK(null, txData, CallBackOK_Single);
- return rx_data; // Is okay return received message
- }
- else
- {
- throw new Exception("Data Rx Wrong");
- }
- }
-
- }
- else // Exception received
- {
- // Normal
- if (!p_transate.IsRxWaitForCommand(rx_data, true))
- {
- int exception = p_transate.GetRxAcknowledgeCode(rx_data, true);
- //buf.CallBackError(exception, txData, "");
- // If read .. try again after wait
- }
- else
- {
- if (!is_write)
- {
- //buf.Add(txData);
- // if Write.. then all must be okay and put event on delay
- }
- else
- {
- //buf.CallBackOK(null, txData, CallBackOK_Single);
- }
- if (p_transate.IsRxWaitForFinishMax60S(rx_data, true))
- {
- Thread.Sleep((int)(60 * 1000));
- }
- else if (p_transate.IsRxWaitForFinishMax5Min(rx_data, true))
- {
- Thread.Sleep((int)(5 * 60 * 1000));
- }
- else if (p_transate.IsRxWaitForFinishMax5S(rx_data, true))
- {
- Thread.Sleep((int)(5 * 1000));
- }
- else
- {
- int waitTime = 5 * 1000; // default
- Thread.Sleep(waitTime); // Wait for reset
- }
- }
- }
- return answer;
- }
- catch (Exception ex)
- {
- var message = "Error: \n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "modbus_com()", message);
- return null;
- }
- finally
- {
- _serial.Close();
- }
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/ProtocolTranslateModbusRTUClass.cs b/Common/modbus_master_csharp/Communication/ProtocolTranslateModbusRTUClass.cs
deleted file mode 100644
index 8f6f4ed2..00000000
--- a/Common/modbus_master_csharp/Communication/ProtocolTranslateModbusRTUClass.cs
+++ /dev/null
@@ -1,572 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net.Sockets;
-using XYLEM.Base;
-
-namespace XYLEM.Communication
-{
- public class ProtocolTranslateModbusRTUClass
- {
- public enum FunctionNumber : byte
- {
- NoSupport = 0,
- Read_No3 = 3,
- Read_No4 = 4,
- Write_No15 = 15,
- Write_No16 = 16,
-
- };
-
- ///
- /// Modbus Byte Offset for write data telegram
- ///
- private enum BaseOffset
- {
- ID = 0,
- FuncCode
- }
-
- ///
- /// Modbus Byte Offset for write data telegram
- ///
- private enum TxOffset_W
- {
- AdrHigh = (int)BaseOffset.FuncCode + 1,
- AdrLow,
- RegCount_High,
- RegCount_Low,
- ByteCount,
- Data_Start
- };
-
- ///
- /// Modbus Byte Offset for read data telegram
- ///
- private enum TxOffset_R
- {
- AdrHigh = (int)BaseOffset.FuncCode + 1,
- AdrLow,
- RegCount_High, RegCount_Low
- };
-
- ///
- /// Modbus Byte Offset for read data telegram
- ///
- private enum RxOffset_R
- {
- ByteCount = (int)BaseOffset.FuncCode + 1,
- Data_Start
- };
-
- ///
- /// Modbus Byte Offset for read data telegram
- ///
- private enum RxOffset_W
- {
- AdrHigh = (int)BaseOffset.FuncCode + 1,
- AdrLow,
- RegCount_High, RegCount_Low
- };
-
- ///
- /// Modbus Byte Offset for exception data telegram
- ///
- private enum TxRxOffset_Exc
- {
- ExceptionCode = (int)BaseOffset.FuncCode + 1
- };
-
- ///
- /// Calc CRC
- ///
- ///
- ///
- ///
- private UInt16 CalcCrc(Byte[] bByteData, int iDataCount)
- {
- int u8CountByte;
- byte u8Temp, u8CountBit;
- UInt16 u16RetCRCvalue;
- u16RetCRCvalue = 0xffff;
- for (u8CountByte = 0; u8CountByte < iDataCount; u8CountByte++)
- { // Udregn CRC værdien
- u16RetCRCvalue ^= bByteData[u8CountByte];
- for (u8CountBit = 0; u8CountBit < 8; u8CountBit++)
- {
- u8Temp = (Byte)(u16RetCRCvalue & 1);
- u16RetCRCvalue >>= 1;
- if (u8Temp == 1)
- {
- u16RetCRCvalue ^= 0xa001;
- }
- }
- }
- return u16RetCRCvalue;
- }
-
-
- #region IProtocolTranslateClass Members
- public int MaxDataReadBSize()
- {
- return 250; ////(252-1"Number of bytes to read")/2=125 MODBUS over _serial line specification and implementation guide V1.02 (Page 13) + Func 4/3
- }
-
- public int MaxDataWriteBSize()
- {
- return 230; //
- }
-
- public void StampReset() { }
-
- public byte StampNow
- {
- get { return 0; } // Off
- }
-
- ///
- /// Create a tx modbus message
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public byte[] CreateTxData(int slaveID, int rwFuncNo, int adr, int dataByteSize, Byte[] writeData, bool IsDeviceResponse)
- {
- try
- {
- Byte bTemp;
- Byte[] txData = null;
- int count = 0, iCRC;
- // Convert to modb us func number
- FunctionNumber funcNo;
- switch (rwFuncNo)
- {
- case (int)Func_RD.No3: funcNo = FunctionNumber.Read_No3; break;
- case (int)Func_RD.No4: funcNo = FunctionNumber.Read_No4; break;
- case (int)Func_WR.No15: funcNo = FunctionNumber.Write_No15; break;
- case (int)Func_WR.No16: funcNo = FunctionNumber.Write_No16; break;
- default: throw new Exception(LogMessageTool.ToFuncErrorText(this.ToString(), "CreateTxData()", "Incorrect func = " + rwFuncNo.ToString()));
- }
- #region ---- Read ----
- if ((funcNo == FunctionNumber.Read_No3) || (funcNo == FunctionNumber.Read_No4))
- {
- if (IsDeviceResponse)
- {
- if ((writeData == null) && (dataByteSize != writeData.Length))
- {
- var dataBLng = (writeData == null ? 0 : writeData.Length);
- throw new Exception("Data length is not the same expected " + dataByteSize + " but is " + dataBLng);
- }
- count = (int)RxOffset_R.Data_Start + dataByteSize;
- txData = new Byte[count + 2/*to crc*/ ];
- txData[(int)BaseOffset.ID] = (byte)slaveID;
- txData[(int)BaseOffset.FuncCode] = (byte)funcNo;
- txData[(int)RxOffset_R.ByteCount] = (byte)dataByteSize;
- // Copy and Swap High And Low byte in word
- for (int offset = 0; offset < dataByteSize; offset += 2)
- {
- bTemp = writeData[offset];
- txData[(int)RxOffset_R.Data_Start + offset] = writeData[offset + 1];
- txData[(int)RxOffset_R.Data_Start + offset + 1] = bTemp;
- }
- }
- else
- {
- dataByteSize = (dataByteSize == 1) ? 2 : dataByteSize;
- txData = new Byte[(int)TxOffset_R.RegCount_Low + 3];
- txData[(int)BaseOffset.ID] = (byte)slaveID;
- txData[(int)BaseOffset.FuncCode] = (byte)funcNo;
- txData[(int)TxOffset_R.AdrHigh] = (byte)(adr >> 8);
- txData[(int)TxOffset_R.AdrLow] = (byte)adr;
- txData[(int)TxOffset_R.RegCount_High] = (byte)0;
- txData[(int)TxOffset_R.RegCount_Low] = (byte)(dataByteSize >> 1);
- count = (int)TxOffset_R.RegCount_Low + 1;
- }
- }
- #endregion// Read
- #region ---- Write ----
- if ((funcNo == FunctionNumber.Write_No16) || (funcNo == FunctionNumber.Write_No15))
- {
- dataByteSize = writeData.Length;
- dataByteSize = (dataByteSize == 1) ? 2 : dataByteSize;
- txData = new Byte[(int)TxOffset_W.Data_Start + dataByteSize + 2];
- txData[(int)BaseOffset.ID] = (byte)slaveID;
- txData[(int)BaseOffset.FuncCode] = (byte)funcNo;
- txData[(int)TxOffset_W.AdrHigh] = (byte)(adr >> 8);
- txData[(int)TxOffset_W.AdrLow] = (byte)adr;
- txData[(int)TxOffset_W.RegCount_High] = (byte)0;
- txData[(int)TxOffset_W.RegCount_Low] = (byte)(dataByteSize >> 1);
- txData[(int)TxOffset_W.ByteCount] = (byte)dataByteSize;
- // Copy and Swap High And Low byte in word
- for (count = 0; count < dataByteSize; count += 2)
- {
- bTemp = writeData[count];
- txData[(int)TxOffset_W.Data_Start + count] = writeData[count + 1];
- txData[(int)TxOffset_W.Data_Start + count + 1] = bTemp;
- }
- count = dataByteSize + (int)TxOffset_W.Data_Start;
- }
- #endregion// Write
- iCRC = CalcCrc(txData, count);
- txData[count] = (byte)iCRC;
- txData[count + 1] = (byte)(iCRC >> 8);
- return txData; // OK
- }
- catch
- {
- return null; // Error
- }
- }
-
- public bool IsDataOkay(byte[] data, bool IsDeviceResponse)
- {
- int iCRC;
- int length = (data != null) ? data.Length : 0;
- iCRC = data[length - 1];
- iCRC = data[length - 2] + (iCRC << 8);
- return (CalcCrc(data, length - 2) == iCRC) || (CalcCrc(data, length - 2) == (((iCRC & 0xff) << 8) | (iCRC >> 8))); // Keller Fix
- }
-
- public bool IsRxDataOkay(byte[] data)
- {
- return IsDataOkay(data, true);
- }
-
-
- public bool IsDataRW(byte[] data, bool IsDeviceResponse)
- {
- return (data[(int)BaseOffset.FuncCode] < 0x80);
- }
-
- public bool IsRead(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)BaseOffset.FuncCode] == (int)FunctionNumber.Read_No3
- || data[(int)BaseOffset.FuncCode] == (int)FunctionNumber.Read_No4;
- }
-
- public byte[] GetReadData(byte[] data, bool IsDeviceResponse)
- {
- try
- {
- Byte[] retData = new Byte[(int)data[(int)RxOffset_R.ByteCount]];
- int offset = 0, length = 0, func = data[(int)BaseOffset.FuncCode];
- if ((func == (int)FunctionNumber.Read_No3) || (func == (int)FunctionNumber.Read_No4))
- {
- offset = (int)RxOffset_R.Data_Start;
- length = retData.Length;
- if (data.Count() < length)
- {
- throw new Exception($"Data lng ={data.Count()} is expecting min. {length}");
- }
- if (length == 0)
- {
- return null; // Error
- }
- for (int iTemp = 0; (iTemp < length); iTemp += 2)
- {
- retData[iTemp + 1] = data[offset + iTemp];
- retData[iTemp] = data[offset + iTemp + 1];
- }
- }
- else
- {
- return null; // Error
- }
- return retData;
- }
- catch (Exception ex)
- {
- var dataAsTxt = (data==null) ? "Data is null" : data.ToHex(true, false);
- var message = $"Error: data={dataAsTxt}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "GetReadData()", message);
- throw new Exception(message);
- }
- }
-
- public bool IsWrite(byte[] data, bool IsDeviceResponse)
- {
- return (data[(int)BaseOffset.FuncCode] == (int)FunctionNumber.Write_No16);
- }
-
- public bool IsAdrPossible(byte[] data, bool IsDeviceResponse)
- {
- return false;
- }
-
- public int GetRxAdr(byte[] data, bool IsDeviceResponse)
- {
- return ((int)data[(int)RxOffset_W.AdrHigh] << 8) | (int)data[(int)RxOffset_W.AdrLow];
- }
-
- public bool IsRxWaitForCommand(byte[] data, bool IsDeviceResponse)
- {
- return
- (data[(int)TxRxOffset_Exc.ExceptionCode] == (int)DeviceExceptionData.SpecialType.WaitForReset)
- || IsRxWaitForFinishMax5S(data, IsDeviceResponse)
- || IsRxWaitForFinishMax60S(data, IsDeviceResponse)
- || IsRxWaitForFinishMax5Min(data, IsDeviceResponse);
- }
-
- public bool IsRxWaitForFinishMax5S(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)TxRxOffset_Exc.ExceptionCode] == (int)DeviceExceptionData.SpecialType.WaitForFinishMax5s;
- }
-
- public bool IsRxWaitForFinishMax60S(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)TxRxOffset_Exc.ExceptionCode] == (int)DeviceExceptionData.SpecialType.WaitForFinishMax60s;
- }
-
- public bool IsRxWaitForFinishMax5Min(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)TxRxOffset_Exc.ExceptionCode] == (int)DeviceExceptionData.SpecialType.WaitForFinishMax5Min;
- }
-
- public bool IsAcknowledge(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)BaseOffset.FuncCode] >= 0x80;
- }
-
- public int GetRxAcknowledgeCode(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)TxRxOffset_Exc.ExceptionCode];
- }
-
- public ProtocolType Protocol
- {
- get { return ProtocolType.ModbusRTU; }
- }
-
- public int GetFuncNo(byte[] rx_data, bool IsDeviceResponse)
- {
- return (int)rx_data[(int)BaseOffset.FuncCode];
- }
-
- public int GetStartAdr(byte[] rx_data, bool IsDeviceResponse)
- {
- if (IsWrite(rx_data, IsDeviceResponse))
- {
- return GetRxAdr(rx_data, IsDeviceResponse);
- }
- else if (IsRead(rx_data, IsDeviceResponse))
- {
- return GetRxAdr(rx_data, IsDeviceResponse); // Is master read
- }
- throw new Exception("Unknown protocol type and location for start adr.");
- }
-
- public int GetNumberOfDataBytes(byte[] rx_data, bool IsDeviceResponse)
- {
- if (IsWrite(rx_data, IsDeviceResponse))
- {
- return rx_data[(int)RxOffset_W.RegCount_Low] * 2;
- }
- else if (IsRead(rx_data, IsDeviceResponse))
- {
- if (IsDeviceResponse)
- {
- return rx_data[(int)RxOffset_R.ByteCount];
- }
- else
- {
- return rx_data[(int)RxOffset_W.RegCount_Low] * 2;
- }
- }
- throw new Exception("Unknown protocol type and location for number of bytes");
- }
-
- public int GetComID(byte[] rx_data, bool IsDeviceResponse)
- {
- return rx_data[(int)BaseOffset.ID];
- }
-
- public byte[] GetWriteData(byte[] rx_data, bool IsDeviceResponse)
- {
- var bytesToWrite = GetNumberOfDataBytes(rx_data, IsDeviceResponse);
- try
- {
- var data = Base.ByteArrayExtensionClass.SwapByteInWord(rx_data.Copy((int)TxOffset_W.Data_Start, bytesToWrite));
- return data;
- }
- catch (Exception)
- {
- throw new Exception("Fail to copy write data! data byte size = " + bytesToWrite);
- }
- }
-
- public byte[] CreateTxData(int slaveID, int rwFuncNo, int adr, int writeResponse, bool IsDeviceResponse)
- {
- throw new NotImplementedException();
- }
-
- public string ToInfo(byte[] input, bool IsDeviceResponse)
- {
- string ret = "";
- try
- {
- bool isOkay = IsDataOkay(input, IsDeviceResponse);
- if (isOkay)
- {
- int id = GetComID(input, IsDeviceResponse);
- int func = GetFuncNo(input, IsDeviceResponse);
- ret += string.Format("Type {0}" + Environment.NewLine, IsDeviceResponse ? "Response" : "Request");
- ret += string.Format("ID {0}" + Environment.NewLine, id);
- bool isExeption = !IsDataRW(input, IsDeviceResponse);
- try
- {
- var func2Test = func;
- if (isExeption)
- {
- func2Test -= 0x80; // Get function from exeption code
- ret += "Exception ";
- }
- ret += string.Format("Func. {0} / {1} hex", func2Test, func2Test.ToString("x"));
- switch (func2Test)
- {
- case (int)FunctionNumber.Read_No3:
- case (int)FunctionNumber.Read_No4:
- ret += " is Read";
- break;
- case (int)FunctionNumber.Write_No15:
- case (int)FunctionNumber.Write_No16:
- if (IsDeviceResponse)
- {
- ret += " Incorrect write replay from slave!!!!";
- }
- else
- {
- ret += " is Write";
- }
- break;
- default: ret += " Unknown func. type!"; break;
- }
- }
- catch { ret += string.Format(" Unknown func. type!"); }
- ret += Environment.NewLine;
- if (isExeption)
- {
- var exeptioncode = (int)input[(int)BaseOffset.FuncCode + 1];
- ret += string.Format("Exception code {0} / {1} hex", exeptioncode, exeptioncode.ToString("x"));
- }
- else
- {
- ret += string.Format("Number of Bytes {0}" + Environment.NewLine, GetNumberOfDataBytes(input, IsDeviceResponse));
- if (IsDeviceResponse)
- {
- byte[] data = null;
- if (IsRead(input, IsDeviceResponse))
- {
- data = GetReadData(input, IsDeviceResponse);
- }
- if (data != null)
- {
- data = Base.ByteArrayExtensionClass.SwapByteInWord(data);
- ret += string.Format("Data is = {0}", Base.NumberConvert.ToHex(data, true, false));
- }
- }
- else
- {
- byte[] data = null;
- ret += string.Format("Start Address {0}" + Environment.NewLine, GetStartAdr(input, IsDeviceResponse));
- if (IsWrite(input, IsDeviceResponse))
- {
- data = GetWriteData(input, IsDeviceResponse);
- }
- if (data != null)
- {
- data = Base.ByteArrayExtensionClass.SwapByteInWord(data);
- ret += string.Format("Data is = {0}\n", Base.NumberConvert.ToHex(data, true, false));
- }
- }
- }
- //No44, // or 68 as a Special myconnect IO module telegram for https://mjksvn.world.fluidtechnology.net:4443/svn/development/8440XX Connect and myConnect/myConnect/trunk/docs/IO modules communication.docx
- }
- else if ((input != null) && (input.Length >= (16 + 2)))
- { // Check if it is
- var telegrams = input.SliceSameSize(0, (16 + 2));
- foreach (var telegram in telegrams)
- {
- if (IsDataOkay(telegram, IsDeviceResponse))
- {
- ret += "¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤" + Environment.NewLine;
- int offset = 0;
- ret += "ID[" + telegram[offset++] + "]";
- ret += " func[" + telegram[offset++] + "]";
- int Quantity = telegram[offset++];
- int[] Descriptors = new int[] { telegram[offset++], 0 };
- { // print out Status
- ret += Environment.NewLine;
- int Status = telegram[offset++];
- switch (Status)
- {
- case 0x11: ret += "Both recognized"; break;
- case 0x01: ret += "Lower OK, upper ERROR"; break;
- case 0x10: ret += "Lower ERROR, upper OK"; break;
- case 0x00: ret += "Both ERROR"; break;
- default: ret += "Unknown status" + Status.ToHex(true); break;
- }
- }
- {// Print out Descriptor
- ret += Environment.NewLine;
- Descriptors[1] = telegram[offset++];
- foreach (var Descriptor in Descriptors)
- {
- ret += " Type[";
- switch (Descriptor)
- {
- case 0: ret += "none"; break;
- case 1: ret += "6DI"; break;
- case 2: ret += "6DO"; break;
- case 3: ret += "3AI"; break;
- case 4: ret += "3AO"; break;
- default: ret += "Unknown" + Descriptor.ToHex(true); break;
- }
- ret += "]";
- }
- }
- {// Print out data
- ret += Environment.NewLine + "Raw[" + telegram.Slice(offset, telegram.Length - offset).ToHex(true, false) + "]";
-
- var u32Values = telegram.SliceSameSize(offset, 4);
- foreach (var u32Value in u32Values)
- {
- ret += Environment.NewLine;
- ret += " DI&DO[" + u32Value[0].ToBin(true) + "]/AI&AO[" + (new DataUnion()).PutByteArray(u32Value, DataUnion.DataByteLayoutType.SwapWords).F32Data + "]";
- }
- }
- }
- else
- {
- ret += string.Format("Message is {0} is wrong!" + Environment.NewLine, telegram.ToHex(true, false));
- }
- ret += Environment.NewLine;
- }
- }
- else
- {
- ret += string.Format("Message is {0}" + Environment.NewLine, isOkay ? "okay" : "CRC is wrong!");
- }
- }
- catch (Exception ex)
- {
- ret += "Error = " + ex.Message;
- }
- return ret;
- }
-
- ///
- /// Added to IProtocolTranslateClass to use in Comli
- ///
- public byte[] CreateTxData(int slaveID, int rwFuncNo, int adr, int dataByteSize, byte[] writeData, bool IsDeviceResponse, ref int pageNumberNow)
- {
- throw new NotImplementedException();
- }
-
- #endregion
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Communication/ProtocolType.cs b/Common/modbus_master_csharp/Communication/ProtocolType.cs
deleted file mode 100644
index 9917f686..00000000
--- a/Common/modbus_master_csharp/Communication/ProtocolType.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System;
-
-namespace XYLEM.Communication
-{
- //------------------------------------- Define ------------------------------------------------
- public enum ProtocolType : int
- {
- ModbusRTU = 0,
- None,
- };
-}
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/ArrayManipulator.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/ArrayManipulator.cs
deleted file mode 100644
index 437b8573..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/ArrayManipulator.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace XYLEM.Communication.ValueEncoders
-{
- static class ArrayManipulator
- {
- public static byte[] SwapPairWise(byte[] input)
- {
- byte[] swapped = new byte[input.Length];
- for (int i = 0; i < input.Length; i = i+2)
- {
- swapped[i + 1] = input[i];
- swapped[i] = input[i + 1];
- }
-
- return swapped;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/DeviceValueEncoder.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/DeviceValueEncoder.cs
deleted file mode 100644
index b485232c..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/DeviceValueEncoder.cs
+++ /dev/null
@@ -1,952 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using XYLEM.Communication;
-using System.Xml;
-using System.Xml.Linq;
-using XYLEM.Base;
-using XYLEM.Base.Files;
-using XYLEM.Device.Value;
-using System.Numerics;
-using XYLEM.Communication.ValueEncoders;
-using XYLEM.Base.XML;
-
-namespace XYLEM.Communication.ValueEncoders
-{
- ///
- /// Return used character set used for email or empty if not Loaded from setup
- ///
- /// ex. "iso-8859-1"
- public delegate string GetEmailCharacterSetToUse();
-
- public static class DeviceValueEncoder
- {
- public static object Default(this ValueDataType dataType)
- {
- try
- {
- switch (dataType)
- {
- case ValueDataType.U8:
- case ValueDataType.B8: return (byte)0;
- case ValueDataType.S8: return (sbyte)0;
-
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return (UInt16)0;
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC: return ((UInt32)0).Convert1970SecToTime(TimeType.UTC);
- case ValueDataType.U32TIME_Y2000: return ((UInt32)0).Convert2000SecToTime();
- case ValueDataType.U32MJK_SN: return ((UInt32)0);
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: return ((UInt32)0);
- //case DeviceValueDataType.U24:
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- case ValueDataType.B32:
- case ValueDataType.U32: return (UInt32)0;
- case ValueDataType.B64:
- case ValueDataType.U64: return (UInt64)0;
- case ValueDataType.F64: return (double)0;
- case ValueDataType.U128: return (BigInteger)0;
- case ValueDataType.S16: return (Int16)0;
- case ValueDataType.F32: return (Single)0;
- //case DeviceValueDataType.U32IPV4: return "0.0.0.0"; // handled as a string
- default:
- if (dataType.IsText())
- { // Do this as the last check to save CPU power
- return "";
- }
- throw new Exception(dataType.ToString() + "has no default value)");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Default()", "dataType = " + dataType.ToString()));
- }
- }
-
- public static string EncodeXML(this object value, ValueDataType type)
- {
- try
- {
- string valueAsTxt = value.ToString();
- switch (type)
- {
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- if (value is DateTime)
- {
- var value32bit = ((DateTime)value).ConvertTimeTo1970Sec(TimeType.Local);
- return XmlConvert.ToString(value32bit);
- }
- return XmlConvert.ToString((Double)value);
- case ValueDataType.U32TIME_Y2000:
- if (value is DateTime)
- {
- var value32bit = ((DateTime)value).ConvertTimeTo2000Sec(TimeType.Local);
- return XmlConvert.ToString(value32bit);
- }
- return XmlConvert.ToString((Double)value);
- case ValueDataType.U8:
- case ValueDataType.B8:
- case ValueDataType.S8:
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS:
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U24:
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.B64:
- case ValueDataType.U64:
- case ValueDataType.S16:
- case ValueDataType.S32:
- case ValueDataType.S64:
- case ValueDataType.F32:
- case ValueDataType.F64:
- case ValueDataType.U32MJK_SN:
- {
- if (typeof(Double) == value.GetType())
- {
- valueAsTxt = XmlConvert.ToString((Double)value);
- }
- else if (typeof(Single) == value.GetType())
- {
- valueAsTxt = XmlConvert.ToString((Single)value);
- }
- return valueAsTxt;
- }
- case ValueDataType.U128:
- if (typeof(BigInteger) == value.GetType())
- {
- valueAsTxt = ((BigInteger)value).ToString("X"); // enclode as hex
- }
- else
- {
- throw new Exception($"{value.GetType()} is not supported for U128 xml convert");
- }
- return valueAsTxt;
-
- //case DeviceValueDataType.U32IPV4: return valueAsTxt.Trim( ).StripIllegalXMLChars( );// handled as a string
- default:
- if (type.IsText())
- { // Do this as the last check to save CPU power
- return valueAsTxt.Trim().StripIllegalXMLChars();
- }
- throw new NotImplementedException("DataType '" + type + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "EncodeXML()", "dataType = " + type.ToString() + " Value is = " + value.ToString()));
- }
- }
-
- public static Object DecodeXML(this string valueInXml, ValueDataType type)
- {
- try
- {
- switch (type)
- {
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- return XmlConvert.ToUInt32(valueInXml).Convert1970SecToTime(TimeType.Local);
- case ValueDataType.U32TIME_Y2000:
- return XmlConvert.ToUInt32(valueInXml).Convert2000SecToTime();
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC: return XmlConvert.ToUInt32( valueInXml );
- case ValueDataType.B8:
- case ValueDataType.U8:
- return XmlConvert.ToByte(valueInXml);
- case ValueDataType.S8:
- return XmlConvert.ToSByte(valueInXml);
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return XmlConvert.ToUInt16(valueInXml);
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS:
- //case DeviceValueDataType.U24:
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- return XmlConvert.ToUInt32(valueInXml);
- case ValueDataType.B64:
- case ValueDataType.U64: return XmlConvert.ToUInt64(valueInXml);
- case ValueDataType.S16: return XmlConvert.ToInt16(valueInXml);
- case ValueDataType.S32: return XmlConvert.ToInt32(valueInXml);
- case ValueDataType.S64: return XmlConvert.ToInt64(valueInXml);
- case ValueDataType.F32: return XmlConvert.ToSingle(valueInXml);
- case ValueDataType.F64: return XmlConvert.ToDouble(valueInXml);
- case ValueDataType.U128: return BigInteger.Parse(valueInXml, System.Globalization.NumberStyles.HexNumber);
- //case DeviceValueDataType.U32IPV4: return valueInXml.ReinsetIllegalXMLChars( );// handled as a string
- default:
- if (type.IsText())
- { // Do this as the last check to save CPU power
- return valueInXml.ReinsetIllegalXMLChars();
- }
- throw new NotImplementedException("DataType '" + type + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "DecodeXML()", "dataType = " + type.ToString() + " Value is = " + valueInXml));
- }
- }
-
- ///
- /// do layout changes on byte stream
- ///
- ///
- ///
- ///
- static byte[] DoLayout(this byte[] bytes, LayoutType layout = LayoutType.Normal)
- {
- try
- {
- switch (layout)
- {
- case LayoutType.Normal: return bytes; ; // Do nothing
- case LayoutType.SwapAll: return bytes.Reverse();
- default:
- throw new NotSupportedException(layout + " is not supported");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "DoLayout", "layout = " + layout));
- }
- }
-
-
- ///
- /// Encode data with normal data layout
- ///
- ///
- ///
- /// Null if not used
- ///
- public static byte[] Encode(this object value, ValueDataType dataType, GetEmailCharacterSetToUse emailCharacterSet = null)
- {
- try
- {
- if (value == null)
- {
- throw new Exception("Value is null");
- }
- switch (dataType)
- {
- case ValueDataType.B8:
- case ValueDataType.U8:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(byte));// Try set type if not the correct one
- return BitConverter.GetBytes((byte)value);
- }
- case ValueDataType.S8:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(sbyte));// Try set type if not the correct one
- return BitConverter.GetBytes((sbyte)value);
- }
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return BitConverter.GetBytes((UInt16)value);
- case ValueDataType.U32TIME_Y1970:
- if (value is DateTime)
- {
- return BitConverter.GetBytes(((DateTime)value).ConvertTimeTo1970Sec(TimeType.Local));
- }
- return BitConverter.GetBytes((UInt32)value); // Work around on olde types
- case ValueDataType.U32TIME_Y1970_UTC:
- if (value is DateTime)
- {
- return BitConverter.GetBytes(((DateTime)value).ConvertTimeTo1970Sec(TimeType.UTC));
- }
- return BitConverter.GetBytes((UInt32)value); // Work around on olde types
- case ValueDataType.U32TIME_Y2000:
- if (value is DateTime)
- {
- return BitConverter.GetBytes(((DateTime)value).ConvertTimeTo2000Sec(TimeType.Local));
- }
- return BitConverter.GetBytes((UInt32)value);
- // Work around on olde types
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- // return BitConverter.GetBytes( TimeConvertClass.ToMidnightSecOffsetUTC( (UInt32)value ) );
- //case DeviceValueDataType.U24DateHH_MM_SS: {
- // var timeSpan = TimeConvertClass.ConvertTimeSpan( (UInt32)value );
- // return new byte[] { (byte)timeSpan.Seconds, (byte)timeSpan.Minutes, (byte)timeSpan.Hours };
- // }
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: {
- // var date = ((UInt32)value).Convert1970SecToTime( TimeType.Local );
- // return new byte[] {
- // (byte)date.Second,
- // (byte)date.Minute,
- // (byte)date.Hour,
- // (byte)date.Day,
- // (byte)date.Month,
- // (byte)(date.Year - 2000)
- // };
- // }
- //case DeviceValueDataType.U24: {
- // value = CorrectTypeIfNotTheSame( value, dataType, typeof( UInt32 ) );// Try set type if not the correct one
- // return BitConverter.GetBytes( (UInt32)value ).Remove( 3 );
- // }
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(UInt32));// Try set type if not the correct one
- return BitConverter.GetBytes((UInt32)value);
- }
- case ValueDataType.B64:
- case ValueDataType.U64:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(UInt64));// Try set type if not the correct one
- return BitConverter.GetBytes((UInt64)value);
- }
- case ValueDataType.S16:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(Int16));// Try set type if not the correct one
- return BitConverter.GetBytes((Int16)value);
- }
- case ValueDataType.S32:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(Int32));// Try set type if not the correct one
- return BitConverter.GetBytes((Int32)value);
- }
- case ValueDataType.F32:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(Single));// Try set type if not the correct one
- return BitConverter.GetBytes((Single)value);
- }
- case ValueDataType.F64:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(double));// Try set type if not the correct one
- return BitConverter.GetBytes((double)value);
- }
- case ValueDataType.U128:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(BigInteger));// Try set type if not the correct one
- return ((BigInteger)value).ToByteArray(); // TODO: Is this okay or need always to be the 16 byte in size?
- }
- //case DeviceValueDataType.U32IPV4: return U32_IP_Encoder.Encode( value.ToString( ) );
- default:
- if (dataType.IsText())
- { // Do this as the last check to save CPU power
- var typeAsText = dataType.ToString();
- // is Email
- if (dataType.IsEmailText())
- {
- return StringEncoderEmail.Encode(value.ToString(), Length(dataType), ((emailCharacterSet == null) ? "" : emailCharacterSet()));
- }
- // is SMS
- if (dataType.IsSMSText())
- {
- return StringEncoderUnicode.Encode(value.ToString(), Length(dataType));
- }
- // is Windows 1252
- if (dataType.IsWindows1252Text())
- {
- return StringEncoder_W1252.Encode(value.ToString(), Length(dataType));
- }
- // is Windows 1252, but needs to have "<>" in frond and end
- // Ex. end result is "," or ""
- if (dataType.IsWindows1252TextRecipient())
- {
- var valueAsText = value.ToString().Trim();
- if (!String.IsNullOrEmpty(valueAsText))
- {
- // Remove manual added brackets or " if user has done it in the past
- if (valueAsText.Contains("\""))
- {
- valueAsText = valueAsText.Replace("\"", "");
- }
- //// work arround if user has already used "," as separation
- //if (valueAsText.Contains( "," )) {
- // valueAsText = valueAsText.Replace( ",", ">,<" ); //old modem firmware V1.003 and TDC NO
- //}
- // Replace ";" with correct "," as separation and add bracked ">" "<" to support RCF821
- if (valueAsText.Contains(";"))
- {
- //valueAsText = valueAsText.Replace( ";", ">,<" ); old modem firmware V1.003 and TDC NO
- valueAsText = valueAsText.Replace(";", ",");//new modem firmware V1.3 using mail.mjk-link.dk
- }
- // Trim
- valueAsText = valueAsText.Trim();
- // Add brackets "<>" around address / addresses and end with " to tell modem where it starts and end in MC55I at command
- //Ex. end result is "," or ""
- if (!String.IsNullOrEmpty(valueAsText))
- {
- //valueAsText = "\"<" + valueAsText + "\">"; old modem firmware V1.003 and TDC NO
- valueAsText = "\"" + valueAsText + "\""; //new modem firmware V1.3 using mail.mjk-link.dk
- }
- }
- return StringEncoder_W1252.Encode(valueAsText, Length(dataType));
- }
- // is Quoted Printable Text
- if (dataType.IsEmailQuotedPrintableText())
- {
- return StringEncoderEmail_Q_Types.Encode(value.ToString(), Length(dataType), ((emailCharacterSet == null) ? "" : emailCharacterSet()));
- }
- // Is is normal utf8
- return StringEncoder.Encode(value.ToString(), Length(dataType));
- }
- throw new NotImplementedException("DataType '" + dataType + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Encode", "dataType = " + dataType.ToString()));
- }
- }
-
- private static object CorrectTypeIfNotTheSame(object value, ValueDataType correctTypeTag, Type typeUsedForCast)
- {
- try
- {
- if (value.GetType() == typeUsedForCast)
- {
- return value; // Nothing to change
- }
- {
- AppConst.Logger.AddFuncLog(
-#if DEBUG //
- true // log as error
-#else
- false // Log silent in log
-#endif //#if DEBUG
- , typeof(DeviceValueEncoder).ToString(), "CorrectTypeIfNotTheSame()",
- "Warning! correction was needed. Is this a older setting else not okay? " + MakeCorrectTypeValueInfoText(value, correctTypeTag, typeUsedForCast)
- );
- }
- return ToValue(value.ToString(), correctTypeTag);
- }
- catch (Exception ex)
- {
- var valueInfo = MakeCorrectTypeValueInfoText(value, correctTypeTag, typeUsedForCast);
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "CorrectTypeIfNotTheSame", valueInfo));
- }
- }
-
- ///
- /// Generate the value info possible to get for a value to convert
- ///
- /// Value to correct
- /// correct value type tag
- /// type used for cast
- /// Text to show in log
- private static string MakeCorrectTypeValueInfoText(object value, ValueDataType correctTypeTag, Type typeUsedForCast)
- {
- var ValueInfo = "";
- try
- {
- if (ValueInfo == null)
- {
- ValueInfo += " Value= IS NULL and not possible to correct!";
- }
- else
- {
- ValueInfo += " Value=\"" + value.ToString() + "\"";
- ValueInfo += " From Type=\"" + value.GetType() + "\"";
- }
- ValueInfo += " To Type=\"" + correctTypeTag.ToString() + "\"";
- }
- catch { ValueInfo += " [Fail to get info ?] "; }
- return ValueInfo;
- }
-
- ///
- /// Encode data with data layout setting
- ///
- ///
- ///
- ///
- /// Null if not used
- ///
- public static byte[] Encode(this object value, ValueDataType dataType, LayoutType layout, GetEmailCharacterSetToUse emailCharacterSet = null)
- {
- try
- {
- var bytes = Encode(value, dataType, emailCharacterSet);
- if (bytes == null)
- {
- return bytes;
- }
- return bytes.DoLayout(layout);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Encode", "dataType = " + dataType.ToString()));
- }
- }
-
-
- ///
- /// Decode data with normal data layout
- ///
- ///
- ///
- /// Null if not used
- ///
- public static object Decode(this byte[] value, ValueDataType dataType, GetEmailCharacterSetToUse emailCharacterSet = null)
- {
- try
- {
- if (value == null)
- {
- throw new Exception("Value is null");
- }
- if (value.Count() == 0)
- {
- throw new Exception("Value Has no values in array");
- }
- switch (dataType)
- {
- case ValueDataType.B8:
- case ValueDataType.U8:
- return (byte)value.First();
- case ValueDataType.S8:
- return (sbyte)value.First();
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return BitConverter.ToUInt16(value, 0);
- case ValueDataType.U32TIME_Y1970:
- return BitConverter.ToUInt32(value, 0).Convert1970SecToTime(TimeType.Local);
- case ValueDataType.U32TIME_Y1970_UTC:
- return BitConverter.ToUInt32(value, 0).Convert1970SecToTime(TimeType.UTC).ToLocalTime();
- case ValueDataType.U32TIME_Y2000:
- return BitConverter.ToUInt32(value, 0).Convert2000SecToTime();
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- // return TimeConvertClass.FromMidnightSecOffsetUTC( BitConverter.ToUInt32( value, 0 ) );
- //case DeviceValueDataType.U24DateHH_MM_SS: {
- // return (UInt32)((UInt32)value[ 2 ] * 3600) + ((UInt32)value[ 1 ] * 60 + (UInt32)value[ 0 ]);
- // }
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: {
- // var date = new DateTime( (int)value[ 5 ] + 2000, value[ 4 ], value[ 3 ], value[ 2 ], value[ 1 ], value[ 0 ] );
- // return date.ConvertTimeTo1970Sec( TimeType.Local );
- // }
- //case DeviceValueDataType.U24: {
- // var as32bitValue = new byte[] { value[ 0 ], value[ 1 ], value[ 2 ], 0 };
- // return BitConverter.ToUInt32( as32bitValue, 0 );
- // }
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- return BitConverter.ToUInt32(value, 0);
- case ValueDataType.B64:
- case ValueDataType.U64: return BitConverter.ToUInt64(value, 0);
- case ValueDataType.S16: return BitConverter.ToInt16(value, 0);
- case ValueDataType.S32: return BitConverter.ToInt32(value, 0);
- case ValueDataType.F32: return BitConverter.ToSingle(value, 0);
- case ValueDataType.F64: return BitConverter.ToDouble(value, 0);
- case ValueDataType.U128:
- {
- // Need a zero in msb to avoid value is handled as signed
- var valueConverted = new BigInteger((value).Concat(new byte[1]).ToArray());
- return valueConverted;
- }
-
- case ValueDataType.Array6B:
- case ValueDataType.Array10B:
- case ValueDataType.Array12B:
- case ValueDataType.Array64B:
- case ValueDataType.Array128B:
- case ValueDataType.Array136B:
- case ValueDataType.Array250B: return value;
- //case DeviceValueDataType.U32IPV4: return U32_IP_Encoder.Decode( value );
- default:
- if (dataType.IsText())
- { // Do this as the last check to save CPU power
- var typeAsText = dataType.ToString();
- if (dataType.IsEmailText())
- { // is Email
- return StringEncoderEmail.Decode(value, Length(dataType), ((emailCharacterSet == null) ? "" : emailCharacterSet()));
- }
- if (dataType.IsSMSText())
- { // is SMS
- return StringEncoderUnicode.Decode(value, Length(dataType));
- }
- if (dataType.IsWindows1252Text())
- { // is Windows 1252
- return StringEncoder_W1252.Decode(value, Length(dataType));
- }
- if (dataType.IsWindows1252TextRecipient())
- { // is Windows 1252, but needs to have "<>" in frond and end
- var valueAsText = StringEncoder_W1252.Decode(value, Length(dataType));
- if (!String.IsNullOrEmpty(valueAsText))
- {
- // Remove added brackets or " nessesarry that is only to be
- // Ex. end result is "," or ""
- if (valueAsText.Contains("\""))
- {
- valueAsText = valueAsText.Replace("\"", "");
- }
- if (valueAsText.Contains("<"))
- {
- valueAsText = valueAsText.Replace("<", "");
- }
- if (valueAsText.Contains(">"))
- {
- valueAsText = valueAsText.Replace(">", "");
- }
- // Replace email seperation and replace it with correct the standard ";"
- if (valueAsText.Contains(","))
- {
- valueAsText = valueAsText.Replace(",", ";");
- }
- }
- return valueAsText;
- }
- if (dataType.IsEmailQuotedPrintableText())
- {
- return StringEncoderEmail_Q_Types.Decode(value, Length(dataType), ((emailCharacterSet == null) ? "" : emailCharacterSet()));
- }
- // Is allowed to have a variable length on a string / text
- var maxLng = dataType.Length();
- if (value.Length > maxLng)
- {
- throw new Exception(String.Format("Size of text is {0} and more than max {1}", value.Length, maxLng));
- }
- // Is is normal utf8
- return StringEncoder.Decode(value, value.Length);
- }
- throw new NotImplementedException("DataType '" + dataType + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Decode", "dataType = " + dataType.ToString()));
- }
- }
-
- ///
- /// Decode data with data layout setting
- ///
- ///
- ///
- /// Null if not used
- ///
- ///
- public static object Decode(this byte[] value, ValueDataType dataType, LayoutType layout, GetEmailCharacterSetToUse emailCharacterSet = null)
- {
- try
- {
- var bytes = value.DoLayout(layout);
- return Decode(value, dataType, emailCharacterSet);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Encode", "dataType = " + dataType.ToString()));
- }
- }
-
- ///
- /// Convert a local defined string value to the correct value object according to dataType ("DeviceValueType")
- ///
- /// Value as string (floating point must use local setting for "," or ".") and DateTime as local time
- ///
- ///
- public static object ToValue(this string value, ValueDataType dataType)
- {
- try
- {
- if (value == null)
- {
- throw new Exception("Value is null");
- }
- switch (dataType)
- {
- case ValueDataType.B8:
- case ValueDataType.U8:
- return (byte)Convert.ToUInt16(value);
- case ValueDataType.S8:
- return (sbyte)Convert.ToInt16(value);
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return Convert.ToUInt16(value);
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- case ValueDataType.U32TIME_Y2000:
- // Always expect this as local time
- return new DateTime(Convert.ToDateTime(value).Ticks, DateTimeKind.Local);
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U24:
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- return Convert.ToUInt32(value);
- case ValueDataType.B64:
- case ValueDataType.U64: return Convert.ToUInt64(value);
- case ValueDataType.S16: return Convert.ToInt16(value);
- case ValueDataType.S32: return Convert.ToInt32(value);
- case ValueDataType.F32: return Convert.ToSingle(value);
- case ValueDataType.F64: return Convert.ToDouble(value);
- case ValueDataType.U128:
- // Need a zero in msb to avoid value is handled as signed
- return BigInteger.Parse("0"+value, System.Globalization.NumberStyles.HexNumber);
- //case DeviceValueDataType.U32IPV4: {
- // if (dataType.IsText( )) {
- // return value.ToString( );
- // }
- // throw new NotImplementedException( "DataType '" + dataType + "' not recognized." );
- // }
- default:
- if (dataType.IsText())
- { // Do this as the last check to save CPU power
- var typeAsText = dataType.ToString();
- if (dataType.IsEmailText())
- { // is Email
- return value;
- }
- if (dataType.IsSMSText())
- { // is SMS
- return value;
- }
- if (dataType.IsWindows1252Text())
- { // is Windows 1252
- return value;
- }
- if (dataType.IsWindows1252TextRecipient())
- { // is Windows 1252, but needs to have "<>" in frond and end
- return value;
- }
- if (dataType.IsEmailQuotedPrintableText())
- { // is Special Email Quoted Printable
- return value;
- }
- // Is is normal utf8
- return value; //TODO: No converting is done. may have to be converted to utf8?
- }
- throw new NotImplementedException("DataType '" + dataType + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "ToValue()", "dataType = " + dataType.ToString()));
- }
- }
-
- ///
- /// Return data Byte Length (1x8bit)
- ///
- ///
- public static int Length(this ValueDataType DataType)
- {
- try
- {
- switch (DataType)
- {
- case ValueDataType._Empty: return 0;
- #region ---- 8 Bit ----
- case ValueDataType.Bool:
- case ValueDataType.B8:
- case ValueDataType.S8:
- case ValueDataType.U8: return 1;
- #endregion // #region ---- 8 Bit ----
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U24: return 3;
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: return 6;
- default:
- return WLength(DataType) << 1;
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Length"));
- }
- }
-
- ///
- /// Return data Word Length (2x8bit)
- ///
- ///
- public static int WLength(this ValueDataType DataType)
- {
- try
- {
- switch (DataType)
- {
- case ValueDataType._Empty: return 0;
- #region ---- 8 / 16 Bit ----
- case ValueDataType.Bool:
- case ValueDataType.B8:
- case ValueDataType.S8:
- case ValueDataType.U8:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- case ValueDataType.B16:
- case ValueDataType.S16:
- case ValueDataType.U16TEXTID:
- case ValueDataType.U16UNIT:
- case ValueDataType.U16UNITGROUP: return 1;
- #endregion
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: return 3;
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U24: return 2;
- #region ---- 32 Bit ----
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- case ValueDataType.S32:
- case ValueDataType.F32:
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- case ValueDataType.U32TIME_Y2000:
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- //case DeviceValueDataType.U32IPV4:
- return 2;
- #endregion
- #region ---- 12 x 8 Bit Time Types ----
- case ValueDataType.TIME_ASCII_12B:
- case ValueDataType.TIME_ymdhms:
- return 6;
- #endregion
- #region ---- 64 Bit ----
- case ValueDataType.B64:
- case ValueDataType.U64:
- case ValueDataType.S64:
- case ValueDataType.F64:
- return 4;
- #endregion
- #region ---- 128 Bit ----
- case ValueDataType.U128:
- return 8;
- #endregion
- #region ---- Bit Arrays ----
- case ValueDataType.Array6B: return (6 / 2);
- case ValueDataType.Array10B: return (10 / 2);
- case ValueDataType.Array12B: return (12 / 2);
- case ValueDataType.Array64B: return (64 / 2);
- case ValueDataType.Array128B: return (128 / 2);
- case ValueDataType.Array136B: return (136 / 2);
- case ValueDataType.Array250B: return (250 / 2);
- #endregion
- #region ---- Strings / Text ----
- //6bytes
- case ValueDataType.STR6E:
- case ValueDataType.STR6S:
- //case DeviceValueDataType.STR6Q:
- //case DeviceValueDataType.STR6W1252:
- case ValueDataType.STR6: return 3;
- //8bytes
- case ValueDataType.STR8E:
- case ValueDataType.STR8S:
- //case DeviceValueDataType.STR8Q:
- //case DeviceValueDataType.STR8W1252:
- case ValueDataType.STR8: return 4;
- //10bytes
- case ValueDataType.STR10E:
- case ValueDataType.STR10S:
- //case DeviceValueDataType.STR10Q:
- //case DeviceValueDataType.STR10W1252:
- case ValueDataType.STR10: return 5;
- //16bytes
- case ValueDataType.STR16E:
- case ValueDataType.STR16S:
- //case DeviceValueDataType.STR16Q:
- //case DeviceValueDataType.STR16W1252:
- case ValueDataType.STR16: return 8;
- //18bytes
- case ValueDataType.STR18E:
- case ValueDataType.STR18S:
- //case DeviceValueDataType.STR18Q:
- //case DeviceValueDataType.STR18W1252:
- case ValueDataType.STR18: return 9;
- //20bytes
- case ValueDataType.STR20E:
- case ValueDataType.STR20S:
- //case DeviceValueDataType.STR20Q:
- //case DeviceValueDataType.STR20W1252:
- case ValueDataType.STR20: return 10;
- //22bytes
- case ValueDataType.STR22E:
- case ValueDataType.STR22S:
- //case DeviceValueDataType.STR22Q:
- //case DeviceValueDataType.STR22W1252:
- case ValueDataType.STR22: return 11;
- //30bytes
- case ValueDataType.STR30E:
- case ValueDataType.STR30S:
- //case DeviceValueDataType.STR30Q:
- //case DeviceValueDataType.STR30W1252:
- case ValueDataType.STR30: return 15;
- //32bytes
- case ValueDataType.STR32E:
- case ValueDataType.STR32S:
- //case DeviceValueDataType.STR32Q:
- //case DeviceValueDataType.STR32W1252:
- case ValueDataType.STR32: return 16;
- //64bytes
- case ValueDataType.STR64E:
- case ValueDataType.STR64S:
- //case DeviceValueDataType.STR64Q:
- //case DeviceValueDataType.STR64W1252:
- case ValueDataType.STR64: return 32;
- //100bytes
- case ValueDataType.STR100E:
- case ValueDataType.STR100S:
- //case DeviceValueDataType.STR100Q:
- //case DeviceValueDataType.STR100W1252:
- case ValueDataType.STR100: return 50;
- //128bytes
- case ValueDataType.STR128E:
- case ValueDataType.STR128S:
- //case DeviceValueDataType.STR128Q:
- //case DeviceValueDataType.STR128W1252:
- //case DeviceValueDataType.STR128W1252rec:
- case ValueDataType.STR128: return 64;
- //160bytes
- //case DeviceValueDataType.STR160E:
- //case DeviceValueDataType.STR160S:
- //case DeviceValueDataType.STR160Q:
- //case DeviceValueDataType.STR160W1252:
- //case DeviceValueDataType.STR160: return 80;
- //240bytes
- case ValueDataType.STR240E:
- case ValueDataType.STR240S:
- //case DeviceValueDataType.STR240Q:
- //case DeviceValueDataType.STR240W1252:
- case ValueDataType.STR240: return 240;
- #endregion
- default:
- throw (new Exception("No known length for tag = " + DataType.ToString()));
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "WLength"));
- }
- }
-
- ///
- /// Return the text length for value type if it is a text
- ///
- ///
- public static int StringLength(this ValueDataType DataType)
- {
- try
- {
- switch (DataType)
- {
- //case DeviceValueDataType.U32IPV4: return (4 * 3 + 3);
- default:
- if (DataType.IsSMSText())
- { // is SMS
- return DataType.Length() / 2; // is always 16bit
- }
- return Length(DataType);
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "StringLength"));
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/LayoutType.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/LayoutType.cs
deleted file mode 100644
index e1cad01c..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/LayoutType.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Communication.ValueEncoders {
- public enum LayoutType {
- Normal,
- SwapAll,
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoder.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoder.cs
deleted file mode 100644
index b9654183..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoder.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-using System;
-using System.Text;
-using XYLEM.Communication;
-
-namespace XYLEM.Communication.ValueEncoders {
- public static class StringEncoder {
- public static Encoding GetDefaultEncoding( ) {
- try {
- return Encoding.GetEncoding( "Windows-1252"/*Strings._CONFIG_STD_String_DefaultCharacterEncoding*/ );
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rGetDefaultEncoding"+ "\n\rError when making default encoding with = "+ "\n\rWindows-1252"/*Strings._CONFIG_STD_String_DefaultCharacterEncoding*/, ex );
- }
- //Legacy code return Encoding.GetEncoding( 1252 );
- }
-
- ///
- /// Standard Windows iso-8859-1-encoding page.
- ///
- static Encoding s_Encoder = GetDefaultEncoding( ); // Default Fallback
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static byte[] Encode(string value, int lenght, string CharacterSet) {
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length is too long", "value" );
- }
- var result = new byte[ lenght ];
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- Encoding.GetEncoding( CharacterSet ).GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rEncode"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ + Environment.NewLine + ex.Message );
- }
- // Use defalt
- s_Encoder.GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static byte[] Encode(string value, int lenght) { return Encode( value, lenght, null ); }
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static string Decode(byte[] value, int lenght, string CharacterSet) {
- if (value.Length != lenght) {
- throw new ArgumentException( "value.Length wrong lenght", "value" );
- }
- string result = null;
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- result = Encoding.GetEncoding( CharacterSet ).GetString( value );
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rDecode()"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ + Environment.NewLine + ex.Message );
- }
- // Use defalt
- if (result == null) {
- result = s_Encoder.GetString( value );
- }
- var index = result.IndexOf( '\0' );
- if (index >= 0)
- return result.Substring( 0, result.IndexOf( '\0' ) );
- else
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static string Decode(byte[] value, int lenght) { return Decode( value, lenght, null ); }
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail.cs
deleted file mode 100644
index 3d0850ce..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace XYLEM.Communication.ValueEncoders {
- public static class StringEncoderEmail {
- public static Encoding GetDefaultEncoding( ) {
- try {
- return Encoding.GetEncoding( "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ );
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString( )+ "\n\rGetDefaultEncoding"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- // Legacy code return Encoding.GetEncoding( "iso-8859-1" );
- }
-
-
- ///
- /// Standard Windows iso-8859-1-encoding page.
- ///
- static Encoding s_Encoder = GetDefaultEncoding( ); // Default Fallback
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static byte[] Encode(string value, int lenght, string CharacterSet) {
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length is too long", "value" );
- }
- var result = new byte[ lenght ];
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- Encoding.GetEncoding( CharacterSet ).GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString( )+ "\n\rEncode()"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/,ex );
- }
- // Use defalt
- s_Encoder.GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static byte[] Encode(string value, int lenght) { return Encode( value, lenght, null ); }
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static string Decode(byte[] value, int lenght, string CharacterSet) {
- if (value.Length != lenght) {
- throw new ArgumentException( "value.Length wrong lenght", "value" );
- }
- string result = null;
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- result = Encoding.GetEncoding( CharacterSet ).GetString( value );
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString()+ "\n\rDecode()"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- // Use defalt
- if (result == null) {
- result = s_Encoder.GetString( value );
- }
- var index = result.IndexOf( '\0' );
- if (index >= 0) {
-
- return result.Substring( 0, result.IndexOf( '\0' ) );
- }
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static string Decode(byte[] value, int lenght) { return Decode( value, lenght, null ); }
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail_Q_Types.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail_Q_Types.cs
deleted file mode 100644
index 37dcb471..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail_Q_Types.cs
+++ /dev/null
@@ -1,175 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Globalization;
-
-namespace XYLEM.Communication.ValueEncoders {
- public static class StringEncoderEmail_Q_Types {
- static string DefaultEncoding = "iso-8859-1";
-
- public static Encoding GetDefaultEncoding( ) {
- try {
- return Encoding.GetEncoding( "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ );
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString( ) + "\n\rGetDefaultEncoding" + "\n\rError when making default encoding with = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- // Legacy code return Encoding.GetEncoding( DefaultEncoding );
- }
-
- #region Converting to Quoted Printable
- //http://stackoverflow.com/questions/11793734/code-for-encode-decode-quotedprintable
-
- public static byte[] EncodeQ(byte[] value, int lenght) {
- if (value.First( ) == 0) {
- return value;
- }
- List ret = new List( );
- foreach (byte v in value) {
- // The following are not required to be encoded:
- // - Tab (ASCII 9)
- // - Space (ASCII 32)
- // - Characters 33 to 126, except for the equal sign (61).
- if ((v == 9) || ((v >= 32) && (v <= 60)) || ((v >= 62) && (v <= 126))) {
- if (ret.Count + 1 > lenght) { // Check for length is not over max
- break; // Stop converting
- }
- ret.Add( (byte)Convert.ToChar( v ) );
- } else {
- if (ret.Count + 3 > lenght) { // Check for length is not over max
- break; // Stop converting
- }
- if (v == 0) {
- ret.Add( 0 );
- break; // Stop terminate string
- }
- ret.AddRange( Encoding.UTF8.GetBytes( "=" + v.ToString( "X2" ) ) );
- }
- }
- char lastChar = (char)ret.Last( );
- if (char.IsWhiteSpace( lastChar )) {
- ret.RemoveAt( ret.Count( ) - 1 );
- if (!(ret.Count + 3 > lenght)) { // Check for length is not over max
- ret.AddRange( Encoding.UTF8.GetBytes( "=" + ((byte)lastChar).ToString( "X2" ) ) );
- }
- }
- if (ret.Count < lenght) { // Make sure length is correct
- ret.AddRange( new byte[ lenght - ret.Count ] );
- }
- return ret.ToArray( );
- }
-
- public static string DecodeQ(byte[] inputBytes, string charSet) {
- var input = (new UTF8Encoding( )).GetString( inputBytes );
- Encoding enc;
- try {
- enc = Encoding.GetEncoding( charSet );
- } catch {
- enc = new UTF8Encoding( );
- }
- var occurences = new Regex( @"(=[0-9A-Z]{2}){1,}", RegexOptions.Multiline );
- var matches = occurences.Matches( input );
-
- foreach (Match match in matches) {
- try {
- byte[] b = new byte[ match.Groups[ 0 ].Value.Length / 3 ];
- for (int i = 0; i < match.Groups[ 0 ].Value.Length / 3; i++) {
- b[ i ] = byte.Parse( match.Groups[ 0 ].Value.Substring( i * 3 + 1, 2 ), System.Globalization.NumberStyles.AllowHexSpecifier );
- }
- char[] hexChar = enc.GetChars( b );
- input = input.Replace( match.Groups[ 0 ].Value, new String( hexChar ) );
- } catch { ;}
- }
- input = input.Replace( "?=", "" ).Replace( "\r\n", "" );
- return input;
- }
- #endregion
-
- ///
- /// Standard Windows iso-8859-1-encoding page.
- ///
- static Encoding s_Encoder = GetDefaultEncoding( ); // Default Fallback
-
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static byte[] Encode(string value, int lenght, string CharacterSet) {
- byte[] ret = null;
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length is too long", "value" );
- }
- var result = new byte[ lenght ];
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- Encoding.GetEncoding( CharacterSet ).GetBytes( value ).CopyTo( result, 0 );
- ret = EncodeQ( result, lenght );
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString( )+ "\n\rEncode()" + "\n\rWith = " + "\n\riso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- if (ret == null) {
- // Use defalt
- s_Encoder.GetBytes( value ).CopyTo( result, 0 );
- ret = EncodeQ( result, lenght );
- }
- /*#warning "!!!!!!!!!!!!!!!!! Testing !!!!!!!!!!!!!!!!!!!!!!!"
- string test = new UTF8Encoding( ).GetString( ret );*/
- return ret;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static byte[] Encode(string value, int lenght) { return Encode( value, lenght, null ); }
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static string Decode(byte[] value, int lenght, string CharacterSet) {
- if (value.Length != lenght) {
- throw new ArgumentException( "value.Length wrong lenght", "value" );
- }
- /*#warning "!!!!!!!!!!!!!!!!! Testing !!!!!!!!!!!!!!!!!!!!!!!"
- string test = new UTF8Encoding( ).GetString( value );*/
- string result = null;
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- result = DecodeQ( value, CharacterSet );
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString() + "\n\rDecode()" + "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- // Use defalt
- if (result == null) {
- result = DecodeQ( value, DefaultEncoding );
- }
- var index = result.IndexOf( '\0' );
- if (index >= 0) {
- return result.Substring( 0, result.IndexOf( '\0' ) );
- }
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static string Decode(byte[] value, int lenght) { return Decode( value, lenght, null ); }
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderUnicode.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderUnicode.cs
deleted file mode 100644
index 0ac0ec5d..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoderUnicode.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-using System;
-using System.Text;
-using XYLEM.Communication;
-
-namespace XYLEM.Communication.ValueEncoders
-{
- public static class StringEncoderUnicode
- {
- ///
- /// Standard Windows 1252-encoding page.
- ///
- static Encoding s_Unicode = Encoding.BigEndianUnicode;
-
- public static byte[] Encode(string value, int lenght)
- {
- if (value.Length > lenght)
- {
- throw new ArgumentException("value.Length is too long", "value");
- }
-
- var result = new byte[lenght];
- s_Unicode.GetBytes(value).CopyTo(result, 0);
- return result;
- }
-
- public static string Decode(byte[] value, int lenght)
- {
- if (value.Length > lenght)
- {
- throw new ArgumentException("value.Length wrong lenght", "value");
- }
-
- var result = s_Unicode.GetString(value);
- var index = result.IndexOf('\0');
- if (index >= 0)
- return result.Substring(0, result.IndexOf('\0'));
- else
- return result;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoder_W1252.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoder_W1252.cs
deleted file mode 100644
index 25f0a58f..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/StringEncoder_W1252.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using System;
-using System.Text;
-using XYLEM.Communication;
-
-namespace XYLEM.Communication.ValueEncoders {
- public static class StringEncoder_W1252 {
- public static Encoding GetDefaultEncoding( ) {
- return Encoding.GetEncoding( 1252 );
- }
-
- ///
- /// Standard Windows 1252-encoding page.
- ///
- static Encoding s_Win1252 = GetDefaultEncoding( );
-
- public static byte[] Encode(string value, int lenght) {
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length is too long", "value" );
- }
-
- var result = new byte[ lenght ];
- s_Win1252.GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
-
- public static string Decode(byte[] value, int lenght) {
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length wrong lenght", "value" );
- }
-
- var result = s_Win1252.GetString( value );
- var index = result.IndexOf( '\0' );
- if (index >= 0)
- return result.Substring( 0, result.IndexOf( '\0' ) );
- else
- return result;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Communication/ValueEncoders/U32_IP_Encoder.cs b/Common/modbus_master_csharp/Communication/ValueEncoders/U32_IP_Encoder.cs
deleted file mode 100644
index 2f1770ea..00000000
--- a/Common/modbus_master_csharp/Communication/ValueEncoders/U32_IP_Encoder.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using XYLEM.Base;
-
-namespace XYLEM.Communication.ValueEncoders {
- ///
- /// IP Address encoder when it has to be converted to a u32 value
- ///
- internal static class U32_IP_Encoder {
- ///
- /// Check if string is okay and possible to encode
- ///
- ///
- ///
- internal static bool IsOkay(string stringForCheck) {
- try {
- if (string.IsNullOrEmpty( stringForCheck )) {
- return false; // if string empty, then this is off and there is nothing to check
- }
- try {
- var test = Encode( stringForCheck );
- } catch {
- return false; // Error is not possible to convert
- }
- return true; // Okay to convert
- } catch (Exception ex) {
- throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "IsOkay" ) );
- }
- }
-
- ///
- /// Encode xxx.xxx.xxx.xxx to bytes
- ///
- ///
- ///
- static internal byte[] Encode(string ip_XXX_XXX_XXX_XXX) {
- try {
- var splited = ip_XXX_XXX_XXX_XXX.Split( '.' );
- if (splited.Count( ) != 4) {
- throw new Exception( "IP must be formated xxx.xxx.xxx.xxx but is " + ip_XXX_XXX_XXX_XXX.ToString( ) );
- }
- var values = splited.Select( value => byte.Parse( value ) );
- return values.ToArray( );
- } catch (Exception ex) {
- throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "Encode" ) );
- }
- }
-
- ///
- /// decode bytes
- ///
- ///
- /// xxx.xxx.xxx.xxx
- static internal string Decode(byte[] data) {
- try {
- if ((data == null) || (data.Count( ) != 4)) {
- throw new Exception( "Must be 4 bytes" );
- }
- return String.Format( "{0}.{1}.{2}.{3}", data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ] );
- } catch (Exception ex) {
- throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "Decode" ) );
- }
- }
-
- }
-}
diff --git a/Common/modbus_master_csharp/Device/CalibrationPoint.cs b/Common/modbus_master_csharp/Device/CalibrationPoint.cs
deleted file mode 100644
index 8048e942..00000000
--- a/Common/modbus_master_csharp/Device/CalibrationPoint.cs
+++ /dev/null
@@ -1,121 +0,0 @@
-using System;
-using System.Xml;
-
-namespace XYLEM.Device
-{
- ///
- /// A single calibration point
- ///
- [Serializable]
- public class CalibrationPoint : IComparable, IEquatable
- {
- ///
- /// Reference flow in liter / second
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342
- ///
- public Single ReferenceFlowRate_lps { get; set; }
-
- ///
- /// DUT Reported flow in liter / second
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342
- ///
- public Single ReportedFlowRate_lps { get; set; }
-
- public CalibrationPoint()
- {
- ReferenceFlowRate_lps = ReportedFlowRate_lps = 0;
- }
-
- ///
- /// Ctor
- ///
- /// reference flow rate [l/s] given by the flow-test-bench
- /// reported flow rate [l/s] by the DUT
- public CalibrationPoint(Single referenceFlowRate_lps, Single reportedFlowRate_lps)
- {
- ReferenceFlowRate_lps = referenceFlowRate_lps;
- ReportedFlowRate_lps = reportedFlowRate_lps;
- }
-
- public override string ToString()
- {
- const int w1 = 11;
- return $"Ref={ReferenceFlowRate_lps*3.6,w1:F6} m3/h DUT={ReportedFlowRate_lps*3.6,w1:F6} m3/h " +
- $"(Ref={ReferenceFlowRate_lps,w1:F6} l/s DUT={ReportedFlowRate_lps,w1:F6} l/s)";
- }
-
- public int CompareTo(CalibrationPoint other)
- {
- // If null, it can't be the same
- if (System.Object.ReferenceEquals(other, null))
- {
- return -1;
- }
- // Any of them is not okay
- if ((this.ReferenceFlowRate_lps!= other.ReferenceFlowRate_lps) || (this.ReportedFlowRate_lps!= other.ReportedFlowRate_lps))
- {
- return -1; // Not the same
- }
- return 0; // is the same
- }
-
- public bool Equals(CalibrationPoint other)
- {
- return this.CompareTo(other) == 0;
- }
-
- #region Operator == > < ! ..
- public static bool operator ==(CalibrationPoint a, CalibrationPoint b)
- {
- // If both are null, or both are same instance, return true.
- if (System.Object.ReferenceEquals(a, b))
- {
- return true;
- }
-
- // If one is null, but not both, return false.
- // from https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type?redirectedfrom=MSDN
- if (a is null)
- {
- // null == null = true.
- if (b is null)
- {
- return true;
- }
- // Only the left side is null.
- return false;
- }
-
- // Return true if the fields match:
- return (a.Equals(b));
- }
-
- public static bool operator !=(CalibrationPoint a, CalibrationPoint b)
- {
- return !(a == b);
- }
-
- public static bool operator <(CalibrationPoint a, CalibrationPoint b)
- {
- return a.CompareTo(b) < 0;
- }
-
- public static bool operator >(CalibrationPoint a, CalibrationPoint b)
- {
- return a.CompareTo(b) > 0;
- }
-
- public static bool operator >=(CalibrationPoint a, CalibrationPoint b)
- {
- return a.CompareTo(b) >= 0;
- }
-
- public static bool operator <=(CalibrationPoint a, CalibrationPoint b)
- {
- return a.CompareTo(b) <= 0;
- }
-
- #endregion
- }
-
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Device/CalibrationPoints.cs b/Common/modbus_master_csharp/Device/CalibrationPoints.cs
deleted file mode 100644
index fa33eb6e..00000000
--- a/Common/modbus_master_csharp/Device/CalibrationPoints.cs
+++ /dev/null
@@ -1,198 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Xml;
-using XYLEM.Base.XML;
-
-namespace XYLEM.Device
-{
- [Serializable]
- public class CalibrationPoints : IComparable, IEquatable
- {
- ///
- /// calibrations to or from DUT
- ///
- public List calibrations { get; private set; }
-
- public void SaveToFile(string filePath)
- {
- XMLWriteFuncClass.WriteToXmlFile(filePath, calibrations, false);
- }
-
- ///
- ///
- ///
- ///
- /// Is a valid calibration for DUT
- public bool LoadFromFile(string filePath)
- {
- var pointsSaved = XMLWriteFuncClass.ReadFromXmlFile>(filePath);
- calibrations = pointsSaved;
- return IsOkay();
- }
-
- ///
- /// Constructor for A empty list of calibrations, to use for loading calibrations from file
- ///
- public CalibrationPoints()
- {
- calibrations = new List();
- }
-
-
- ///
- ///
- ///
- ///
- /// Maximum numbers of calibration able to write to device
- public CalibrationPoints(List cal_points, int maxTotalPoints)
- {
- if (cal_points == null)
- {
- throw new ArgumentNullException("Calibrations points can't be zero");
- }
- if (cal_points.Count > maxTotalPoints)
- {
- throw new Exception($"Has {cal_points.Count} calibrations points and only support {maxTotalPoints}");
- }
- // Pad with zero if not the full size. Done to make a working writing and comparing two calibrations.
- if (cal_points.Count < maxTotalPoints)
- {
- var missing = maxTotalPoints-cal_points.Count;
- cal_points.AddRange(Enumerable.Range(0, missing).Select(_ => new CalibrationPoint(0, 0)));
- }
- calibrations = cal_points;
- }
-
- ///
- /// Is a valid calibration to or from DUT
- ///
- ///
- public Boolean IsOkay()
- {
- if ((null == calibrations) || (0 > calibrations.Count))
- {
- return false; // Not okay
- }
- return true; // Is okay
- }
-
- ///
- /// Number of calibrations to or from DUT
- ///
- /// is 0 or more if okay and -1 on error / not okay
- public int Get_number_of_calibrations()
- {
- if (!IsOkay())
- {
- return -1;
- }
- return calibrations.Count;
- }
-
- public override string ToString()
- {
- if (!IsOkay())
- {
- return "No valide calibration to print out";
- }
- var ret_txt = "";
- var idx = 0;
- foreach (var cal in calibrations)
- {
- ret_txt += $"{idx++}: {cal}\n";
- }
- return ret_txt;
- }
-
- public int CompareTo(CalibrationPoints other)
- {
- // If null, it can't be the same
- if (System.Object.ReferenceEquals(other, null))
- {
- return -1;
- }
-
- // Any of them is not okay
- if (!this.IsOkay() || !other.IsOkay())
- {
- return -1; // Not the same
- }
- // if number of items is not the same
- if (this.Get_number_of_calibrations() != other.Get_number_of_calibrations())
- {
- return -1; // Not the same
- }
- var num_of_cals = this.calibrations.Count;
- var my_cals = this.calibrations;
- var others_cals = other.calibrations;
- for (int i = 0; i < num_of_cals; i++)
- {
- if (my_cals[i] != others_cals[i])
- {
- return -1; // Not the same
- }
- }
- return 0; // is the same
- }
-
- public bool Equals(CalibrationPoints other)
- {
- return this.CompareTo(other) == 0;
- }
-
- #region Operator == > < ! ..
- public static bool operator ==(CalibrationPoints a, CalibrationPoints b)
- {
- // If both are null, or both are same instance, return true.
- if (System.Object.ReferenceEquals(a, b))
- {
- return true;
- }
-
- // If one is null, but not both, return false.
- // from https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type?redirectedfrom=MSDN
- if (a is null)
- {
- // null == null = true.
- if (b is null)
- {
- return true;
- }
- // Only the left side is null.
- return false;
- }
-
- // Return true if the fields match:
- return (a.Equals(b));
- }
-
- public static bool operator !=(CalibrationPoints a, CalibrationPoints b)
- {
- return !(a == b);
- }
-
- public static bool operator <(CalibrationPoints a, CalibrationPoints b)
- {
- return a.CompareTo(b) < 0;
- }
-
- public static bool operator >(CalibrationPoints a, CalibrationPoints b)
- {
- return a.CompareTo(b) > 0;
- }
-
- public static bool operator >=(CalibrationPoints a, CalibrationPoints b)
- {
- return a.CompareTo(b) >= 0;
- }
-
- public static bool operator <=(CalibrationPoints a, CalibrationPoints b)
- {
- return a.CompareTo(b) <= 0;
- }
- #endregion
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Device/IMagFluxRequestProtocol.cs b/Common/modbus_master_csharp/Device/IMagFluxRequestProtocol.cs
deleted file mode 100644
index 0e91b68b..00000000
--- a/Common/modbus_master_csharp/Device/IMagFluxRequestProtocol.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-using MagFlux6200_metrology_reg_list;
-using XYLEM.Communication;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO.Ports;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Device
-{
- ///
- /// Command interface for MagFlux 6200
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7112855120/Command+Interface+Draft
- ///
- public interface IMagFluxRequestProtocol
- {
- ///
- /// Is connected
- ///
- /// true if yes
- Boolean IsConnected();
-
- ///
- /// Make communication connection to Meter
- /// !!NOTE!! Only one meter is supported for each com port
- ///
- /// Like "COM1"
- /// true on okay or false on error
- Boolean Connect(string comport);
-
- ///
- /// Close communication connection to Meter
- ///
- /// true on okay or false on error
- Boolean CloseConnection();
-
- ///
- /// Get printout of communication counters
- ///
- ///
- string GetComCounters();
-
- ///
- /// Set location for where log data can saved.
- ///
- /// path for where to log file should be saved
- /// set a custom log file name without extension (ex. "UserCustomLogFile") or null if use default
- /// true on okay or false on error
- Boolean SetLogLocation(String path, string filename = null);
-
- ///
- /// Open saved log file
- ///
- void OpenLogFile();
-
- ///
- /// MagFlux Sensor serial number
- ///
- /// a decimal serial number ex. 12345678 or NULL at error
- /// true on okay or false on error
- Boolean GetSensorSerialNo(out string value_out);
-
-
- ///
- /// Set MagFlux Sensor serial number
- ///
- ///
- /// true on okay or false on error
- Boolean SetSensorSerialNo(UInt32 new_serial_number);
-
- ///
- /// Unique-ID for the MagFlux electronics
- ///
- /// a hex decimal string 0x1234ABCDEF or NULL at error
- /// true on okay or false on error
- Boolean GetUniqueId(out string value_out);
-
- ///
- /// Get the firmware version
- ///
- /// like 1.2.4 (MAJOR.MINOR.REVISION)
- /// true on okay or false on error
- Boolean GetFirmwareVersion(out string value_out);
-
- ///
- /// Get the firmware build date
- ///
- /// like 2022/12/24 13:00:00 or 2022-12-24 13:45:10
- /// true on okay or false on error
- Boolean GetFwBuildDate(out string value_out);
-
- ///
- /// Git Hash to Unique identify firmware
- ///
- /// like 0xABCDE123
- /// true on okay or false on error
- Boolean GetFwGitHash(out string value_out);
-
- ///
- /// Flow rate calibrated
- ///
- /// Actual flow rate [l/s]
- /// true on okay or false on error
- Boolean GetFlowRate_lps(out Single value_out);
-
- ///
- /// MagFlux Sensor nominal DN size in millimeters
- ///
- /// DN size in [mm] is -1 on error
- /// true on okay or false on error
- Boolean GetDn_mm(out Int32 dn_mm_out);
-
- ///
- /// Set Sensor nominal DN size in millimeters
- ///
- /// DN size in [mm] ex 50 is 50mm or DN50
- /// true on okay or false on error
- Boolean SetDn_mm(UInt16 new_dn_mm);
-
- ///
- /// Check if there is problem with the DUT
- /// use " to get a list of error messages for debug problems
- ///
- /// >true if device operates correctly
- Boolean GetDeviceHealthy();
-
- ///
- /// get a list of error messages for debug problem
- ///
- /// Will return a empty list if there is no messages to return
- /// true on okay or false on error
- Boolean GetDeviceErrorMessages(out List status_list_out);
-
- ///
- /// This function prepares the DUT for the calibration.
- ///
- /// ATTENTION:
- /// This function needs to be called before the calibration process starts any flow of water.
- ///
- /// true on okay or false on error
- Boolean PrepareDeviceForCalibration();
-
- ///
- /// This function will abort started or failed calibration to bring DUT back to normal calibration state
- ///
- /// true on okay or false on error
- Boolean AbortDeviceForCalibration();
-
- ///
- /// The maximum calibration points that is supported by the device
- ///
- int CalibrationPointsMax { get; }
-
- ///
- /// Get list of calibration points saved in DUT
- ///
- /// The calibrations points from device
- /// true on okay or false on error
- Boolean GetCalibrationPoints(out CalibrationPoints values_read);
-
- ///
- /// set calibration in DUT.
- /// Remember to run before the calibration process is started.
- ///
- /// A list of calibration points to write to DUT
- /// true on okay or false on error
- Boolean SetCalibrationPoints(CalibrationPoints new_calibration_points);
- }
-}
diff --git a/Common/modbus_master_csharp/Device/MagFlux6200.cs b/Common/modbus_master_csharp/Device/MagFlux6200.cs
deleted file mode 100644
index f5ae46ea..00000000
--- a/Common/modbus_master_csharp/Device/MagFlux6200.cs
+++ /dev/null
@@ -1,1190 +0,0 @@
-using MagFlux6200_metrology_reg_list;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO.Ports;
-using System.Linq;
-using System.Numerics;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Threading.Tasks;
-using XYLEM.Base;
-using XYLEM.Base.Files;
-using XYLEM.Communication;
-
-namespace XYLEM.Device
-{
- public enum RUN_TYPE
- {
- ///
- /// Make real connections to a device
- ///
- Normal,
-
- ///
- /// Mock that just return static values and need not _serial connection or connected MagFlux hardware
- ///
- Mock
- }
-
- ///
- /// MagFlux 6200 "Metrology" device API.
- ///
- /// Handling serial communication with a single device during sensor Calibration and verification.
- ///
- /// Note: All Modbus register used needs to be documented in confluence, to show Modbus dependency and insure future support and comparability.
- /// Confluence page https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7337054026/Modbus+register+-+Used+for+Sensor+calibration+and+verification+interface
- ///
- public class MagFlux6200 : ModbusDeviceCom, IMagFluxRequestProtocol
- {
- RUN_TYPE _runAs = RUN_TYPE.Normal;
-
- public MagFlux6200(RUN_TYPE runAs = RUN_TYPE.Normal) : base()
- {
- this._runAs = runAs;
- }
-
- public Boolean Connect(string comport)
- {
- try
- {
- /*metrology RS485 when transparent to metrology*/
- int baudRate = 9600;
- Parity parity = Parity.Even;
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- var result = Connect(comport, baudRate, parity);
- return result;
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail to open connection", ex);
- }
- return false; // failed
- }
-
- public override Boolean Connect(string comport, int baudRate, Parity parity)
- {
- try
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- {// Normal
- if (IsConnected())
- {
- CloseConnection();
- }
- var isOkay = base.Connect(comport, baudRate, parity);
- if (isOkay)
- {
- isOkay = Get_MdbsRegsVer(out var device_reglist_ver);
- var program_reglist_ver = (6200000 + reg_list.Met_U16DeviceType.Version);
- if (!isOkay)
- {
- var message = $"Device Modbus register list version is {(isOkay ? device_reglist_ver : "!Read failed!")}";
- Console.WriteLine(message);
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message);
- }
- else
- { // Check register list version
- var version = int.Parse(device_reglist_ver);
- if (program_reglist_ver != version)
- {
- // Warning to user that the register version is not the same as MagFlux has
- var message = $"Warning communicate!\nProgram use {program_reglist_ver} and may not supporting MagFlux {version}!";
- Console.WriteLine(message);
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message);
- isOkay = true;
- }
- else
- {
- Console.WriteLine($"Communication with Modbus register list ver. {program_reglist_ver}");
- }
- }
- if (!isOkay)
- {
- CloseConnection();
- }
- else
- {
- StartBackgroundChecking();
- }
- }
- return isOkay; // return result
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail to open connection", ex);
- }
- return false; // failed
- }
-
- #region Background service
- ///
- /// Device Healthy status that is periodically updated in background task
- ///
- private bool? _DeviceHealthy;
-
- ///
- /// List with info about what errors is detected
- ///
- private List _DeviceHealthyMsgList = new List();
-
- private UInt16 _Met_U16EmptyPipeStatus = 0;
- private UInt32 _Met_U32Errors = 0;
- private UInt16 _Met_U16Flow_CalibStatus = 0;
- private int _HandlerBackgroundReadStageNow = 0;
-
- ///
- /// Handle checking DUT and background reading device values
- ///
- ///
- protected override void RunBackgroundReadServiceFunction()
- {
- try
- {
- // Is just running as a Mock
- //if (true)
- if (_runAs == RUN_TYPE.Mock)
- {
- _DeviceHealthy = true; // is okay
- }
- else
- {// Normal
- // Run one value for every background task call
- switch (_HandlerBackgroundReadStageNow++)
- {
- case 0:
- { // Read errors
- var valueInfo = reg_list.Met_U32Errors;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- _Met_U32Errors = value.Value;
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- _Met_U32Errors = UInt32.MaxValue; // ERROR: Did not receive a value
- }
- }
- break;
- case 1:
- { // Read Empty pipe
- var valueInfo = reg_list.Met_U16EmptyPipeStatus;
- try
- {
- var value = read_U16(valueInfo);
- // Is okay
- if (value != null)
- {
- _Met_U16EmptyPipeStatus = value.Value;
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- _Met_U16EmptyPipeStatus = UInt16.MaxValue; // ERROR: Did not receive a value
- }
- }
- break;
- case 2:
- { // Read calibration state
- var valueInfo = reg_list.Met_U16Flow_CalibStatus;
- try
- {
- var value = read_U16(valueInfo);
- // Is okay
- if (value != null)
- {
- _Met_U16Flow_CalibStatus = value.Value;
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- _Met_U16Flow_CalibStatus = UInt16.MaxValue; // ERROR: Did not receive a value
- }
- }
- break;
- default:
- // Return to start
- _HandlerBackgroundReadStageNow=0;
- break;
-
- }
- UpdateDeviceHealthy();
- }
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail background service handling";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- _DeviceHealthy = false; // ERROR: Did failing updating value, then just put it as not Healthy
- _DeviceHealthyMsgList = new List()
- {
- "Unknown failing for updating device healthy"
- };
- }
- }
-
- private void UpdateDeviceHealthy()
- {
- try
- {
- var newHealthy = true;
- var newMsgList = new List();
- { // Check Errors
- if (_Met_U32Errors != 0)
- {
- newHealthy = false;
- if (_Met_U32Errors == UInt32.MaxValue)
- {
- newMsgList.Add("System error has unknown error");
- }
- else
- {
- newMsgList.Add($"System error 0x{_Met_U32Errors:X}");
- }
- }
- }
- { // Check empty pipe
- // https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6659966841/Empty+Pipe+Detection+EPD#Empty-pipe-status
- if ((_Met_U16EmptyPipeStatus&1) != 0) // If empty pipe active
- {
- newHealthy = false;
- // Bit for empty pipe used for show pipe level.
- switch ((_Met_U16EmptyPipeStatus >> 1) & 7)
- {
- case 0x01: // Below empty
- newMsgList.Add("Pipe Empty");
- break;
- case 0x02: // Between empty & full
- newMsgList.Add("Pipe Below Half");
- break;
- case 0x04: // Above full
- newMsgList.Add("Pipe Above full");
- break;
- default:
- if (_Met_U16EmptyPipeStatus == UInt16.MaxValue)
- {
- newMsgList.Add("Pipe Empty has unknown error");
- }
- break;
- }
- }
- }
- { // Check Calibration status
- var calstatus = GetCalErrStatus(_Met_U16Flow_CalibStatus);
- if (calstatus != CalibrationErrorStatus.AllOK)
- {
- newHealthy = false;
- newMsgList.Add(GetCalErrText(calstatus));
- }
- }
- // Update to the new status
- _DeviceHealthy = newHealthy;
- _DeviceHealthyMsgList = newMsgList;
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail updating device healthy", ex);
- _DeviceHealthy = false; // ERROR: indicate error
- }
- }
- #endregion // Background service
-
- class CalPointsRegInfo
- {
- internal Device_value Reference { get; }
- internal Device_value Reported { get; }
-
- public CalPointsRegInfo(Device_value reference, Device_value reported)
- {
- Reference = reference;
- Reported = reported;
- }
-
- public override string ToString()
- {
- return $"Cal point ref={Reference.Name} rep={Reported.Name}";
- }
-
- }
-
- List NewCalRegInfoList = new List {
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt0_lps, reg_list.Met_F32Flow_NewReportedPt0_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt1_lps, reg_list.Met_F32Flow_NewReportedPt1_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt2_lps, reg_list.Met_F32Flow_NewReportedPt2_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt3_lps, reg_list.Met_F32Flow_NewReportedPt3_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt4_lps, reg_list.Met_F32Flow_NewReportedPt4_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt5_lps, reg_list.Met_F32Flow_NewReportedPt5_lps),
- };
-
- ///
- /// Present accepted Calibration (Note is read only)
- ///
- List PresentCalRegInfoList = new List {
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint0_reference_lps, reg_list.Met_F32FlowPresentPoint0_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint1_reference_lps, reg_list.Met_F32FlowPresentPoint1_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint2_reference_lps, reg_list.Met_F32FlowPresentPoint2_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint3_reference_lps, reg_list.Met_F32FlowPresentPoint3_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint4_reference_lps, reg_list.Met_F32FlowPresentPoint4_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint5_reference_lps, reg_list.Met_F32FlowPresentPoint5_reported_lps),
- };
-
- public int CalibrationPointsMax { get { return NewCalRegInfoList.Count; } }
-
-
- #region Calibration Error flags
- ///
- /// Calibration Error flags
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- [Flags]
- enum CalibrationErrorStatus
- {
- ///
- /// Bits 0000: All OK
- ///
- AllOK = 0,
-
- ///
- /// Bits 0001: Bad point
- ///
- ErrorInPoint = 0b0001,
-
- ///
- /// Bits 0010: Bad gradient
- ///
- ErrorInGradient = 0b0010,
-
- ///
- /// Bits 1111: Bad other
- ///
- GeneralError = 0b1111,
-
- ///
- /// Haven't any knowledge on it you
- ///
- UnkownError = 0xFFFF,
- }
-
- ///
- /// Get the cal error status from Calibration status register
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- /// Read from "Met_U16Flow_CalibCtrl"
- ///
- CalibrationErrorStatus GetCalErrStatus(UInt16 CalibStatus)
- {
- var status = (CalibStatus&0xF00)>>8;
- try
- {
- return (CalibrationErrorStatus)status;
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to convert {status} to {typeof(CalibrationErrorStatus)}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- return CalibrationErrorStatus.UnkownError;
- }
-
- }
-
- static string AppendErrorTxt(ref string to, string append)
- {
- to = $"{to}[{append}]";
- return to;
- }
-
- ///
- /// Convert the calibration error to a string
- ///
- ///
- ///
- string GetCalErrText(CalibrationErrorStatus status)
- {
- var ret = "";
- switch (status)
- {
- case CalibrationErrorStatus.AllOK:
- AppendErrorTxt(ref ret, "All Cal OK");
- break;
- case CalibrationErrorStatus.ErrorInPoint:
- AppendErrorTxt(ref ret, "Error in point");
- break;
- case CalibrationErrorStatus.ErrorInGradient:
- AppendErrorTxt(ref ret, "Error in gradient");
- break;
- case CalibrationErrorStatus.UnkownError:
- AppendErrorTxt(ref ret, "Unknown error");
- break;
- default:
- AppendErrorTxt(ref ret, $"Unknown error 0x{status:X}");
- break;
- }
- return ret;
- }
- #endregion //#region Calibration Error flags
-
- ///
- /// Calibration state
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- enum CalibrationState
- {
- Normal = 0,
- CalibrationMode = 1,
- UnkownError,
- }
-
- ///
- /// Convert the Calibration State to a string
- ///
- ///
- ///
- string GetCalStateText(CalibrationState state)
- {
- var ret = "";
- switch (state)
- {
- case CalibrationState.Normal:
- AppendErrorTxt(ref ret, "Normal");
- break;
- case CalibrationState.CalibrationMode:
- AppendErrorTxt(ref ret, "Calibration Mode");
- break;
- case CalibrationState.UnkownError:
- AppendErrorTxt(ref ret, "Unknown error");
- break;
- default:
- AppendErrorTxt(ref ret, $"Unknown state 0x{state:X}");
- break;
- }
- return ret;
- }
-
- ///
- /// Get current calibration state from Calibration status register
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- /// Read from "Met_U16Flow_CalibCtrl"
- ///
- CalibrationState GetCurrentCalState(UInt16 CalibStatus)
- {
- var status = (CalibStatus&0x1);
- try
- {
- return (CalibrationState)status;
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to convert {status} to {typeof(CalibrationState)}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- return CalibrationState.UnkownError;
- }
- }
-
- ///
- /// Get current calibration state from Calibration status register
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- /// Read from "Met_U16Flow_CalibCtrl"
- ///
- CalibrationState GetPreviousCalState(UInt16 CalibStatus)
- {
- var status = ((CalibStatus&0xC)>>2);
- try
- {
- return (CalibrationState)status;
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to convert {status} to {typeof(CalibrationState)}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- return CalibrationState.UnkownError;
- }
- }
-
- enum CalibrationCommand
-
- {
- ///
- /// 00: Unused
- ///
- Unused = 0b00,
-
- ///
- /// 01: Enter
- ///
- Enter = 0b01,
-
- ///
- /// 10: Confirm
- ///
- Confirm = 0b10,
-
- ///
- /// 11: Abort
- ///
- Abort = 0b11,
-
- ///
- /// Unknown error
- ///
- UnkownError = 0xFFFF
- }
-
- ///
- /// Get current calibration state from Calibration status register
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- /// Read from "Met_U16Flow_CalibCtrl"
- ///
- CalibrationCommand GetPreviousCalCommand(UInt16 CalibStatus)
- {
- var status = ((CalibStatus&0x20)>>5);
- try
- {
- return (CalibrationCommand)status;
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to convert {status} to {typeof(CalibrationCommand)}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- return CalibrationCommand.UnkownError;
- }
- }
-
- ///
- /// Set a calibration command in device
- ///
- ///
- ///
- bool SetCalCommand(CalibrationCommand command)
- {
- var isOkay = false;
- try
- {
- isOkay = write_U16(reg_list.Met_U16Flow_CalibCtrl, (UInt16)command);
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to write {command}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- }
- return isOkay;
- }
-
- public Boolean GetDeviceErrorMessages(out List status_list_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- status_list_out = new List(); // is okay
- return true; // is okay
- }
- {// Normal
- //TODO: There is not errors to convert yet throw new System.NotImplementedException();
- status_list_out = _DeviceHealthyMsgList; // is okay
- return true; // is okay
- }
- }
-
- public Boolean GetDeviceHealthy()
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- var wait_max_s = 5;
- var wait_pull_ms = 10;
- var start_wait_count = wait_max_s*(1000.0/wait_pull_ms);
- while (_DeviceHealthy == null)
- {
- Thread.Sleep(wait_pull_ms);
- if (start_wait_count-- <=0)
- {
- throw new Exception("Fail getting a updated DeviceHealthy");
- }
- }
- return _DeviceHealthy.Value;
- }
-
- public Boolean GetDn_mm(out Int32 dn_mm_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- dn_mm_out = 50; // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U16PipeDiameterConfig_mm;
- try
- {
- var value = read_U16(valueInfo);
- // Is okay
- if (value != null)
- {
- dn_mm_out = (int)value.Value;
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- dn_mm_out = -1; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
- public bool SetDn_mm(UInt16 new_dn_mm)
- {
- var isOkay = false;
- try
- {
- isOkay = GetDn_mm(out var current);
- // Only write DN if different
- if(current != new_dn_mm)
- {
- isOkay &= write_U16(reg_list.Met_U16PipeDiameterConfig_mm, (UInt16)new_dn_mm);
- }
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to write DN {new_dn_mm}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- }
- return isOkay;
- }
-
- public Boolean GetFirmwareVersion(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out="1.2.3"; // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32FirmwareVersion;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- var GIT_VERSION_MAJOR = value>>24;
- var GIT_VERSION_MINOR = (value>>16) & ((1<<16)-1);
- var GIT_VERSION_REVISION = (value & ((1<<16)-1));
- value_out = $"{GIT_VERSION_MAJOR}.{GIT_VERSION_MINOR}.{GIT_VERSION_REVISION}";
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
- public Boolean GetFlowRate_lps(out Single value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = 1.2345F; // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_F32FlowRate_lps;
- try
- {
- var value = read_F32(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = value.Value;
- return true; // is okay
- }
- throw new Exception("value returned was null");
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = 0; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
- public Boolean GetFwBuildDate(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = TimeConvertClass.ToLocalDateTimeString(DateTime.Now); // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32FmwrBuildDate;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- int year = (int)(value.Value/1000000);
- int Month = (int)((value.Value%1000000)/10000);
- int day = (int)((value.Value%10000)/100);
- int hour = (int)(value.Value%100);
- DateTime time = new DateTime(year, Month, day, hour, 0, 0);
- value_out = TimeConvertClass.ToLocalDateTimeString(time);
- return true; // is okay
- }
- throw new Exception("value returned was null");
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
-
- public Boolean Get_MdbsRegsVer(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = (6200000 + reg_list.Met_U16DeviceType.Version).ToString(); // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32MdbsRegsVer;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = value.ToString();
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
-
- public Boolean GetFwGitHash(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = "0xF3573B9";
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32FmwrGITHash;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = $"0x{value:X}";
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
-
- public Boolean GetSensorSerialNo(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = "0";
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32SensorSerialNo;
- try
- {
- // TODO: is this to be converted to new format maybe like yyyy/mm/day
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = $"{value}";
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
-
- public bool SetSensorSerialNo(UInt32 new_serial_number)
- {
- var isOkay = false;
- try
- {
- isOkay = write_U32(reg_list.Met_U32SensorSerialNo, new_serial_number);
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to write Sensor SN {new_serial_number}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- }
- return isOkay;
- }
-
-
-
- public Boolean GetUniqueId(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = "0";
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U128_CPU_ID;
- try
- {
- var value = read_U128(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = $"0x{value:x}";
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
- #region Calibration points handling
- public Boolean GetCalibrationPoints(out CalibrationPoints values_read)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- values_read = new CalibrationPoints(
- new List {
- new CalibrationPoint(0,0), // 0
- new CalibrationPoint(1,1), // 1
- new CalibrationPoint(5,5), // 2
- },
- CalibrationPointsMax
- );
- return true; // is okay
- }
- {// Normal
- try
- {
- var cals = new List();
- var calP_dvis = PresentCalRegInfoList;
- // ---------- Do read ----------
- var dvList = new List();
- // Add status
- var u16CalStatusReg = reg_list.Met_U16Flow_CalibStatus;
- dvList.Add(u16CalStatusReg);
- // Add cal points
- foreach (var point in calP_dvis)
- {
- dvList.Add(point.Reference);
- dvList.Add(point.Reported);
- }
- var reads = read(dvList);
- if ((reads == null) || (reads.Count == 0))
- {
- throw new Exception("No read data returned");
- }
- // ---------- Handle read respond ----------
- // Check that calibration needs to be in normal mode and accepted before getting the calibration.
- var u16CalStatusValue = reads.Find(data => data.Info == u16CalStatusReg);
- if ((u16CalStatusValue != null) && (u16CalStatusValue != null))
- {
- var calstatus = GetCalErrStatus((UInt16)u16CalStatusValue.Data);
- if (calstatus != CalibrationErrorStatus.AllOK)
- {
- throw new Exception($"Calibration status must be {GetCalErrText(CalibrationErrorStatus.AllOK)} and not {GetCalErrText(calstatus)}");
- }
- var calState = GetCurrentCalState((UInt16)u16CalStatusValue.Data);
- if (calState != CalibrationState.Normal)
- {
- throw new Exception($"Calibration state must be {GetCalStateText(CalibrationState.Normal)} and not {GetCalStateText(calState)}");
- }
- }
-
- // Get calibrations
- foreach (var point in PresentCalRegInfoList)
- {
- try
- {
- var ref_value_lps = reads.Find(data => data.Info == point.Reference);
- var rep_value_lps = reads.Find(data => data.Info == point.Reported);
- // Is okay
- if ((ref_value_lps != null) && (rep_value_lps != null))
- {
- cals.Add(new CalibrationPoint(Convert.ToSingle(ref_value_lps.Data), Convert.ToSingle(rep_value_lps.Data)));
- }
- else
- {
- throw new Exception("value returned was null");
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(point.ToString()), "Fail to read values", ex);
- throw new Exception($"Faild cal point read of {point} ");
- }
- }
- values_read = new CalibrationPoints(cals, CalibrationPointsMax);
- return true; // is okay
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail to read value", ex);
- }
- values_read = null;
- return false; // failed
- }
- }
-
- public Boolean AbortDeviceForCalibration()
- {
-
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- {// Normal
- try
- {
- // Abort any calibration that have been started and possible failed.
- if (!SetCalCommand(CalibrationCommand.Abort))
- {
- throw new Exception("Was not able to abort calibration");
- }
- return true; // is okay
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail preparing for calibrations", ex);
- }
- return false; // failed
- }
- }
-
-
- public Boolean PrepareDeviceForCalibration()
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- {// Normal
- try
- {
- // Generate default calibrations points to use for calibration
- var cals = new List();
- for (int i = 0; i < NewCalRegInfoList.Count; i++)
- {
- cals.Add(new CalibrationPoint(0, 0));
- }
- var calPoints = new CalibrationPoints(cals, CalibrationPointsMax);
- if (!SetCalibrationPoints(calPoints))
- {
- throw new Exception("Fail writing default 0 calibration to DUT");
- }
- return true; // is okay
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail preparing for calibrations", ex);
- }
- return false; // failed
- }
- }
-
- public Boolean SetCalibrationPoints(CalibrationPoints new_calibration_points)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- {// Normal
- try
- {
- if ((new_calibration_points == null) || (new_calibration_points.Get_number_of_calibrations() <= 0))
- {
- throw new Exception("Calibrations is not valid to write");
- }
- if (!new_calibration_points.IsOkay())
- {
- var pointsTxt = "?";
- if (new_calibration_points.calibrations != null)
- {
- var points = new_calibration_points.calibrations.Select(point => point.ToString());
- pointsTxt = $"{String.Join("|", points)}";
- }
- throw new Exception($"Calibrations to write is not okay\n {pointsTxt}");
- }
- // Set calibration to default 0 before beginning.
- if (!SetCalCommand(CalibrationCommand.Enter))
- {
- throw new Exception("Was not able to enter calibration mode");
- }
- var cals = new List();
- var calP_dvis = NewCalRegInfoList;
- // Check if calibrations to write is valid
- if (calP_dvis.Count() < new_calibration_points.Get_number_of_calibrations())
- {
- throw new Exception($"Fail writing calibrations! Support {calP_dvis.Count()} points, given {new_calibration_points.Get_number_of_calibrations()} to write");
- }
- // ---------- Do read ----------
- var reqList = new List();
-
- { // Add cal points
- var idx = 0;
- var calPoints = new_calibration_points.calibrations;
- foreach (var point in calP_dvis)
- {
- var calWr = new CalibrationPoint(0, 0); // Set default up, if points haven't been entered
- if (idx < calPoints.Count)
- {
- calWr = calPoints[idx];
- }
- reqList.Add(new ModbusDataRequest(false, calWr.ReferenceFlowRate_lps, point.Reference));
- reqList.Add(new ModbusDataRequest(false, calWr.ReportedFlowRate_lps, point.Reported));
- idx++;
- }
- }
- var results = write(reqList);
- if ((results == null) || (results.Count != reqList.Count))
- {
- throw new Exception("Unknown Write failing of calibration");
- }
- { // Check if any has failed
- var failedOnes = results.Where(result => !result.IsOkay);
- if (failedOnes.Count() > 0)
- {
- var names = failedOnes.Select(result => result.Info.Name);
- throw new Exception($"Write failing of calibration {String.Join("|", names)}");
- }
- }
- // Finish and setting calibration in use
- if (!SetCalCommand(CalibrationCommand.Confirm))
- {
- throw new Exception("Was not able to enter calibration");
- }
- {// Check calibrations is written correct
- if (!GetCalibrationPoints(out var calRead) || (calRead == null) || (calRead.Get_number_of_calibrations() != calP_dvis.Count))
- {
- throw new Exception("Failed reading default calibration written");
- }
- var calPoints = new_calibration_points.calibrations;
- var failedOnes = new List();
- var idx = 0;
- foreach (var read in calRead.calibrations)
- {
- var calWr = new CalibrationPoint(0, 0); // Set default up, if points haven't been entered
- if (idx < calPoints.Count)
- {
- calWr = calPoints[idx];
- }
- if ((read.ReferenceFlowRate_lps != calWr.ReferenceFlowRate_lps) || (read.ReportedFlowRate_lps != calWr.ReportedFlowRate_lps))
- {
- failedOnes.Add(calWr);
- var msg = $"Write failing of calibration idx {idx}\n As {calWr}\n Was {read}";
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), msg);
- }
- idx++;
- }
- if (failedOnes.Count() > 0)
- {
- var values = failedOnes.Select(point => point.ToString());
- throw new Exception($"Write failing of calibration {String.Join("|", values)}");
- }
- }
- return true; // is okay
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail writing calibrations", ex);
- // Make sure that calibration is off
- AbortDeviceForCalibration();
- }
- return false; // failed
- }
- }
-
- #endregion //#region Calibration points
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Device/MagFlux6200_metrology_modbus_dependency_documentation.url b/Common/modbus_master_csharp/Device/MagFlux6200_metrology_modbus_dependency_documentation.url
deleted file mode 100644
index 595941e5..00000000
--- a/Common/modbus_master_csharp/Device/MagFlux6200_metrology_modbus_dependency_documentation.url
+++ /dev/null
@@ -1,5 +0,0 @@
-[{000214A0-0000-0000-C000-000000000046}]
-Prop3=19,11
-[InternetShortcut]
-IDList=
-URL=https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7337054026/Modbus+register+-+Used+for+Sensor+calibration+and+verification+interface
diff --git a/Common/modbus_master_csharp/Device/MagFlux6200_metrology_reg_list.cs b/Common/modbus_master_csharp/Device/MagFlux6200_metrology_reg_list.cs
deleted file mode 100644
index 6c750776..00000000
--- a/Common/modbus_master_csharp/Device/MagFlux6200_metrology_reg_list.cs
+++ /dev/null
@@ -1,1211 +0,0 @@
-/* @page Declaration for "Gluing" Metrology Modbus API in to Application
-* AUTO GENERATED DON'T EDIT, IS GENERATED WITH "MagFlux6200_metrology_reg_listvX.py @ 2023_10_19__08_34"
-* From: https://bitbucket.org/xyleminc/magflux_modbus_registers/src/main/Registers/
-*/
-
-using XYLEM.Device.Value;
-using XYLEM.Communication;
-using System;
-
-/*---------------------------------------------------------------------------*/
-
-namespace MagFlux6200_metrology_reg_list
-{
-
-/*---------------------------------------------------------------------------*/
-
- ///
- /// Value support
- ///
- public enum ValueRW_Type
- {
- ReadOnly,
- WriteOnly,
- ReadWrite,
- // Alway last
- Unknown,
- };
-
- ///
- /// Used for containing the information for access metrology values
- ///
- public class Device_value
- {
- ///
- /// @brief Version number of Metrology register list.
- /// The md_master_csharp_6200_reg_list.cs files were created from this version
- ///
- public int Version { get { return 46; } }
-
- ///
- /// Variable name
- ///
- public string Name { get; private set; }
-
- ///
- /// Modbus address to access data on (0 - 65535)
- ///
- public int MD_adr { get; private set; }
-
- ///
- /// Data type to expect data to be returned as
- ///
- public ValueDataType Datatype { get; private set; }
-
- ///
- /// Read Write support
- ///
- public ValueRW_Type RW { get; private set; }
-
- ///
- /// The value information
- ///
- public string Info { get; private set; }
-
- public Device_value(string name, int md_adr, ValueDataType datatype, ValueRW_Type rw, string info)
- {
- this.Name = name;
- this.MD_adr = md_adr;
- this.Datatype = datatype;
- this.RW = rw;
- this.Info = info;
- }
-
- public override string ToString()
- {
- return Name;
- }
- }
-/*---------------------------------------------------------------------------*/
-/*---------------------------------------------------------------------------*/
-
- internal class reg_list
- {
-
-
-/*------------------------------ block number 0 ------------------------------*/
-
- ///
- /// @brief Device type used at MJK. Metrology = 0x003C
- ///
- internal static readonly Device_value Met_U16DeviceType = new Device_value("Met_U16DeviceType", 0, ValueDataType.U16, ValueRW_Type.ReadWrite, "Device type used at MJK. Metrology = 0x003C ");
-
- ///
- /// @brief MAGFLUX NEXTGEN - MJKNXTGN == 0x4D4A4B4E5854474E, const with JTAG, big end? little end ? TBD.
- ///
- internal static readonly Device_value Met_U64DeviceFamily = new Device_value("Met_U64DeviceFamily", 1, ValueDataType.U64, ValueRW_Type.ReadWrite, "MAGFLUX NEXTGEN - MJKNXTGN == 0x4D4A4B4E5854474E, const with JTAG, big end? little end ? TBD.");
-
- ///
- /// @brief Type version / model detail - A0 in hex 0x41300000 for Alpha, big end? little end ? const with JTAG, TBD
- ///
- internal static readonly Device_value Met_U32DeviceTypeDetail = new Device_value("Met_U32DeviceTypeDetail", 5, ValueDataType.U32, ValueRW_Type.ReadWrite, "Type version / model detail - A0 in hex 0x41300000 for Alpha, big end? little end ? const with JTAG, TBD");
-
- ///
- /// @brief Programmed during production. Const after production. Days since ...01.01.2020.
- ///
- internal static readonly Device_value Met_U32ProdDate = new Device_value("Met_U32ProdDate", 7, ValueDataType.U32, ValueRW_Type.ReadWrite, "Programmed during production. Const after production. Days since ...01.01.2020.");
-
- ///
- /// @brief Programmed during production of entire meter assembly. Const after production.
- ///
- internal static readonly Device_value Met_U32ProdSerialNo = new Device_value("Met_U32ProdSerialNo", 9, ValueDataType.U32, ValueRW_Type.ReadWrite, "Programmed during production of entire meter assembly. Const after production.");
-
- ///
- /// @brief Programmed during JTAG with firmware. Const after production.
- ///
- internal static readonly Device_value Met_U32FirmwareVersion = new Device_value("Met_U32FirmwareVersion", 11, ValueDataType.U32, ValueRW_Type.ReadWrite, "Programmed during JTAG with firmware. Const after production.");
-
- ///
- /// @brief Programmed during JTAG with firmware. Const after production.
- ///
- internal static readonly Device_value Met_U32FmwrBuildDate = new Device_value("Met_U32FmwrBuildDate", 13, ValueDataType.U32, ValueRW_Type.ReadWrite, "Programmed during JTAG with firmware. Const after production.");
-
- ///
- /// @brief Programmed during JTAG with firmware. Const after production.
- ///
- internal static readonly Device_value Met_U32FmwrGITHash = new Device_value("Met_U32FmwrGITHash", 15, ValueDataType.U32, ValueRW_Type.ReadWrite, "Programmed during JTAG with firmware. Const after production.");
-
- ///
- /// @brief Programmed during production ? or maybe programmed during JTAG with firmware. Const after production.
- ///
- internal static readonly Device_value Met_U32HdwrVersion = new Device_value("Met_U32HdwrVersion", 17, ValueDataType.U32, ValueRW_Type.ReadWrite, "Programmed during production ? or maybe programmed during JTAG with firmware. Const after production.");
-
- ///
- /// @brief Programmed during JTAG with firmware. Const after production.
- ///
- internal static readonly Device_value Met_U32MdbsRegsVer = new Device_value("Met_U32MdbsRegsVer", 19, ValueDataType.U32, ValueRW_Type.ReadWrite, "Programmed during JTAG with firmware. Const after production.");
-
- ///
- /// @brief Tells you what calibration method was used. 0 is default, for calibration on flow rig for 5 min per point
- ///
- internal static readonly Device_value Met_U16CalibrationVersion = new Device_value("Met_U16CalibrationVersion", 21, ValueDataType.U16, ValueRW_Type.ReadWrite, "Tells you what calibration method was used. 0 is default, for calibration on flow rig for 5 min per point");
-
-
-/*------------------------------ block number 1 ------------------------------*/
-
- ///
- /// @brief CAUSES RESTART! 10s - Coil driver frequency configuration, 0 = 1.25Hz, 1 = 2.5Hz, 2 = 5Hz, 3 = 10Hz,
- ///
- internal static readonly Device_value Met_U16CoilDriverFrequencyConfig = new Device_value("Met_U16CoilDriverFrequencyConfig", 25, ValueDataType.U16, ValueRW_Type.ReadWrite, "CAUSES RESTART! 10s - Coil driver frequency configuration, 0 = 1.25Hz, 1 = 2.5Hz, 2 = 5Hz, 3 = 10Hz,");
-
- ///
- /// @brief CAUSES RESTART! 10s - Pipe Diameter configuration, 50 for DN50, 100 for DN100 etc.
- ///
- internal static readonly Device_value Met_U16PipeDiameterConfig_mm = new Device_value("Met_U16PipeDiameterConfig_mm", 26, ValueDataType.U16, ValueRW_Type.ReadWrite, "CAUSES RESTART! 10s - Pipe Diameter configuration, 50 for DN50, 100 for DN100 etc.");
-
- ///
- /// @brief Programmed during connection to metrology. Const after production. See label on sensor
- ///
- internal static readonly Device_value Met_U32SensorSerialNo = new Device_value("Met_U32SensorSerialNo", 27, ValueDataType.U32, ValueRW_Type.ReadWrite, "Programmed during connection to metrology. Const after production. See label on sensor");
-
-
-/*------------------------------ block number 2 ------------------------------*/
-
- ///
- /// @brief Const pulled from inside Met CPU
- ///
- internal static readonly Device_value Met_U128_CPU_ID = new Device_value("Met_U128_CPU_ID", 80, ValueDataType.U128, ValueRW_Type.ReadWrite, "Const pulled from inside Met CPU");
-
-
-/*------------------------------ block number 3 ------------------------------*/
-
- ///
- /// @brief Signature is only calculated when the Modbus reads the signature and it ALWAYS covers the Volume information block. If you don't know the hash seed then you won't be able to check the signature. :-) Still TBD.
- ///
- internal static readonly Device_value Met_U128Signature = new Device_value("Met_U128Signature", 100, ValueDataType.U128, ValueRW_Type.ReadWrite, "Signature is only calculated when the Modbus reads the signature and it ALWAYS covers the Volume information block. If you don't know the hash seed then you won't be able to check the signature. :-) Still TBD.");
-
- ///
- /// @brief Status and other registers up to the age are covered by the signature
- ///
- internal static readonly Device_value Met_U32Status = new Device_value("Met_U32Status", 108, ValueDataType.U32, ValueRW_Type.ReadWrite, "Status and other registers up to the age are covered by the signature");
-
- ///
- /// @brief Errors come and go. Flags for them are here.
- ///
- internal static readonly Device_value Met_U32Errors = new Device_value("Met_U32Errors", 110, ValueDataType.U32, ValueRW_Type.ReadWrite, "Errors come and go. Flags for them are here.");
-
- ///
- /// @brief We set alarms from the slave when errors happen, only the master can clear them.
- ///
- internal static readonly Device_value Met_U32Alarms = new Device_value("Met_U32Alarms", 112, ValueDataType.U32, ValueRW_Type.ReadWrite, "We set alarms from the slave when errors happen, only the master can clear them.");
-
- ///
- /// @brief Volume register names should speak for themselves.
- ///
- internal static readonly Device_value Met_U64ForwardNormalVolume_l = new Device_value("Met_U64ForwardNormalVolume_l", 114, ValueDataType.U64, ValueRW_Type.ReadWrite, "Volume register names should speak for themselves.");
-
- ///
- /// @brief Volume of water measured goingbackwards!
- ///
- internal static readonly Device_value Met_U64ReverseVolume_l = new Device_value("Met_U64ReverseVolume_l", 118, ValueDataType.U64, ValueRW_Type.ReadWrite, "Volume of water measured goingbackwards!");
-
- ///
- /// @brief Volume of water measured going faster than we can measure accurately
- ///
- internal static readonly Device_value Met_U64ForwardTooFastVolume_l = new Device_value("Met_U64ForwardTooFastVolume_l", 122, ValueDataType.U64, ValueRW_Type.ReadWrite, "Volume of water measured going faster than we can measure accurately");
-
- ///
- /// @brief Speed of flow in m/s, calibrated, floating point number so units are easy.
- ///
- internal static readonly Device_value Met_F32FlowSpeed_mps = new Device_value("Met_F32FlowSpeed_mps", 126, ValueDataType.F32, ValueRW_Type.ReadWrite, "Speed of flow in m/s, calibrated, floating point number so units are easy.");
-
- ///
- /// @brief Forward +1, Reverse -1
- ///
- internal static readonly Device_value Met_S16FlowDirection = new Device_value("Met_S16FlowDirection", 128, ValueDataType.S16, ValueRW_Type.ReadWrite, "Forward +1, Reverse -1");
-
- ///
- /// @brief Rate of flow in L/s, calibrated
- ///
- internal static readonly Device_value Met_F32FlowRate_lps = new Device_value("Met_F32FlowRate_lps", 129, ValueDataType.F32, ValueRW_Type.ReadWrite, "Rate of flow in L/s, calibrated");
-
- ///
- /// @brief Updated with the second tick, maybe a little less often if we are in low power mode. Atomic with the signature, total updates etc.
- ///
- internal static readonly Device_value Met_U16AgeTotals_s = new Device_value("Met_U16AgeTotals_s", 131, ValueDataType.U16, ValueRW_Type.ReadWrite, "Updated with the second tick, maybe a little less often if we are in low power mode. Atomic with the signature, total updates etc.");
-
-
-/*------------------------------ block number 4 ------------------------------*/
-
- ///
- /// @brief Logged in as secure = 1. Not logged in as secure 0
- ///
- internal static readonly Device_value Met_U16SecurityLoginStatus = new Device_value("Met_U16SecurityLoginStatus", 300, ValueDataType.U16, ValueRW_Type.ReadWrite, "Logged in as secure = 1. Not logged in as secure 0");
-
- ///
- /// @brief Security Login will timeout... when we get to 0... Updated with the second tick
- ///
- internal static readonly Device_value Met_U16SecurityLoginTimeleft_s = new Device_value("Met_U16SecurityLoginTimeleft_s", 301, ValueDataType.U16, ValueRW_Type.ReadWrite, "Security Login will timeout... when we get to 0... Updated with the second tick");
-
- ///
- /// @brief Part of the security login games etc. TBD.
- ///
- internal static readonly Device_value Met_U32SecurityLoginChallenge = new Device_value("Met_U32SecurityLoginChallenge", 302, ValueDataType.U32, ValueRW_Type.ReadWrite, " Part of the security login games etc. TBD.");
-
- ///
- /// @brief This will change - but we play a game here just to start a conversation, enter code, read challenge, enter reply to code... all good... or bad...
- ///
- internal static readonly Device_value Met_U32SecurityLoginCode = new Device_value("Met_U32SecurityLoginCode", 304, ValueDataType.U32, ValueRW_Type.ReadWrite, "This will change - but we play a game here just to start a conversation, enter code, read challenge, enter reply to code... all good... or bad...");
-
-
-/*------------------------------ block number 5 ------------------------------*/
-
- ///
- /// @brief No one is allowed to change bootcount, but can be zero'd after JTAG ? TBD.
- ///
- internal static readonly Device_value Met_U16BootCount = new Device_value("Met_U16BootCount", 500, ValueDataType.U16, ValueRW_Type.ReadWrite, "No one is allowed to change bootcount, but can be zero'd after JTAG ? TBD.");
-
- ///
- /// @brief How long has the meter been running (inc. sleep time).
- ///
- internal static readonly Device_value Met_U32LifeTime_min = new Device_value("Met_U32LifeTime_min", 501, ValueDataType.U32, ValueRW_Type.ReadWrite, "How long has the meter been running (inc. sleep time).");
-
- ///
- /// @brief Allows us to watch the clock, since last power on
- ///
- internal static readonly Device_value Met_U64TimeUpTicks = new Device_value("Met_U64TimeUpTicks", 503, ValueDataType.U64, ValueRW_Type.ReadWrite, "Allows us to watch the clock, since last power on");
-
- ///
- /// @brief Number of good packets recieved. This value can be zero'd by writing anything to it.
- ///
- internal static readonly Device_value Met_U32ComGoodPktCounter = new Device_value("Met_U32ComGoodPktCounter", 507, ValueDataType.U32, ValueRW_Type.ReadWrite, "Number of good packets recieved. This value can be zero'd by writing anything to it.");
-
- ///
- /// @brief Number of transmissions. This value can be zero'd by writing anything to it.
- ///
- internal static readonly Device_value Met_U32ComTxCounter = new Device_value("Met_U32ComTxCounter", 509, ValueDataType.U32, ValueRW_Type.ReadWrite, "Number of transmissions. This value can be zero'd by writing anything to it.");
-
- ///
- /// @brief Number of packets that have been dropped. This value can be zero'd by writing anything to it.
- ///
- internal static readonly Device_value Met_U32ComDroppedPktCounter = new Device_value("Met_U32ComDroppedPktCounter", 511, ValueDataType.U32, ValueRW_Type.ReadWrite, "Number of packets that have been dropped. This value can be zero'd by writing anything to it.");
-
- ///
- /// @brief Number of bad CRC's that have been recieved. This value can be zero'd by writing anything to it.
- ///
- internal static readonly Device_value Met_U32ComBadCRCCounter = new Device_value("Met_U32ComBadCRCCounter", 513, ValueDataType.U32, ValueRW_Type.ReadWrite, "Number of bad CRC's that have been recieved. This value can be zero'd by writing anything to it.");
-
- ///
- /// @brief Number of good bytes recieved. This sort of number is used to allow a measure of reliability to be calculated. This value can be zero'd by writing anything to it.
- ///
- internal static readonly Device_value Met_U32ComGoodByteCounter = new Device_value("Met_U32ComGoodByteCounter", 515, ValueDataType.U32, ValueRW_Type.ReadWrite, "Number of good bytes recieved. This sort of number is used to allow a measure of reliability to be calculated. This value can be zero'd by writing anything to it.");
-
- ///
- /// @brief Number of bad bytes recieved, meaning those from non valid packets. This value can be zero'd by writing anything to it.
- ///
- internal static readonly Device_value Met_U32ComBadByteCounter = new Device_value("Met_U32ComBadByteCounter", 517, ValueDataType.U32, ValueRW_Type.ReadWrite, "Number of bad bytes recieved, meaning those from non valid packets. This value can be zero'd by writing anything to it.");
-
-
-/*------------------------------ block number 6 ------------------------------*/
-
- ///
- /// @brief Register to set pulse-on time in ms, for pulse output 1. Write 0 will set digital output to fastest possible Ton_ms (0.5ms)
- ///
- internal static readonly Device_value Met_U16ComPktPulseOutput1_Ton_ms = new Device_value("Met_U16ComPktPulseOutput1_Ton_ms", 640, ValueDataType.U16, ValueRW_Type.ReadWrite, "Register to set pulse-on time in ms, for pulse output 1. Write 0 will set digital output to fastest possible Ton_ms (0.5ms)");
-
- ///
- /// @brief Register to get minimum value of pulse-on time in ms, for pulse output 1. The Ton_Min_ms is updated by FW at Init. True min is 0.5ms when Ton_ms = 0
- ///
- internal static readonly Device_value Met_U16ComPktPulseOutput1_Ton_min_ms = new Device_value("Met_U16ComPktPulseOutput1_Ton_min_ms", 641, ValueDataType.U16, ValueRW_Type.ReadWrite, "Register to get minimum value of pulse-on time in ms, for pulse output 1. The Ton_Min_ms is updated by FW at Init. True min is 0.5ms when Ton_ms = 0");
-
- ///
- /// @brief Register to get maximum value of pulse-on time in ms, for pulse output 1. The Ton_Max_ms is updated by FW at Init
- ///
- internal static readonly Device_value Met_U16ComPktPulseOutput1_Ton_max_ms = new Device_value("Met_U16ComPktPulseOutput1_Ton_max_ms", 642, ValueDataType.U16, ValueRW_Type.ReadWrite, "Register to get maximum value of pulse-on time in ms, for pulse output 1. The Ton_Max_ms is updated by FW at Init");
-
- ///
- /// @brief Register to set volume per pulse for pulse output 1.
- ///
- internal static readonly Device_value Met_U32VolumePerPulse_PulseOutput1_mL = new Device_value("Met_U32VolumePerPulse_PulseOutput1_mL", 643, ValueDataType.U32, ValueRW_Type.ReadWrite, "Register to set volume per pulse for pulse output 1.");
-
- ///
- /// @brief Register to get the minimum value used by volume per pulse register for pulse output 1.
- ///
- internal static readonly Device_value Met_U32VolumePerPulse_PulseOutput1_min_mL = new Device_value("Met_U32VolumePerPulse_PulseOutput1_min_mL", 645, ValueDataType.U32, ValueRW_Type.ReadWrite, "Register to get the minimum value used by volume per pulse register for pulse output 1.");
-
- ///
- /// @brief Register to get the maximum value used by volume per pulse register for pulse output 1.
- ///
- internal static readonly Device_value Met_U32VolumePerPulse_PulseOutput1_max_mL = new Device_value("Met_U32VolumePerPulse_PulseOutput1_max_mL", 647, ValueDataType.U32, ValueRW_Type.ReadWrite, "Register to get the maximum value used by volume per pulse register for pulse output 1.");
-
- ///
- /// @brief Register to set pulse-on time in ms, for pulse output 2. Write 0 will set digital output to fastest possible Ton_ms (0.5ms)
- ///
- internal static readonly Device_value Met_U16ComPktPulseOutput2_Ton_ms = new Device_value("Met_U16ComPktPulseOutput2_Ton_ms", 649, ValueDataType.U16, ValueRW_Type.ReadWrite, "Register to set pulse-on time in ms, for pulse output 2. Write 0 will set digital output to fastest possible Ton_ms (0.5ms)");
-
- ///
- /// @brief Register to get minimum value of pulse-on time in ms, for pulse output 2. The Ton_Min_ms is updated by FW at Init. True min is 0.5ms when Ton_ms = 0
- ///
- internal static readonly Device_value Met_U16ComPktPulseOutput2_Ton_min_ms = new Device_value("Met_U16ComPktPulseOutput2_Ton_min_ms", 650, ValueDataType.U16, ValueRW_Type.ReadWrite, "Register to get minimum value of pulse-on time in ms, for pulse output 2. The Ton_Min_ms is updated by FW at Init. True min is 0.5ms when Ton_ms = 0");
-
- ///
- /// @brief Register to get maximum value of pulse-on time in ms, for pulse output 2. The Ton_Max_ms is updated by FW at Init.
- ///
- internal static readonly Device_value Met_U16ComPktPulseOutput2_Ton_max_ms = new Device_value("Met_U16ComPktPulseOutput2_Ton_max_ms", 651, ValueDataType.U16, ValueRW_Type.ReadWrite, "Register to get maximum value of pulse-on time in ms, for pulse output 2. The Ton_Max_ms is updated by FW at Init.");
-
- ///
- /// @brief Register to set volume per pulse for pulse output 2.
- ///
- internal static readonly Device_value Met_U32VolumePerPulse_PulseOutput2_mL = new Device_value("Met_U32VolumePerPulse_PulseOutput2_mL", 652, ValueDataType.U32, ValueRW_Type.ReadWrite, "Register to set volume per pulse for pulse output 2.");
-
- ///
- /// @brief Register to get the minimum value used by volume per pulse register for pulse output 2.
- ///
- internal static readonly Device_value Met_U32VolumePerPulse_PulseOutput2_min_mL = new Device_value("Met_U32VolumePerPulse_PulseOutput2_min_mL", 654, ValueDataType.U32, ValueRW_Type.ReadWrite, "Register to get the minimum value used by volume per pulse register for pulse output 2.");
-
- ///
- /// @brief Register to get the maximum value used by volume per pulse register for pulse output 2
- ///
- internal static readonly Device_value Met_U32VolumePerPulse_PulseOutput2_max_mL = new Device_value("Met_U32VolumePerPulse_PulseOutput2_max_mL", 656, ValueDataType.U32, ValueRW_Type.ReadWrite, "Register to get the maximum value used by volume per pulse register for pulse output 2");
-
-
-/*------------------------------ block number 7 ------------------------------*/
-
- ///
- /// @brief Write to this register to control ADC calibration
- ///
- internal static readonly Device_value Met_U16ExtAdc_CalibCtrl = new Device_value("Met_U16ExtAdc_CalibCtrl", 700, ValueDataType.U16, ValueRW_Type.ReadWrite, "Write to this register to control ADC calibration");
-
- ///
- /// @brief Read this register to understand ADC calibration states and errors etc.
- ///
- internal static readonly Device_value Met_U16ExtAdc_CalibStatus = new Device_value("Met_U16ExtAdc_CalibStatus", 701, ValueDataType.U16, ValueRW_Type.ReadWrite, "Read this register to understand ADC calibration states and errors etc.");
-
- ///
- /// @brief External ADC current measuring Electrode inputs, see CalibStatus
- ///
- internal static readonly Device_value Met_F32ExtADC_Electrode_mV = new Device_value("Met_F32ExtADC_Electrode_mV", 702, ValueDataType.F32, ValueRW_Type.ReadWrite, "External ADC current measuring Electrode inputs, see CalibStatus");
-
- ///
- /// @brief External ADC current measuring Coil inputs, see CalibStatus
- ///
- internal static readonly Device_value Met_F32ExtADC_Coil_mV = new Device_value("Met_F32ExtADC_Coil_mV", 704, ValueDataType.F32, ValueRW_Type.ReadWrite, "External ADC current measuring Coil inputs, see CalibStatus");
-
-
-/*------------------------------ block number 8 ------------------------------*/
-
- ///
- /// @brief External ADC calibration point0 measuring electrodes - known mV
- ///
- internal static readonly Device_value Met_F32ExtADC_Electrode_referencePt0_mV = new Device_value("Met_F32ExtADC_Electrode_referencePt0_mV", 740, ValueDataType.F32, ValueRW_Type.ReadWrite, "External ADC calibration point0 measuring electrodes - known mV");
-
- ///
- /// @brief External ADC calibration point0 measuring electrodes - read mV
- ///
- internal static readonly Device_value Met_F32ExtADC_Electrode_reportPt0_mV = new Device_value("Met_F32ExtADC_Electrode_reportPt0_mV", 742, ValueDataType.F32, ValueRW_Type.ReadWrite, "External ADC calibration point0 measuring electrodes - read mV");
-
-
-/*------------------------------ block number 9 ------------------------------*/
-
- ///
- /// @brief External ADC calibration point0 measuring coil - known mV
- ///
- internal static readonly Device_value Met_F32ExtADC_Coil_referencePt0_mV = new Device_value("Met_F32ExtADC_Coil_referencePt0_mV", 760, ValueDataType.F32, ValueRW_Type.ReadWrite, "External ADC calibration point0 measuring coil - known mV");
-
- ///
- /// @brief External ADC calibration point0 measuring coil - read mV
- ///
- internal static readonly Device_value Met_F32ExtADC_Coil_reportPt0_mV = new Device_value("Met_F32ExtADC_Coil_reportPt0_mV", 762, ValueDataType.F32, ValueRW_Type.ReadWrite, "External ADC calibration point0 measuring coil - read mV");
-
-
-/*------------------------------ block number 10 ------------------------------*/
-
- ///
- /// @brief Write to this register to control Flow calibration
- ///
- internal static readonly Device_value Met_U16Flow_CalibCtrl = new Device_value("Met_U16Flow_CalibCtrl", 800, ValueDataType.U16, ValueRW_Type.ReadWrite, "Write to this register to control Flow calibration");
-
- ///
- /// @brief Read this register to understand Flow calibration states and errors etc.
- ///
- internal static readonly Device_value Met_U16Flow_CalibStatus = new Device_value("Met_U16Flow_CalibStatus", 801, ValueDataType.U16, ValueRW_Type.ReadWrite, "Read this register to understand Flow calibration states and errors etc.");
-
- ///
- /// @brief Raw flow speed in m/s, before calibration
- ///
- internal static readonly Device_value Met_F32Flow_RawSpeed_mps = new Device_value("Met_F32Flow_RawSpeed_mps", 802, ValueDataType.F32, ValueRW_Type.ReadWrite, "Raw flow speed in m/s, before calibration");
-
- ///
- /// @brief Raw flow rate in L/s, before calibration
- ///
- internal static readonly Device_value Met_F32Flow_RawRate_lps = new Device_value("Met_F32Flow_RawRate_lps", 804, ValueDataType.F32, ValueRW_Type.ReadWrite, "Raw flow rate in L/s, before calibration");
-
- ///
- /// @brief Flow point0, ZERO flow cal. From reference test harness, known L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReferencePt0_lps = new Device_value("Met_F32Flow_NewReferencePt0_lps", 806, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point0, ZERO flow cal. From reference test harness, known L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point0, ZERO flow cal. calculated from this meter, L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReportedPt0_lps = new Device_value("Met_F32Flow_NewReportedPt0_lps", 808, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point0, ZERO flow cal. calculated from this meter, L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point1, from reference test harness, known L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReferencePt1_lps = new Device_value("Met_F32Flow_NewReferencePt1_lps", 810, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point1, from reference test harness, known L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point1, calculated from this meter, L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReportedPt1_lps = new Device_value("Met_F32Flow_NewReportedPt1_lps", 812, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point1, calculated from this meter, L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point2, from reference test harness, known L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReferencePt2_lps = new Device_value("Met_F32Flow_NewReferencePt2_lps", 814, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point2, from reference test harness, known L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point2, calculated from this meter, L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReportedPt2_lps = new Device_value("Met_F32Flow_NewReportedPt2_lps", 816, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point2, calculated from this meter, L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point3, from reference test harness, known L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReferencePt3_lps = new Device_value("Met_F32Flow_NewReferencePt3_lps", 818, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point3, from reference test harness, known L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point3, calculated from this meter, L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReportedPt3_lps = new Device_value("Met_F32Flow_NewReportedPt3_lps", 820, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point3, calculated from this meter, L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point4, from reference test harness, known L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReferencePt4_lps = new Device_value("Met_F32Flow_NewReferencePt4_lps", 822, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point4, from reference test harness, known L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point4, calculated from this meter, L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReportedPt4_lps = new Device_value("Met_F32Flow_NewReportedPt4_lps", 824, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point4, calculated from this meter, L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point5, from reference test harness, known L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReferencePt5_lps = new Device_value("Met_F32Flow_NewReferencePt5_lps", 826, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point5, from reference test harness, known L/s - Cannot read present cal point!");
-
- ///
- /// @brief Flow point5, calculated from this meter, L/s - Cannot read present cal point!
- ///
- internal static readonly Device_value Met_F32Flow_NewReportedPt5_lps = new Device_value("Met_F32Flow_NewReportedPt5_lps", 828, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow point5, calculated from this meter, L/s - Cannot read present cal point!");
-
-
-/*------------------------------ block number 11 ------------------------------*/
-
- ///
- /// @brief Number of current points used for calibration. Set by FW at init and at a successful calibration
- ///
- internal static readonly Device_value Met_U16PresentPointsCount = new Device_value("Met_U16PresentPointsCount", 849, ValueDataType.U16, ValueRW_Type.ReadWrite, "Number of current points used for calibration. Set by FW at init and at a successful calibration");
-
- ///
- /// @brief ZERO flow cal. Current boundary position between Zero flow and 1st region, post-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint0_reference_lps = new Device_value("Met_F32FlowPresentPoint0_reference_lps", 850, ValueDataType.F32, ValueRW_Type.ReadWrite, "ZERO flow cal. Current boundary position between Zero flow and 1st region, post-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief ZERO flow cal. Current boundary position between Zero flow and 1st region, pre-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint0_reported_lps = new Device_value("Met_F32FlowPresentPoint0_reported_lps", 852, ValueDataType.F32, ValueRW_Type.ReadWrite, "ZERO flow cal. Current boundary position between Zero flow and 1st region, pre-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 1 and 2, post-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint1_reference_lps = new Device_value("Met_F32FlowPresentPoint1_reference_lps", 854, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 1 and 2, post-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 1 and 2, pre-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint1_reported_lps = new Device_value("Met_F32FlowPresentPoint1_reported_lps", 856, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 1 and 2, pre-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 2 and 3, post-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint2_reference_lps = new Device_value("Met_F32FlowPresentPoint2_reference_lps", 858, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 2 and 3, post-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 2 and 3, pre-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint2_reported_lps = new Device_value("Met_F32FlowPresentPoint2_reported_lps", 860, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 2 and 3, pre-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 3 and 4, post-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint3_reference_lps = new Device_value("Met_F32FlowPresentPoint3_reference_lps", 862, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 3 and 4, post-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 3 and 4, pre-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint3_reported_lps = new Device_value("Met_F32FlowPresentPoint3_reported_lps", 864, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 3 and 4, pre-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 4 and 5, post-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint4_reference_lps = new Device_value("Met_F32FlowPresentPoint4_reference_lps", 866, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 4 and 5, post-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 4 and 5, pre-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint4_reported_lps = new Device_value("Met_F32FlowPresentPoint4_reported_lps", 868, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 4 and 5, pre-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 5 and above, post-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint5_reference_lps = new Device_value("Met_F32FlowPresentPoint5_reference_lps", 870, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 5 and above, post-calibration, L/s. - Only saved after a successful calibration");
-
- ///
- /// @brief Current boundary position between region 5 and above, pre-calibration, L/s. - Only saved after a successful calibration
- ///
- internal static readonly Device_value Met_F32FlowPresentPoint5_reported_lps = new Device_value("Met_F32FlowPresentPoint5_reported_lps", 872, ValueDataType.F32, ValueRW_Type.ReadWrite, "Current boundary position between region 5 and above, pre-calibration, L/s. - Only saved after a successful calibration");
-
-
-/*------------------------------ block number 12 ------------------------------*/
-
- ///
- /// @brief Flow calibration gradient m in region 0. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion0_gradient_m = new Device_value("Met_F32FlowRegion0_gradient_m", 880, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration gradient m in region 0. y = mx+c");
-
- ///
- /// @brief Flow calibration offset c in region 0. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion0_offset_c = new Device_value("Met_F32FlowRegion0_offset_c", 882, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration offset c in region 0. y = mx+c");
-
- ///
- /// @brief Flow calibration gradient m in region 1. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion1_gradient_m = new Device_value("Met_F32FlowRegion1_gradient_m", 884, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration gradient m in region 1. y = mx+c");
-
- ///
- /// @brief Flow calibration offset c in region 1. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion1_offset_c = new Device_value("Met_F32FlowRegion1_offset_c", 886, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration offset c in region 1. y = mx+c");
-
- ///
- /// @brief Flow calibration gradient m in region 2. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion2_gradient_m = new Device_value("Met_F32FlowRegion2_gradient_m", 888, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration gradient m in region 2. y = mx+c");
-
- ///
- /// @brief Flow calibration offset c in region 2.
- ///
- internal static readonly Device_value Met_F32FlowRegion2_offset_c = new Device_value("Met_F32FlowRegion2_offset_c", 890, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration offset c in region 2.");
-
- ///
- /// @brief Flow calibration gradient m in region 3. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion3_gradient_m = new Device_value("Met_F32FlowRegion3_gradient_m", 892, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration gradient m in region 3. y = mx+c");
-
- ///
- /// @brief Flow calibration offset c in region 3.
- ///
- internal static readonly Device_value Met_F32FlowRegion3_offset_c = new Device_value("Met_F32FlowRegion3_offset_c", 894, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration offset c in region 3.");
-
- ///
- /// @brief Flow calibration gradient m in region 4. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion4_gradient_m = new Device_value("Met_F32FlowRegion4_gradient_m", 896, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration gradient m in region 4. y = mx+c");
-
- ///
- /// @brief Flow calibration offset c in region 4.
- ///
- internal static readonly Device_value Met_F32FlowRegion4_offset_c = new Device_value("Met_F32FlowRegion4_offset_c", 898, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration offset c in region 4.");
-
- ///
- /// @brief Flow calibration gradient m in region 5. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion5_gradient_m = new Device_value("Met_F32FlowRegion5_gradient_m", 900, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration gradient m in region 5. y = mx+c");
-
- ///
- /// @brief Flow calibration offset c in region 5.
- ///
- internal static readonly Device_value Met_F32FlowRegion5_offset_c = new Device_value("Met_F32FlowRegion5_offset_c", 902, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration offset c in region 5.");
-
- ///
- /// @brief Flow calibration gradient m in region 6. y = mx+c
- ///
- internal static readonly Device_value Met_F32FlowRegion6_gradient_m = new Device_value("Met_F32FlowRegion6_gradient_m", 904, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration gradient m in region 6. y = mx+c");
-
- ///
- /// @brief Flow calibration offset c in region 6.
- ///
- internal static readonly Device_value Met_F32FlowRegion6_offset_c = new Device_value("Met_F32FlowRegion6_offset_c", 906, ValueDataType.F32, ValueRW_Type.ReadWrite, "Flow calibration offset c in region 6.");
-
-
-/*------------------------------ block number 13 ------------------------------*/
-
- ///
- /// @brief CAUSES RESTART! 10s - You need to be logged to force this... also incs boot count.
- ///
- internal static readonly Device_value Met_U16ForceResetOfFirmware = new Device_value("Met_U16ForceResetOfFirmware", 1000, ValueDataType.U16, ValueRW_Type.ReadWrite, "CAUSES RESTART! 10s - You need to be logged to force this... also incs boot count.");
-
-
-/*------------------------------ block number 14 ------------------------------*/
-
- ///
- /// @brief You need to be able to login to force this... See also status register. Setting the flags on means that mock values are used. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.
- ///
- internal static readonly Device_value Met_U32MockFlags = new Device_value("Met_U32MockFlags", 1100, ValueDataType.U32, ValueRW_Type.ReadWrite, "You need to be able to login to force this... See also status register. Setting the flags on means that mock values are used. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.");
-
- ///
- /// @brief Mock water pressure value. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.
- ///
- internal static readonly Device_value Met_F32MockFEPressure_MPa = new Device_value("Met_F32MockFEPressure_MPa", 1102, ValueDataType.F32, ValueRW_Type.ReadWrite, "Mock water pressure value. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.");
-
- ///
- /// @brief Mock temperature, degrees C. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.
- ///
- internal static readonly Device_value Met_F32MockFETemperature_C = new Device_value("Met_F32MockFETemperature_C", 1104, ValueDataType.F32, ValueRW_Type.ReadWrite, "Mock temperature, degrees C. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.");
-
- ///
- /// @brief Mock speed of flow. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.
- ///
- internal static readonly Device_value Met_F32MockFlowSpeed_mps = new Device_value("Met_F32MockFlowSpeed_mps", 1106, ValueDataType.F32, ValueRW_Type.ReadWrite, "Mock speed of flow. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.");
-
- ///
- /// @brief Mock flow rate for testing calibration.
- ///
- internal static readonly Device_value Met_S64MockFlowRate_ulps = new Device_value("Met_S64MockFlowRate_ulps", 1108, ValueDataType.S64, ValueRW_Type.ReadWrite, "Mock flow rate for testing calibration.");
-
- ///
- /// @brief Mock value for direction of flow. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.
- ///
- internal static readonly Device_value Met_S16MockFlowDirection = new Device_value("Met_S16MockFlowDirection", 1112, ValueDataType.S16, ValueRW_Type.ReadWrite, "Mock value for direction of flow. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.");
-
- ///
- /// @brief Mock time between current sample and previous one. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.
- ///
- internal static readonly Device_value Met_F32MockTimeSampleInterval_s = new Device_value("Met_F32MockTimeSampleInterval_s", 1113, ValueDataType.F32, ValueRW_Type.ReadWrite, "Mock time between current sample and previous one. Mock registers are implemented to support test an error flag in the status register will indicate mock registers in use.");
-
- ///
- /// @brief Scratch register - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_U16Scratch0 = new Device_value("Met_U16Scratch0", 1115, ValueDataType.U16, ValueRW_Type.ReadWrite, "Scratch register - just somewhere to play write and read.");
-
-
-/*------------------------------ block number 15 ------------------------------*/
-
- ///
- /// @brief Scratch register - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_S16Scratch_S16 = new Device_value("Met_S16Scratch_S16", 1118, ValueDataType.S16, ValueRW_Type.ReadWrite, "Scratch register - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_U32Scratch_U32 = new Device_value("Met_U32Scratch_U32", 1119, ValueDataType.U32, ValueRW_Type.ReadWrite, "Scratch register - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_S32Scratch_S32 = new Device_value("Met_S32Scratch_S32", 1121, ValueDataType.S32, ValueRW_Type.ReadWrite, "Scratch register - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_U64Scratch_U64 = new Device_value("Met_U64Scratch_U64", 1123, ValueDataType.U64, ValueRW_Type.ReadWrite, "Scratch register - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_S64Scratch_S64 = new Device_value("Met_S64Scratch_S64", 1127, ValueDataType.S64, ValueRW_Type.ReadWrite, "Scratch register - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_U128Scratch_U128 = new Device_value("Met_U128Scratch_U128", 1131, ValueDataType.U128, ValueRW_Type.ReadWrite, "Scratch register - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_F32Scratch_F32 = new Device_value("Met_F32Scratch_F32", 1139, ValueDataType.F32, ValueRW_Type.ReadWrite, "Scratch register - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register, min and max - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_F32Scratch_MinMax = new Device_value("Met_F32Scratch_MinMax", 1141, ValueDataType.F32, ValueRW_Type.ReadWrite, "Scratch register, min and max - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register, Enum - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_U16Scratch_Enum = new Device_value("Met_U16Scratch_Enum", 1143, ValueDataType.U16, ValueRW_Type.ReadWrite, "Scratch register, Enum - just somewhere to play write and read.");
-
- ///
- /// @brief Scratch register, const - just somewhere to play write and read.
- ///
- internal static readonly Device_value Met_U16Scratch_Const = new Device_value("Met_U16Scratch_Const", 1144, ValueDataType.U16, ValueRW_Type.ReadWrite, "Scratch register, const - just somewhere to play write and read.");
-
-
-/*------------------------------ block number 16 ------------------------------*/
-
- ///
- /// @brief Int. ADC value: batt_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_battADC_V = new Device_value("Met_F32IntADCSample_battADC_V", 3200, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: batt_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_U32IntADCSample_battADC_tick = new Device_value("Met_U32IntADCSample_battADC_tick", 3202, ValueDataType.U32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: diag_p_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagP_adc_V = new Device_value("Met_F32IntADCSample_diagP_adc_V", 3204, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: diag_p_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_U32IntADCSample_diagP_adc_tick = new Device_value("Met_U32IntADCSample_diagP_adc_tick", 3206, ValueDataType.U32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: diag_n_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagN_adc_V = new Device_value("Met_F32IntADCSample_diagN_adc_V", 3208, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: diag_n_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_U32IntADCSample_diagN_adc_tick = new Device_value("Met_U32IntADCSample_diagN_adc_tick", 3210, ValueDataType.U32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: diag_c_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagC_adc_V = new Device_value("Met_F32IntADCSample_diagC_adc_V", 3212, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: diag_c_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_U32IntADCSample_diagC_adc_tick = new Device_value("Met_U32IntADCSample_diagC_adc_tick", 3214, ValueDataType.U32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: vref_common_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_vrefCommonADC_V = new Device_value("Met_F32IntADCSample_vrefCommonADC_V", 3216, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: vref_common_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_U32IntADCSample_vrefCommonADC_tick = new Device_value("Met_U32IntADCSample_vrefCommonADC_tick", 3218, ValueDataType.U32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: vref_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_vrefADC_V = new Device_value("Met_F32IntADCSample_vrefADC_V", 3220, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: vref_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_U32IntADCSample_vrefADC_tick = new Device_value("Met_U32IntADCSample_vrefADC_tick", 3222, ValueDataType.U32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: temperature_Cdiv10_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_temperature_C = new Device_value("Met_F32IntADCSample_temperature_C", 3224, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: temperature_Cdiv10_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_U32IntADCSample_temperature_C_tick = new Device_value("Met_U32IntADCSample_temperature_C_tick", 3226, ValueDataType.U32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: int_batt_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_intBattADC_V = new Device_value("Met_F32IntADCSample_intBattADC_V", 3228, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: int_batt_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_U32IntADCSample_intBattADC_tick = new Device_value("Met_U32IntADCSample_intBattADC_tick", 3230, ValueDataType.U32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
-
-/*------------------------------ block number 17 ------------------------------*/
-
- ///
- /// @brief Extern ADC, Electrode diff as Voltage
- ///
- internal static readonly Device_value Met_F32ExtADC_ElectrodeDiff_V = new Device_value("Met_F32ExtADC_ElectrodeDiff_V", 3250, ValueDataType.F32, ValueRW_Type.ReadWrite, "Extern ADC, Electrode diff as Voltage");
-
- ///
- /// @brief Tick count, for Extern ADC, Electrode diff
- ///
- internal static readonly Device_value Met_S32ExtADC_ElectrodeDiff_tics = new Device_value("Met_S32ExtADC_ElectrodeDiff_tics", 3252, ValueDataType.S32, ValueRW_Type.ReadWrite, "Tick count, for Extern ADC, Electrode diff");
-
- ///
- /// @brief Extern ADC, Coil diff as Current
- ///
- internal static readonly Device_value Met_F32ExtADC_CoilDiff_A = new Device_value("Met_F32ExtADC_CoilDiff_A", 3254, ValueDataType.F32, ValueRW_Type.ReadWrite, "Extern ADC, Coil diff as Current");
-
- ///
- /// @brief Tick count, for Extern ADC, Coil diff
- ///
- internal static readonly Device_value Met_S32ExtADC_CoilDiff_tics = new Device_value("Met_S32ExtADC_CoilDiff_tics", 3256, ValueDataType.S32, ValueRW_Type.ReadWrite, "Tick count, for Extern ADC, Coil diff");
-
-
-/*------------------------------ block number 18 ------------------------------*/
-
- ///
- /// @brief Int. ADC value: batt_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_battADC_offset = new Device_value("Met_F32IntADCSample_battADC_offset", 3300, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: batt_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_F32IntADCSample_battADC_scale = new Device_value("Met_F32IntADCSample_battADC_scale", 3302, ValueDataType.F32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: diag_p_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagP_adc_offset = new Device_value("Met_F32IntADCSample_diagP_adc_offset", 3304, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: diag_p_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagP_adc_scale = new Device_value("Met_F32IntADCSample_diagP_adc_scale", 3306, ValueDataType.F32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: diag_n_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagN_adc_offset = new Device_value("Met_F32IntADCSample_diagN_adc_offset", 3308, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: diag_n_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagN_adc_scale = new Device_value("Met_F32IntADCSample_diagN_adc_scale", 3310, ValueDataType.F32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: diag_c_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagC_adc_offset = new Device_value("Met_F32IntADCSample_diagC_adc_offset", 3312, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: diag_c_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_F32IntADCSample_diagC_adc_scale = new Device_value("Met_F32IntADCSample_diagC_adc_scale", 3314, ValueDataType.F32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: vref_common_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_vrefCommonADC_offset = new Device_value("Met_F32IntADCSample_vrefCommonADC_offset", 3316, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: vref_common_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_F32IntADCSample_vrefCommonADC_scale = new Device_value("Met_F32IntADCSample_vrefCommonADC_scale", 3318, ValueDataType.F32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: vref_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_vrefADC_offset = new Device_value("Met_F32IntADCSample_vrefADC_offset", 3320, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: vref_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_F32IntADCSample_vrefADC_scale = new Device_value("Met_F32IntADCSample_vrefADC_scale", 3322, ValueDataType.F32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: temperature_Cdiv10_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_temperature_offset = new Device_value("Met_F32IntADCSample_temperature_offset", 3324, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: temperature_Cdiv10_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_F32IntADCSample_temperature_C_scale = new Device_value("Met_F32IntADCSample_temperature_C_scale", 3326, ValueDataType.F32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
- ///
- /// @brief Int. ADC value: int_batt_adc as Voltage
- ///
- internal static readonly Device_value Met_F32IntADCSample_intBattADC_offset = new Device_value("Met_F32IntADCSample_intBattADC_offset", 3328, ValueDataType.F32, ValueRW_Type.ReadWrite, "Int. ADC value: int_batt_adc as Voltage");
-
- ///
- /// @brief Tick count, for ADC data sample
- ///
- internal static readonly Device_value Met_F32IntADCSample_intBattADC_scale = new Device_value("Met_F32IntADCSample_intBattADC_scale", 3330, ValueDataType.F32, ValueRW_Type.ReadWrite, "Tick count, for ADC data sample");
-
-
-/*------------------------------ block number 19 ------------------------------*/
-
- ///
- /// @brief Extern ADC, Electrode diff offset
- ///
- internal static readonly Device_value Met_F32ExtADC_ElectrodeDiff_offset = new Device_value("Met_F32ExtADC_ElectrodeDiff_offset", 3350, ValueDataType.F32, ValueRW_Type.ReadWrite, "Extern ADC, Electrode diff offset");
-
- ///
- /// @brief Extern ADC, Electrode diff scale, ref/adc bits, 2.5/2^23
- ///
- internal static readonly Device_value Met_F32ExtADC_ElectrodeDiff_scale = new Device_value("Met_F32ExtADC_ElectrodeDiff_scale", 3352, ValueDataType.F32, ValueRW_Type.ReadWrite, "Extern ADC, Electrode diff scale, ref/adc bits, 2.5/2^23");
-
- ///
- /// @brief Extern ADC, Coil diff offset as Voltage
- ///
- internal static readonly Device_value Met_F32ExtADC_CoilDiff_offset = new Device_value("Met_F32ExtADC_CoilDiff_offset", 3354, ValueDataType.F32, ValueRW_Type.ReadWrite, "Extern ADC, Coil diff offset as Voltage");
-
- ///
- /// @brief Extern ADC, Coil diff scale, ref/adc bits, 2.5/2^23
- ///
- internal static readonly Device_value Met_F32ExtADC_CoilDiff_scale = new Device_value("Met_F32ExtADC_CoilDiff_scale", 3356, ValueDataType.F32, ValueRW_Type.ReadWrite, "Extern ADC, Coil diff scale, ref/adc bits, 2.5/2^23");
-
-
-/*------------------------------ block number 20 ------------------------------*/
-
- ///
- /// @brief Updated with EEPROM operation.
- ///
- internal static readonly Device_value Met_U16EEPROM_Status = new Device_value("Met_U16EEPROM_Status", 6000, ValueDataType.U16, ValueRW_Type.ReadWrite, "Updated with EEPROM operation.");
-
- ///
- /// @brief Updated with EEPROM operation.
- ///
- internal static readonly Device_value Met_U16EEPROM_LastErrorCode = new Device_value("Met_U16EEPROM_LastErrorCode", 6001, ValueDataType.U16, ValueRW_Type.ReadWrite, "Updated with EEPROM operation.");
-
-
-/*------------------------------ block number 21 ------------------------------*/
-
- ///
- /// @brief Updated with 1_WIRE operation.
- ///
- internal static readonly Device_value Met_U16_OneWIRE_Status = new Device_value("Met_U16_OneWIRE_Status", 6100, ValueDataType.U16, ValueRW_Type.ReadWrite, "Updated with 1_WIRE operation.");
-
- ///
- /// @brief Updated with 1_WIRE operation.
- ///
- internal static readonly Device_value Met_U16_OneWIRE_Error = new Device_value("Met_U16_OneWIRE_Error", 6101, ValueDataType.U16, ValueRW_Type.ReadWrite, "Updated with 1_WIRE operation.");
-
- ///
- /// @brief Issue commands to control 1_WIRE operation
- ///
- internal static readonly Device_value Met_U16_OneWIRE_Ctrl = new Device_value("Met_U16_OneWIRE_Ctrl", 6102, ValueDataType.U16, ValueRW_Type.ReadWrite, "Issue commands to control 1_WIRE operation");
-
-
-/*------------------------------ block number 22 ------------------------------*/
-
- ///
- /// @brief Measured resistance between electrodes, in ohms, 0deg phase.
- ///
- internal static readonly Device_value Met_F32_Zi_ohms = new Device_value("Met_F32_Zi_ohms", 7000, ValueDataType.F32, ValueRW_Type.ReadWrite, "Measured resistance between electrodes, in ohms, 0deg phase.");
-
- ///
- /// @brief Measured resistance between electrodes, in ohms, 90deg phase.
- ///
- internal static readonly Device_value Met_F32_Zj_ohms = new Device_value("Met_F32_Zj_ohms", 7002, ValueDataType.F32, ValueRW_Type.ReadWrite, "Measured resistance between electrodes, in ohms, 90deg phase.");
-
- ///
- /// @brief Electrode resistance max, (mod = sqrt(Zi^2+Zj^2)), for full decision.
- ///
- internal static readonly Device_value Met_F32_FullLevelThreshold_ohms = new Device_value("Met_F32_FullLevelThreshold_ohms", 7004, ValueDataType.F32, ValueRW_Type.ReadWrite, "Electrode resistance max, (mod = sqrt(Zi^2+Zj^2)), for full decision.");
-
- ///
- /// @brief Electrode resistance min, (mod = sqrt(Zi^2+Zj^2)), for empty decision.
- ///
- internal static readonly Device_value Met_F32_EmptyLevelThreshold_ohms = new Device_value("Met_F32_EmptyLevelThreshold_ohms", 7006, ValueDataType.F32, ValueRW_Type.ReadWrite, "Electrode resistance min, (mod = sqrt(Zi^2+Zj^2)), for empty decision.");
-
- ///
- /// @brief Electrode resistance min, (arg = atan(Zq/Zi)), for empty decision.
- ///
- internal static readonly Device_value Met_S16_EmptyLevelThreshold_minPhs_degs = new Device_value("Met_S16_EmptyLevelThreshold_minPhs_degs", 7008, ValueDataType.S16, ValueRW_Type.ReadWrite, "Electrode resistance min, (arg = atan(Zq/Zi)), for empty decision.");
-
- ///
- /// @brief Electrode resistance min, (arg = atan(Zq/Zi)), for empty decision.
- ///
- internal static readonly Device_value Met_S16_EmptyLevelThreshold_maxPhs_degs = new Device_value("Met_S16_EmptyLevelThreshold_maxPhs_degs", 7009, ValueDataType.S16, ValueRW_Type.ReadWrite, "Electrode resistance min, (arg = atan(Zq/Zi)), for empty decision.");
-
- ///
- /// @brief Filter coef for EPD decision.
- ///
- internal static readonly Device_value Met_F32_ZiZj_FilterA = new Device_value("Met_F32_ZiZj_FilterA", 7010, ValueDataType.F32, ValueRW_Type.ReadWrite, "Filter coef for EPD decision.");
-
- ///
- /// @brief Filter coef for EPD decision.
- ///
- internal static readonly Device_value Met_F32_ZiZj_FilterB = new Device_value("Met_F32_ZiZj_FilterB", 7012, ValueDataType.F32, ValueRW_Type.ReadWrite, "Filter coef for EPD decision.");
-
-
-/*------------------------------ block number 23 ------------------------------*/
-
- ///
- /// @brief EPD state
- ///
- internal static readonly Device_value Met_U16EmptyPipeControl = new Device_value("Met_U16EmptyPipeControl", 7050, ValueDataType.U16, ValueRW_Type.ReadWrite, "EPD state");
-
- ///
- /// @brief EPD state
- ///
- internal static readonly Device_value Met_U16EmptyPipeStatus = new Device_value("Met_U16EmptyPipeStatus", 7051, ValueDataType.U16, ValueRW_Type.ReadWrite, "EPD state");
-
- ///
- /// @brief EPD flags, including decison
- ///
- internal static readonly Device_value Met_U16EmptyPipeFlags = new Device_value("Met_U16EmptyPipeFlags", 7052, ValueDataType.U16, ValueRW_Type.ReadWrite, "EPD flags, including decison");
-
-
-/*------------------------------ block number 24 ------------------------------*/
-
- ///
- /// @brief Low flow can be set on or off etc.
- ///
- internal static readonly Device_value Met_U16LowFlowControl = new Device_value("Met_U16LowFlowControl", 7100, ValueDataType.U16, ValueRW_Type.ReadWrite, "Low flow can be set on or off etc.");
-
- ///
- /// @brief How is it going? Low flow - or not.
- ///
- internal static readonly Device_value Met_U16LowFlowStatus = new Device_value("Met_U16LowFlowStatus", 7101, ValueDataType.U16, ValueRW_Type.ReadWrite, "How is it going? Low flow - or not.");
-
- ///
- /// @brief Can be reset by master. Does not wrap.
- ///
- internal static readonly Device_value Met_S32LowFlow_ResettableTotal_l = new Device_value("Met_S32LowFlow_ResettableTotal_l", 7102, ValueDataType.S32, ValueRW_Type.ReadWrite, "Can be reset by master. Does not wrap.");
-
- ///
- /// @brief micro-litres per second below which we let it go.
- ///
- internal static readonly Device_value Met_U32LowFlowVolThresh_ulps = new Device_value("Met_U32LowFlowVolThresh_ulps", 7104, ValueDataType.U32, ValueRW_Type.ReadWrite, "micro-litres per second below which we let it go.");
-
- ///
- /// @brief micro-litres per second below which we let it go.
- ///
- internal static readonly Device_value Met_U16LowFlowTimeThresh_s = new Device_value("Met_U16LowFlowTimeThresh_s", 7106, ValueDataType.U16, ValueRW_Type.ReadWrite, "micro-litres per second below which we let it go.");
-
-
-/*------------------------------ block number 25 ------------------------------*/
-
- ///
- /// @brief Rev flow can be set on or off etc.
- ///
- internal static readonly Device_value Met_U16RevFlowControl = new Device_value("Met_U16RevFlowControl", 7150, ValueDataType.U16, ValueRW_Type.ReadWrite, "Rev flow can be set on or off etc.");
-
- ///
- /// @brief How is it going? Rev flow - or not.
- ///
- internal static readonly Device_value Met_U16RevFlowStatus = new Device_value("Met_U16RevFlowStatus", 7151, ValueDataType.U16, ValueRW_Type.ReadWrite, "How is it going? Rev flow - or not.");
-
- ///
- /// @brief Can be reset by master. Does not wrap.
- ///
- internal static readonly Device_value Met_S32RevFlow_ResettableTotal_l = new Device_value("Met_S32RevFlow_ResettableTotal_l", 7152, ValueDataType.S32, ValueRW_Type.ReadWrite, "Can be reset by master. Does not wrap.");
-
- ///
- /// @brief micro-litres per second below which we let it go.
- ///
- internal static readonly Device_value Met_U32RevFlowVolThresh_ulps = new Device_value("Met_U32RevFlowVolThresh_ulps", 7154, ValueDataType.U32, ValueRW_Type.ReadWrite, "micro-litres per second below which we let it go.");
-
- ///
- /// @brief micro-litres per second below which we let it go.
- ///
- internal static readonly Device_value Met_U16RevFlowTimeThresh_s = new Device_value("Met_U16RevFlowTimeThresh_s", 7156, ValueDataType.U16, ValueRW_Type.ReadWrite, "micro-litres per second below which we let it go.");
-
-
-/*------------------------------ block number 26 ------------------------------*/
-
- ///
- /// @brief Rev flow can be set on or off etc.
- ///
- internal static readonly Device_value Met_U16ExcessFlowControl = new Device_value("Met_U16ExcessFlowControl", 7200, ValueDataType.U16, ValueRW_Type.ReadWrite, "Rev flow can be set on or off etc.");
-
- ///
- /// @brief How is it going? Rev flow - or not.
- ///
- internal static readonly Device_value Met_U16ExcessFlowStatus = new Device_value("Met_U16ExcessFlowStatus", 7201, ValueDataType.U16, ValueRW_Type.ReadWrite, "How is it going? Rev flow - or not.");
-
- ///
- /// @brief Can be reset by master. Does not wrap.
- ///
- internal static readonly Device_value Met_S32ExcessFlow_ResettableTotal_l = new Device_value("Met_S32ExcessFlow_ResettableTotal_l", 7202, ValueDataType.S32, ValueRW_Type.ReadWrite, "Can be reset by master. Does not wrap.");
-
- ///
- /// @brief micro-litres per second below which we let it go.
- ///
- internal static readonly Device_value Met_U32ExcessFlowVolThresh_ulps = new Device_value("Met_U32ExcessFlowVolThresh_ulps", 7204, ValueDataType.U32, ValueRW_Type.ReadWrite, "micro-litres per second below which we let it go.");
-
- ///
- /// @brief micro-litres per second below which we let it go.
- ///
- internal static readonly Device_value Met_U16ExcessFlowTimeThresh_s = new Device_value("Met_U16ExcessFlowTimeThresh_s", 7206, ValueDataType.U16, ValueRW_Type.ReadWrite, "micro-litres per second below which we let it go.");
-
-
-/*------------------------------ block number 27 ------------------------------*/
-
- ///
- /// @brief Only uneven number allowed Changes will dynamic change Met_U16_...OnOffAvr_Max and Met_U16_...OnOffAvr
- ///
- internal static readonly Device_value Met_U16_FlowMedian_NoTapsReq = new Device_value("Met_U16_FlowMedian_NoTapsReq", 7220, ValueDataType.U16, ValueRW_Type.ReadWrite, "Only uneven number allowed Changes will dynamic change Met_U16_...OnOffAvr_Max and Met_U16_...OnOffAvr");
-
- ///
- /// @brief Minimum value limit for Met_U16...NoTapsReq
- ///
- internal static readonly Device_value Met_U16_FlowMedian_NoTapsReq_Min = new Device_value("Met_U16_FlowMedian_NoTapsReq_Min", 7221, ValueDataType.U16, ValueRW_Type.ReadWrite, "Minimum value limit for Met_U16...NoTapsReq");
-
- ///
- /// @brief Maximum value limit for Met_U16...NoTapsReq
- ///
- internal static readonly Device_value Met_U16_FlowMedian_NoTapsReq_Max = new Device_value("Met_U16_FlowMedian_NoTapsReq_Max", 7222, ValueDataType.U16, ValueRW_Type.ReadWrite, "Maximum value limit for Met_U16...NoTapsReq");
-
- ///
- /// @brief 0:Passthrough, n: No. Central values. (default: 1) Will dynamic change, if Met_U16...OnOffAvr_Max changes to lower value.
- ///
- internal static readonly Device_value Met_U16_FlowMedian_OnOffAvr = new Device_value("Met_U16_FlowMedian_OnOffAvr", 7223, ValueDataType.U16, ValueRW_Type.ReadWrite, "0:Passthrough, n: No. Central values. (default: 1) Will dynamic change, if Met_U16...OnOffAvr_Max changes to lower value.");
-
- ///
- /// @brief Minimum value limit for Met_U16...OnOffAvr
- ///
- internal static readonly Device_value Met_U16_FlowMedian_OnOffAvr_Min = new Device_value("Met_U16_FlowMedian_OnOffAvr_Min", 7224, ValueDataType.U16, ValueRW_Type.ReadWrite, "Minimum value limit for Met_U16...OnOffAvr");
-
- ///
- /// @brief Maximum value limit for Met_U16...OnOffAvr Max is Dynamic changed and defined as (Met_U16...NoTapsReq - 2)
- ///
- internal static readonly Device_value Met_U16_FlowMedian_OnOffAvr_Max = new Device_value("Met_U16_FlowMedian_OnOffAvr_Max", 7225, ValueDataType.U16, ValueRW_Type.ReadWrite, "Maximum value limit for Met_U16...OnOffAvr Max is Dynamic changed and defined as (Met_U16...NoTapsReq - 2)");
-
- ///
- /// @brief 0:No options, 1:max-min based, 2:Running stdev based
- ///
- internal static readonly Device_value Met_U16_FlowMedian_Options = new Device_value("Met_U16_FlowMedian_Options", 7226, ValueDataType.U16, ValueRW_Type.ReadWrite, "0:No options, 1:max-min based, 2:Running stdev based");
-
- ///
- /// @brief Minimum limit allowed for Met_U16...Options
- ///
- internal static readonly Device_value Met_U16_FlowMedian_Options_Min = new Device_value("Met_U16_FlowMedian_Options_Min", 7227, ValueDataType.U16, ValueRW_Type.ReadWrite, "Minimum limit allowed for Met_U16...Options");
-
- ///
- /// @brief Maximum limit allowed for Met_U16...Options
- ///
- internal static readonly Device_value Met_U16_FlowMedian_Options_Max = new Device_value("Met_U16_FlowMedian_Options_Max", 7228, ValueDataType.U16, ValueRW_Type.ReadWrite, "Maximum limit allowed for Met_U16...Options");
-
- ///
- /// @brief Version of the median filter implementation
- ///
- internal static readonly Device_value Met_U16_FlowMedian_Version = new Device_value("Met_U16_FlowMedian_Version", 7229, ValueDataType.U16, ValueRW_Type.ReadWrite, "Version of the median filter implementation");
-
- ///
- /// @brief 0 is ok, 1 is interesting like starting up etc., 2 is interesting - like EPD blanking ... all TBD
- ///
- internal static readonly Device_value Met_U16_FlowMedian_Status = new Device_value("Met_U16_FlowMedian_Status", 7230, ValueDataType.U16, ValueRW_Type.ReadWrite, "0 is ok, 1 is interesting like starting up etc., 2 is interesting - like EPD blanking ... all TBD");
-
- ///
- /// @brief Time in seconds in the filter. Easily calculated from the current flip rate * number of taps, but may be useful.
- ///
- internal static readonly Device_value Met_F32_FlowMedian_TimeInFilter_s = new Device_value("Met_F32_FlowMedian_TimeInFilter_s", 7231, ValueDataType.F32, ValueRW_Type.ReadWrite, "Time in seconds in the filter. Easily calculated from the current flip rate * number of taps, but may be useful.");
-
- ///
- /// @brief Central Filter value
- ///
- internal static readonly Device_value Met_F32_FlowMedian_CentralValue = new Device_value("Met_F32_FlowMedian_CentralValue", 7233, ValueDataType.F32, ValueRW_Type.ReadWrite, "Central Filter value");
-
- ///
- /// @brief Maximum Filter value
- ///
- internal static readonly Device_value Met_F32_FlowMedian_MaxValue = new Device_value("Met_F32_FlowMedian_MaxValue", 7235, ValueDataType.F32, ValueRW_Type.ReadWrite, "Maximum Filter value");
-
- ///
- /// @brief Minimum Filter value
- ///
- internal static readonly Device_value Met_F32_FlowMedian_MinValue = new Device_value("Met_F32_FlowMedian_MinValue", 7237, ValueDataType.F32, ValueRW_Type.ReadWrite, "Minimum Filter value");
-
- ///
- /// @brief Usually something like ((max-min)/(0.001*Q3)) but may be something else TBD.
- ///
- internal static readonly Device_value Met_F32_FlowMedian_NoiseMeasure = new Device_value("Met_F32_FlowMedian_NoiseMeasure", 7239, ValueDataType.F32, ValueRW_Type.ReadWrite, "Usually something like ((max-min)/(0.001*Q3)) but may be something else TBD.");
-
- } // End of reg_list
- /*---------------------------------------------------------------------------*/
-} /* MagFlux6200_metrology_reg_list */
diff --git a/Common/modbus_master_csharp/Device/Met_6200v046.html b/Common/modbus_master_csharp/Device/Met_6200v046.html
deleted file mode 100644
index 517770f9..00000000
--- a/Common/modbus_master_csharp/Device/Met_6200v046.html
+++ /dev/null
@@ -1,1154 +0,0 @@
-
-
-
-
-
-
-
-
-
-
Met_6200v046 from Fri Oct 27 10:21:57 2023
-
-
-
-
-
-
-
-
-
diff --git a/Common/modbus_master_csharp/Device/ModbusDeviceCom.cs b/Common/modbus_master_csharp/Device/ModbusDeviceCom.cs
deleted file mode 100644
index 30729db6..00000000
--- a/Common/modbus_master_csharp/Device/ModbusDeviceCom.cs
+++ /dev/null
@@ -1,334 +0,0 @@
-using MagFlux6200_metrology_reg_list;
-using System.Collections.Generic;
-using System.Numerics;
-using System;
-using XYLEM.Communication;
-using System.IO.Ports;
-using XYLEM.Base.Files;
-using System.Threading.Tasks;
-using XYLEM.Base;
-
-namespace XYLEM.Device
-{
- public abstract class ModbusDeviceCom
- {
- protected ProgramLogCSVFileClass _logger = null;
-
- UInt16 _device_id = 1;
- ModbusCom _md_com = null;
-
-#if (!DEBUG)
- public Boolean DoComDebugPrint = false;
-#else
- //public Boolean DoComDebugPrint = true;
- public Boolean DoComDebugPrint = false;
-#if (DoComDebugPrint)
-#warning DoTxValuePrint is true!!!!!!!!!!!!!!!!
-#endif
- const int ch_lng_dv = -15;
- const int ch_lng_Version = -3;
- const int ch_lng_MD_adr = -7;
- const int dig_value = 10;
-#endif
- public ModbusDeviceCom()
- {
-
- }
-
- public Boolean SetLogLocation(string path, string filename)
- {
- try
- {
- // If already created a _logger then
- if (_logger != null)
- {
- // TODO: nothing to do right now
- throw new Exception("Logger path can only be set one time");
- }
- _logger = new ProgramLogCSVFileClass(path, filename);
- return true; // Okay
- }
- catch (Exception ex)
- {
- Console.WriteLine($"Fail to setup program log path!\nPath:{path}\nMessage:{ex.Message}");
- }
- return false; // failed
- }
-
-
- public void OpenLogFile()
- {
- // If already created a _logger then
- if (_logger != null)
- {
- _logger.OpenProgramLogFile();
- }
- }
-
-
- public string GetComCounters()
- {
- if (_md_com == null)
- {
- return "T=? E=?";
- }
- return $"T={_md_com.MsgCount} E={_md_com.MsgErrorCount}";
-
- }
-
-
- public Boolean IsConnected()
- {
- if (_md_com == null)
- {
- return false;
- }
- return _md_com.IsConnected();
- }
-
- public Boolean CloseConnection()
- {
- try
- {
- StopBackgroundChecking();
- if (_md_com != null)
- {
- /*There is nothing to close right now*/
- }
- return true; // is okay
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), "CloseConnection", "Fail to close connection", ex);
- }
- return false; // failed
- }
-
-
-
- public virtual Boolean Connect(string comport, int baudRate, Parity parity)
- {
- try
- {
- {// Normal
- if (IsConnected())
- {
- CloseConnection();
- }
- _md_com = new ModbusCom(comport, baudRate, parity);
- return _md_com.IsConnected(); // return result
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), "Connect", "Fail to open connection", ex);
- }
- return false; // failed
- }
-
- #region Background service
- System.Timers.Timer _BackgroundCheckingTimer = null;
-
- protected void StartBackgroundChecking()
- {
- StopBackgroundChecking(); // Make sure that a already running one is stopped
- _BackgroundCheckingTimer = new System.Timers.Timer(1000);
- _BackgroundCheckingTimer.Elapsed += (sender, e) => HandleBackgroundChecking();
- _BackgroundCheckingTimer.Start();
- }
-
- protected void StopBackgroundChecking()
- {
- if (_BackgroundCheckingTimer != null)
- {
- _BackgroundCheckingTimer.Stop();
- _BackgroundCheckingTimer.Close();
- _BackgroundCheckingTimer = null;
- }
- }
-
- ///
- /// Handle checking DUT and background reading device values
- ///
- ///
- private void HandleBackgroundChecking()
- {
- // Don't continue background service before the first has been serviced
- if (_BackgroundCheckingTimer != null)
- {
- _BackgroundCheckingTimer.Stop();
- }
- try
- {
- RunBackgroundReadServiceFunction();
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail background service handling";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "HandleBackgroundChecking()", message, ex);
-#endif // #if (DEBUG)
- }
- // Don't continue background service before the first has been serviced
- if (_BackgroundCheckingTimer != null)
- {
- _BackgroundCheckingTimer.Start();
- }
- }
-
- ///
- /// Need to be overwritten with a function for polling periodically read information from device for checking health etc.
- ///
- protected abstract void RunBackgroundReadServiceFunction();
- #endregion // Background service
-
- #region ---------------- Generic modbus communications ---------------------
- protected UInt16? read_U16(Device_value dv)
- {
- var ret = _md_com.Read(_device_id, dv, new UInt16());
- if (ret.IsOkay)
- {
- var value = ret.Data;
-#if (DEBUG)
- if (DoComDebugPrint)
- {
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={value,dig_value}");
- }
-#endif // #if (DEBUG)
- return value;
- }
- return null; // Error in reading
- }
-
- protected UInt32? read_U32(Device_value dv)
- {
- var ret = _md_com.Read(_device_id, dv, new UInt32());
- if (ret.IsOkay)
- {
- var value = ret.Data;
-#if (DEBUG)
- if (DoComDebugPrint)
- {
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={value,dig_value}");
- }
-#endif // #if (DEBUG)
- return value;
- }
- return null; // Error in reading
- }
-
-
- protected Single? read_F32(Device_value dv)
- {
- var ret = _md_com.Read(_device_id, dv, new Single());
- if (ret.IsOkay)
- {
- var value = ret.Data;
-#if (DEBUG)
- if (DoComDebugPrint)
- {
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={value,dig_value}");
- }
-#endif // #if (DEBUG)
- return value;
- }
- return null; // Error in reading
- }
-
- protected BigInteger? read_U128(Device_value dv)
- {
- var ret = _md_com.Read(_device_id, dv, new BigInteger());
- if (ret.IsOkay)
- {
- var value = ret.Data;
-#if (DEBUG)
- if (DoComDebugPrint)
- {
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={value,dig_value}");
- }
-#endif // #if (DEBUG)
- return value;
- }
- return null; // Error in reading
- }
-
- protected List read(List dvList)
- {
- var ret = _md_com.Read(_device_id, dvList);
- if (ret.Count > 0)
- {
-#if (DEBUG)
- foreach (var data in ret)
- {
- if (DoComDebugPrint)
- {
- var dv = data.Info;
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={data.Data,dig_value}");
- }
- }
-#endif // #if (DEBUG)
- return ret;
- }
- return null; // Error in reading
- }
-
-
-
- protected bool write_U16(Device_value dv, UInt16 value)
- {
- var isOkay = _md_com.Write(_device_id, dv, value);
- if (!isOkay)
- {
-#if (DEBUG)
- if (DoComDebugPrint)
- {
- Console.WriteLine($"Failed Write={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={value,dig_value}");
- }
-#endif // #if (DEBUG)
- }
- return isOkay; // Error in reading
- }
-
- protected bool write_U32(Device_value dv, UInt32 value)
- {
- var isOkay = _md_com.Write(_device_id, dv, value);
- if (!isOkay)
- {
-#if (DEBUG)
- if (DoComDebugPrint)
- {
- Console.WriteLine($"Failed Write={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={value,dig_value}");
- }
-#endif // #if (DEBUG)
- }
- return isOkay; // Error in reading
- }
-
- ///
- /// Write multiple values in a optimized number of telegrams
- ///
- ///
- ///
- protected List write(List reqList)
- {
- var ret = _md_com.Write(_device_id, reqList);
- if ((ret!=null) && (ret.Count > 0))
- {
-#if (DEBUG)
- foreach (var data in ret)
- {
- if (DoComDebugPrint)
- {
- var dv = data.Info;
- Console.WriteLine($"Write={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={data.Data,dig_value} {data.IsOkay}");
- }
- }
-#endif // #if (DEBUG)
- return ret;
- }
- return null; // Error in reading
- }
- #endregion // #region ---------------- Generic modbus communications ---------------------
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/Device/Value/ValueDataType.cs b/Common/modbus_master_csharp/Device/Value/ValueDataType.cs
deleted file mode 100644
index 82b07575..00000000
--- a/Common/modbus_master_csharp/Device/Value/ValueDataType.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Device.Value
-{
- ///
- /// Possible Type to use
- ///
- public enum ValueDataType
- {
- _Empty,
- B8,
- S8,
- U8,
- Bool,
- U16,
- U16MJK_SN,
- U16MJK_BRAND_ID,
- B16,
- S16,
- B32,
- U32,
- U32MJK_SN,
- S32,
- F32,
- B64,
- U64,
- S64,
- F64,
- U128,
- Array6B,
- Array10B,
- Array12B,
- Array64B,
- Array128B,
- Array136B,
- Array250B,
- STR6E,
- STR6S,
- STR6,
- STR8E,
- STR8S,
- STR8,
- STR10E,
- STR10S,
- STR10,
- STR16E,
- STR16S,
- STR16,
- STR18E,
- STR18S,
- STR18,
- STR20E,
- STR20S,
- STR20,
- STR22E,
- STR22S,
- STR22,
- STR30E,
- STR30S,
- STR30,
- STR32E,
- STR32S,
- STR32,
- STR34E,
- STR40E,
- STR40S,
- STR40,
- STR64E,
- STR64S,
- STR64,
- STR100E,
- STR100S,
- STR100,
- STR128E,
- STR128S,
- STR128,
- STR240E,
- STR240S,
- STR240,
- U16TEXTID,
- U16UNIT,
- U16UNITGROUP,
- U32TIME_Y2000,
- U32TIME_Y1970,
- U32TIME_Y1970_UTC,
- TIME_ymdhms,
- TIME_ASCII_12B
- }
-}
diff --git a/Common/modbus_master_csharp/Device/Value/ValueDescriptionFunc.cs b/Common/modbus_master_csharp/Device/Value/ValueDescriptionFunc.cs
deleted file mode 100644
index b04fb890..00000000
--- a/Common/modbus_master_csharp/Device/Value/ValueDescriptionFunc.cs
+++ /dev/null
@@ -1,146 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Xml;
-
-namespace XYLEM.Device.Value
-{
- public static class ValueDescriptionFunc
- {
- ///
- /// Is data a text
- ///
- ///
- public static Boolean IsText(this ValueDataType DataType)
- {
- switch (DataType)
- {
- case ValueDataType._Empty:
- case ValueDataType.B8:
- case ValueDataType.S8:
- case ValueDataType.U8:
- case ValueDataType.Bool:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- case ValueDataType.U16MJK_BRAND_ID:
- case ValueDataType.B16:
- case ValueDataType.S16:
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- case ValueDataType.S32:
- case ValueDataType.F32:
- case ValueDataType.B64:
- case ValueDataType.U64:
- case ValueDataType.S64:
- case ValueDataType.F64:
- case ValueDataType.U128:
- case ValueDataType.U16TEXTID:
- case ValueDataType.U16UNIT:
- case ValueDataType.U16UNITGROUP:
- case ValueDataType.U32TIME_Y2000:
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- case ValueDataType.TIME_ASCII_12B:
- case ValueDataType.TIME_ymdhms:
- case ValueDataType.Array6B:
- case ValueDataType.Array10B:
- case ValueDataType.Array12B:
- case ValueDataType.Array64B:
- case ValueDataType.Array128B:
- case ValueDataType.Array136B:
- case ValueDataType.Array250B:
- return false;
- default:
- if (DataType.ToString().StartsWith("STR"))
- {
- return true; // Is text
- }
- throw (new Exception("No known tag = " + DataType.ToString()));
- }
- }
-
- public static bool IsSMSText(this ValueDataType DataType)
- {
- if (DataType.IsText())
- {
- var typeAsText = DataType.ToString();
- if (typeAsText.EndsWith("S"))
- { // is Email
- return true;
- }
- }
- return false;
- }
-
- public static bool IsEmailText(this ValueDataType DataType)
- {
- if (DataType.IsText())
- {
- var typeAsText = DataType.ToString();
- if (typeAsText.EndsWith("E"))
- { // is Email
- return true;
- }
- }
- return false;
- }
-
- ///
- /// Conversion has to be for string Quoted Printable Text
- ///
- ///
- ///
- public static bool IsEmailQuotedPrintableText(this ValueDataType DataType)
- {
- if (DataType.IsText())
- {
- var typeAsText = DataType.ToString();
- if (typeAsText.EndsWith("Q"))
- { // is Email
- return true;
- }
- }
- return false;
- }
-
- ///
- /// Conversion type for string is Windows 1252
- ///
- ///
- ///
- public static bool IsWindows1252Text(this ValueDataType DataType)
- {
- if (DataType.IsText())
- {
- var typeAsText = DataType.ToString();
- if (typeAsText.EndsWith("W1252"))
- { // is Email
- return true;
- }
- }
- return false;
- }
-
- ///
- /// Conversion type for string is Windows 1252 and for the email recipient address that needs special handling
- /// Needs to have "<>" in frond and end
- ///
- ///
- ///
- public static bool IsWindows1252TextRecipient(this ValueDataType DataType)
- {
- if (DataType.IsText())
- {
- var typeAsText = DataType.ToString();
- if (typeAsText.EndsWith("W1252rec"))
- { // is Email
- return true;
- }
- }
- return false;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Device/md_test.cs b/Common/modbus_master_csharp/Device/md_test.cs
deleted file mode 100644
index cfb9b435..00000000
--- a/Common/modbus_master_csharp/Device/md_test.cs
+++ /dev/null
@@ -1,155 +0,0 @@
-using XYLEM.Device.Value;
-using MagFlux6200_metrology_reg_list;
-using XYLEM.Communication;
-using System;
-using System.IO.Ports;
-using System.Threading.Tasks;
-
-namespace XYLEM.Device
-{
- public enum MD_Reg_list
- {
- APP,
- MET
- }
-
- public class md_test
- {
- #region Access data from normal Application RS485
- internal static readonly Device_value App_F32FlowRate_m3ps = new Device_value("App_F32FlowRate_m3ps", 600, ValueDataType.F32, ValueRW_Type.ReadOnly, "App read flow");
- #endregion
-
-
- const int ch_lng_dv = -15;
- const int ch_lng_Version = -3;
- const int ch_lng_MD_adr = -7;
- const int dig_value = 10;
-
- public void Go(MD_Reg_list md_reg_list_selection, string serial_port, int baudRate, Parity parity)
- {
- ModbusCom md = new ModbusCom(serial_port, baudRate, parity);
- ReadTests(md_reg_list_selection, md);
-
- }
-
- public void ReadTests(MD_Reg_list md_reg_list_selection, ModbusCom md)
- {
- var device_id = 1;
- //{ // Testing read of specific registers
- // var test_rw_items = new[] { reg_list.Met_U32MdbsRegsVer, reg_list.Met_U16DeviceType, reg_list.Met_U32DeviceTypeDetail };
-
- // foreach (var testRead in test_rw_items)
- // {// Testing
- // Device_value dv = null;
- // if (md_reg_list_selection == MD_Reg_list.MET) // Metrology
- // {
- // dv = testRead;
- // var ret = md.Read(device_id, dv, new UInt32());
- // if (ret.IsOkay)
- // {
- // var value = ret.Data;
- // Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={value,dig_value}");
- // }
- // }
- // else // To application
- // {
- // dv = null; // Not yet supported
- // }
- // }
- // return;
- //}
-
-
- { // Read ID
- Device_value dv = reg_list.Met_U16DeviceType;
- var ret = md.Read(device_id, dv, new UInt16());
- if (ret.IsOkay)
- {
- var value = ret.Data;
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,ch_lng_MD_adr} value={value,dig_value}");
- }
- }
- {// Read Met_U32MdbsRegsVer
- Device_value dv = null;
- if (md_reg_list_selection == MD_Reg_list.MET) // Metrology
- {
- dv = reg_list.Met_U32MdbsRegsVer;
- var ret = md.Read(device_id, dv, new UInt32());
- if (ret.IsOkay)
- {
- var value = ret.Data;
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={value,dig_value}");
- }
- }
- else // To application
- {
- dv = null; // Not yet supported
- }
- }
- {// Read flow
- Device_value dv = null;
- string unit = "m3/h";
- Single scale = 1.0f;
- if (md_reg_list_selection == MD_Reg_list.MET) // Metrology
- {
- dv = reg_list.Met_F32FlowRate_lps;
- scale = 3.6f; // From l/s to m3/h
- }
- else // To application
- {
- dv = App_F32FlowRate_m3ps;
- scale = 3600f; // From m3/s to m3/h
- }
- var ret = md.Read(device_id, dv, new Single());
- if (ret.IsOkay)
- {
- var value = ret.Data;
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={(value*scale),dig_value} {unit}");
- }
- }
-
- {// Read / Write scratch
- Device_value dv = null;
- string unit = "";
- Single scale = 1.0f;
- if (md_reg_list_selection == MD_Reg_list.MET) // Metrology
- {
- dv = reg_list.Met_F32Scratch_F32;
-
- Single value = Single.NaN;
- { // read
- var ret = md.Read(device_id, dv, new Single());
- if (ret.IsOkay)
- {
- value = ret.Data;
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={(value*scale),dig_value} {unit}");
- }
- }
- { // write
- value += 10;
- if (!md.Write(device_id, dv, value))
- {
- Console.WriteLine($"Write failed={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={value,dig_value} {unit}");
- }
- else
- {
- Console.WriteLine($"Write={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={value,dig_value} {unit}");
- }
- }
- { // read back
- var ret = md.Read(device_id, dv, new Single());
- if (ret.IsOkay)
- {
- value = ret.Data; ;
- Console.WriteLine($"Read={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={(value*scale),dig_value} {unit}");
- }
- }
- }
- else // To application
- {
- dv = null; // Not yet supported
- }
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Program.cs b/Common/modbus_master_csharp/Program.cs
deleted file mode 100644
index 69fe52c5..00000000
--- a/Common/modbus_master_csharp/Program.cs
+++ /dev/null
@@ -1,1127 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.IO.Ports;
-using XYLEM.Communication;
-using System.Xml.Linq;
-using XYLEM.Base;
-using XYLEM.Communication.ValueEncoders;
-using System.Linq.Expressions;
-using System.Threading;
-using MagFlux6200_metrology_reg_list;
-using XYLEM.Device;
-using static modbus_master_csharp.Program;
-using System.Diagnostics.Contracts;
-using System.Security.Policy;
-using System.IO;
-using System.Diagnostics;
-using System.Xml.Schema;
-using System.Net.NetworkInformation;
-
-namespace modbus_master_csharp
-{
- internal class Program
- {
- /*For testing directly to metrology */
- static string[] argsDefault1 = new string[] { "TEST", "COM200", "115200", "N" };
- /*For metrology RS485 when transparent to metrology*/
- static string[] argsDefault2 = new string[] { "SAVE_CAL", "COM38" };
-
- static string[] argsDefault2b = new string[] { "SAVE_CAL", "COM200", "115200", "N" };
-
- static string[] argsDefault2c = new string[] { "SAVE_CAL", "COM200", "COM200", "115200", "N" };
-
- // Having more ports
- static string[] argsDefault3 = new string[] { "TEST", "COM38", "COM200" };
-
- /*For metrology RS485 when transparent to metrology*/
- static string[] argsDefault4 = new string[] { "LOAD_CAL=\"0_sensor_cal_for_testing.xml\"", "COM38" };
-
- /*For metrology RS485 when transparent to metrology*/
- static string[] argsDefault5 = new string[] { "SET_DN_SN=25,999999", "COM38" };
-
- /*For metrology RS485 when transparent to metrology*/
- static string[] argsDebugLiveRun = new string[] { "TEST", "COM200" };
-
- /*For metrology RS485 when transparent to metrology*/
- static string[] args_ExAbortCal = new string[] { "ABORT_CAL", "COM200" };
-
-#if (DEBUG)
- static bool LIVE_RUN = true; // Default = "true" to run with DUT communication or "false" to run without any DUT for communication and mock values
-
- /* Preload with program argument used for debugging*/
- static bool MAIN_ARGS_OVERWRITE = true; // true to overwrite run with "argsDebugLiveRun" [Default = false]
- static string[] MAIN_ARGS_OVERWRITE_WITH = argsDebugLiveRun; //testing arguments in debug Default = "argsDebugLiveRun"
-#else
- static bool LIVE_RUN = true; //
-#endif
-
- private static string GetArgHelpMessage(bool isArgErrorMessage, string[] args)
- {
- var name_exe = System.AppDomain.CurrentDomain.FriendlyName;
- var message = $@"
-Example of from command line:
-Save calibrations only include COMx to use standard baudrate and parity setup:
- ""{name_exe} {argsDefault2.ToSingleString(false)}""
-
-or run functional test for 2 MagFlux
- ""{name_exe} {argsDefault3.ToSingleString(false)}""
-
-To run functional test and configure both COMx, baudrate, parity. (Used for com directly to Metrology)
- ""{name_exe} {argsDefault1.ToSingleString(false)}""
-
-To Load calibrations only include COMx to use standard baudrate and parity setup:
- ""{name_exe} {argsDefault4.ToSingleString(false)}""
-
-To Set DN [mm] and Sensor Serial number, only include COMx to use standard baudrate and parity setup:
- ""{name_exe} {argsDefault5.ToSingleString(false)}""
-
-To Abort calibrations only include COMx to use standard baudrate and parity setup:
- ""{name_exe} {args_ExAbortCal.ToSingleString(false)}""
-";
- if (isArgErrorMessage)
- {
- var argsTxt = args != null ? args.ToSingleString(" ") : "";
- message = $"{new string('!', 50)}\nThere is errors in the Arguments list!\n{new string('!', 50)}\nWas: {name_exe} {argsTxt}\n" + message;
- }
- return message;
- }
-
- #region Reused functions for testing
- private static bool GetDeviceHealthy(IMagFluxRequestProtocol dut)
- {
- var name = nameof(dut.GetDeviceHealthy);
- var isOkay = dut.GetDeviceHealthy();
- var message = $"{name}: {(isOkay ? "Is okay" : "Has errors")}";
- if (!isOkay)
- {
- if (dut.GetDeviceErrorMessages(out var errorList))
- {
- Console.WriteLine(message + "\nError List:\n" + errorList.ToSingleString(false));
- }
- else
- {
- Console.WriteLine(message);
- }
- }
- return isOkay;
- }
-
- private static void GetBasicDeviceInfo(IMagFluxRequestProtocol dut)
- {
- {
- var name = nameof(dut.GetFwGitHash);
- var isOkay = dut.GetFwGitHash(out var value_out);
- var message = $"{name}: {(isOkay ? value_out : "!Read failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- {
- var name = nameof(dut.GetSensorSerialNo);
- var isOkay = dut.GetSensorSerialNo(out var value_out);
- var message = $"{name}: {(isOkay ? value_out : "!Read failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- {
- var name = nameof(dut.GetUniqueId);
- var isOkay = dut.GetUniqueId(out var value_out);
- var message = $"{name}: {(isOkay ? value_out : "!Read failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- {
- var name = nameof(dut.GetFirmwareVersion);
- var isOkay = dut.GetFirmwareVersion(out var value_out);
- var message = $"{name}: {(isOkay ? value_out : "!Read failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- {
- var name = nameof(dut.GetFwBuildDate);
- var isOkay = dut.GetFwBuildDate(out var value_out);
- var message = $"{name}: {(isOkay ? value_out : "!Read failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- }
-
- private static void GetBasicSensorInfo(IMagFluxRequestProtocol dut)
- {
- {
- var name = nameof(dut.GetDn_mm);
- var isOkay = dut.GetDn_mm(out var dn_mm_out);
- var message = $"{name}: {(isOkay ? $"{dn_mm_out}mm" : "!Read failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- {
- GetDeviceHealthy(dut);
- }
- }
-
- private static void AbortDeviceCalibration(IMagFluxRequestProtocol dut)
- {
- {
- var name = nameof(dut.AbortDeviceForCalibration);
- var isOkay = dut.AbortDeviceForCalibration();
- var message = $"{name}: {(isOkay ? "Done" : "!Abort failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- }
-
- private static bool GetCalibrationPoints(IMagFluxRequestProtocol dut, out CalibrationPoints value_out, bool printoutPoints)
- {
- var name = nameof(dut.GetCalibrationPoints);
- var isOkay = dut.GetCalibrationPoints(out value_out);
- if (printoutPoints)
- {
- Console.WriteLine($"{name}: Read points-> {(isOkay ? "\n"+value_out.ToString() : "!Read failed!")}");
- }
- else
- {
- Console.WriteLine($"{name}: Reading calibration points {(isOkay ? "Okay" : "!Read failed!")}");
- }
- return isOkay;
- }
-
- private static bool SetCalibrationPoints(IMagFluxRequestProtocol dut, CalibrationPoints new_calibration_points)
- {
- var isOkay = dut.SetCalibrationPoints(new_calibration_points);
- Console.WriteLine($"{nameof(dut.SetCalibrationPoints)}: {(isOkay ? "Okay" : "Failed")}\n{new_calibration_points}");
- return isOkay;
- }
-
- private static bool PrepareDeviceForCalibration(IMagFluxRequestProtocol dut)
- {
- { // --- Test setting the device ready for the first measurement used for calibrations ---
- {
- var isOkay = dut.PrepareDeviceForCalibration();
- Console.WriteLine($"{nameof(dut.PrepareDeviceForCalibration)}: {(isOkay ? "Okay" : "Failed")}");
- if (!isOkay || !GetCalibrationPoints(dut, out var value_out, true/*printout points*/))
- {
- GetDeviceHealthy(dut);
- throw new Exception("Failed Setting device up for calibration");
- }
- return isOkay;
- }
- }
- }
-
- private static void RunTestCalibrationPoints(IMagFluxRequestProtocol dut, CalibrationPoints new_calibration_points)
- {
- { // Write calibrations
- var isOkay = SetCalibrationPoints(dut, new_calibration_points);
- if (!isOkay)
- {
- GetDeviceHealthy(dut);
- throw new Exception("Failed writing the calibration to device");
- }
- }
- { // Get calibrations and check it
- if (!GetCalibrationPoints(dut, out var value_out, false/*Don't printout*/) || (new_calibration_points != value_out))
- {
- GetDeviceHealthy(dut);
- var msg = $"Failed! Calibration is not the same read as written to device\nWritten:\n{new_calibration_points}\nRead:\n{value_out}";
- Console.WriteLine(msg);
- throw new Exception(msg);
- }
- }
- }
-
- ///
- /// Read Sensor serial number
- ///
- ///
- /// Return the Serial number
- /// Will throw an exception if failing
- private static UInt32 GetSensorSerialNo(IMagFluxRequestProtocol dut)
- {
- var isOkay = dut.GetSensorSerialNo(out var read_out);
- UInt32 ret = 0;
- if (isOkay)
- {
- isOkay = UInt32.TryParse(read_out, out var passed);
- ret = passed;
- }
- { // Handle result
- var name = nameof(dut.GetSensorSerialNo);
- var message = $"Read {name}: {(isOkay ? ret.ToString() : "!failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- return ret;
- }
-
- ///
- /// Write Sensor serial number (Also check with a read back)
- ///
- /// what dut to write to
- /// New serial number
- /// Will throw an exception if failing
- private static void SetSensorSerialNo(IMagFluxRequestProtocol dut, UInt32 new_SN)
- {
- var name = nameof(dut.SetSensorSerialNo);
- Console.WriteLine($"Write of {name}: {new_SN.ToString()}");
- var isOkay = dut.SetSensorSerialNo(new_SN);
- var read = GetSensorSerialNo(dut);
- isOkay &= (read == new_SN); // Is the same as read ?
- // Handle result
- if (!isOkay)
- {
- var message = $"Write of {name}:!failed!";
- Console.WriteLine(message);
- throw new Exception(message);
- }
- }
-
- ///
- /// Read Sensor DN
- ///
- ///
- /// Return DN [mm]
- /// Will throw an exception if failing
- private static UInt16 GetDn_mm(IMagFluxRequestProtocol dut)
- {
- var isOkay = dut.GetDn_mm(out var read_out);
- UInt16 ret = 0;
- if (isOkay)
- {
- isOkay = UInt16.TryParse(read_out.ToString(), out var passed);
- ret = passed;
- }
- { // Handle result
- var name = nameof(dut.GetDn_mm);
- var message = $"Read {name}: {(isOkay ? ret.ToString() : "!failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- return ret;
- }
-
-
- ///
- /// Write Sensor DN size (Also check with a read back)
- ///
- /// what dut to write to
- /// New DN [mm]
- /// Will throw an exception if failing
- private static void SetDn_mm(IMagFluxRequestProtocol dut, UInt16 new_DN_mm)
- {
- var name = nameof(dut.SetDn_mm);
- Console.WriteLine($"Write of {name}: {new_DN_mm.ToString()}");
- var isOkay = dut.SetDn_mm(new_DN_mm);
- var read = GetDn_mm(dut);
- isOkay &= (read == new_DN_mm); // Is the same as read ?
- // Handle result
- if (!isOkay)
- {
- var message = $"Write of {name}:!failed!";
- Console.WriteLine(message);
- throw new Exception(message);
- }
- }
-
-
- ///
- /// save and load what is read from device
- ///
- ///
- ///
- private static void SaveCalPointsToTempFolder(IMagFluxRequestProtocol dut, CalibrationPoints value_out)
- {
- var tempSaveFolder = Environment.GetEnvironmentVariable("USERPROFILE")+@"\Downloads\";
- if (dut.GetSensorSerialNo(out var sensorSerial))
- {
- dut.GetUniqueId(out var id);
- var sensor_cal_file = tempSaveFolder+$"{sensorSerial}_sensor_cal_id_{id}_{DateTime.Now.ToFileTimeTxt()}.xml";
- Console.WriteLine($"Save to:\n{sensor_cal_file}");
- value_out.SaveToFile(sensor_cal_file);
- // Check saved data
- var to_saved_points = value_out.calibrations.ToArray();
- value_out.LoadFromFile(sensor_cal_file);
- var loaded_points = value_out.calibrations.ToArray();
- if (!to_saved_points.SequenceEqual(loaded_points))
- {
- var msg = $"Failed save of calibrations\nSaved:\n{to_saved_points}\nLoaded:\n{loaded_points}";
- Console.WriteLine(msg);
- throw new Exception(msg);
- }
- }
- }
-
-
-
- private static void SAVE_CAL(List duts)
- {
- { // Check Save all calibrations one DUT at a time
- for (var dutIdx = 0; dutIdx < duts.Count(); dutIdx++)
- {
- var dut = duts[dutIdx];
- Console.WriteLine($"------------------- DUT{dutIdx+1} --------------------");
- try
- {
- GetBasicDeviceInfo(dut);
- GetBasicSensorInfo(dut);
- if (!GetCalibrationPoints(dut, out var value_out, true/*printout points*/))
- {
- GetDeviceHealthy(dut);
- throw new Exception("Failed saving device calibration");
- }
- else
- {
- // save and load what is read from device
- SaveCalPointsToTempFolder(dut, value_out);
- }
- }
- catch (Exception ex)
- {
- dut.OpenLogFile();
- throw ex;
- }
- }
- }
- }
- private static void ABORT_CAL(List duts)
- {
- { // Check Save all calibrations one DUT at a time
- for (var dutIdx = 0; dutIdx < duts.Count(); dutIdx++)
- {
- var dut = duts[dutIdx];
- Console.WriteLine($"------------------- DUT{dutIdx+1} --------------------");
- try
- {
- GetBasicDeviceInfo(dut);
- AbortDeviceCalibration(dut);
- GetBasicSensorInfo(dut);
- if (!GetCalibrationPoints(dut, out var value_out, true/*printout points*/))
- {
- if (!PrepareDeviceForCalibration(dut))
- {
- throw new Exception("Failed abort of device calibration");
- }
- }
- }
- catch (Exception ex)
- {
- dut.OpenLogFile();
- throw ex;
- }
- }
- }
- }
-
-
- ///
- /// Load Calibrations
- ///
- ///
- ///
- private static void LOAD_CAL(List duts, List loadedCalibrations)
- {
- { // Check all Values one by one a DUT at a time
- if (duts.Count() != loadedCalibrations.Count())
- {
- throw new Exception("The number of calibrations is not the same as DUT's to load it in");
- }
- Console.WriteLine("\nSave Calibrations before starting writing new calibrations\n");
- SAVE_CAL(duts);
- Console.WriteLine("\nStarting writing new calibrations\n");
- for (var dutIdx = 0; dutIdx < duts.Count(); dutIdx++)
- {
- var dut = duts[dutIdx];
- Console.WriteLine($"------------------- DUT{dutIdx+1} --------------------");
- try
- {
- var new_calibration_points = loadedCalibrations[dutIdx];
- var isOkay = SetCalibrationPoints(dut, new_calibration_points);
- if (!isOkay)
- {
- throw new Exception($"Writing calibration Fail!\n{new_calibration_points}");
- }
- }
- catch (Exception ex)
- {
- dut.OpenLogFile();
- throw ex;
- }
- }
- }
- }
-
-
- ///
- /// Set DN and SN in device
- ///
- /// Device to write it to
- /// DN size in [mm]
- /// Sensor serial number
- static void SET_DN_SN(IMagFluxRequestProtocol dut, UInt16 DN_mm, UInt32 sensor_sn)
- {
- Console.WriteLine($"------------------- Read current DUT Sensor DN and SN --------------------");
- try
- {
- GetDn_mm(dut);
- GetSensorSerialNo(dut);
- }
- catch (Exception ex)
- {
- dut.OpenLogFile();
- throw ex;
- }
-
- Console.WriteLine($"------------------- Set DUT Sensor DN and SN --------------------");
- try
- {
- SetDn_mm(dut, DN_mm);
- SetSensorSerialNo(dut, sensor_sn);
- }
- catch (Exception ex)
- {
- dut.OpenLogFile();
- throw ex;
- }
- }
-
- static void TEST(List duts)
- {
- { // Check all Values one by one a DUT at a time
- for (var dutIdx = 0; dutIdx < duts.Count(); dutIdx++)
- {
- Console.WriteLine($"------------------- DUT{dutIdx+1} --------------------");
- var dut = duts[dutIdx];
- try
- {
- //if (false) // Don't do basic reads
- if (true) // Do basic read test
- {
- GetBasicDeviceInfo(dut);
- {
- var name = nameof(dut.GetFlowRate_lps);
- var isOkay = dut.GetFlowRate_lps(out var value_out);
- var message = $"{name}: {(isOkay ? $"{value_out} l/s or {value_out*3.6} m3/h" : "!Read failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- GetBasicSensorInfo(dut);
- { // Always check that GetDeviceErrorMessages() even when there is not error, to test function
- // Is only run in GetBasicSensorInfo() when there is an error
- var name = nameof(dut.GetDeviceErrorMessages);
- var isOkay = dut.GetDeviceErrorMessages(out var value_out);
- var message = $"{name}: \n{(isOkay ? String.Join("\n", value_out) : "!Read failed!")}";
- Console.WriteLine(message);
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- AbortDeviceCalibration(dut);
- {
- if (!GetCalibrationPoints(dut, out var value_out, true/*printout points*/))
- {
- GetDeviceHealthy(dut);
- }
- else
- {
- // save and load what is read from device
- SaveCalPointsToTempFolder(dut, value_out);
- }
- }
- }
- //if (false) // Do not execute calibration test
- if (LIVE_RUN && true) // execute calibration test
- { // A single calibration Test
- PrepareDeviceForCalibration(dut);
- { // --- Do a simple 2 point calibration with zero ---
- var new_calibration_points = new CalibrationPoints(
- new List {
- new CalibrationPoint(0,0.001f), // 0
- new CalibrationPoint(1,1.002f), // 1
- new CalibrationPoint(2,2.003f), // 2
- },
- dut.CalibrationPointsMax // Extend to
- );
- RunTestCalibrationPoints(dut, new_calibration_points);
- }
- { // --- Do a 6 point calibration with negative zero ---
- var new_calibration_points = new CalibrationPoints(
- new List {
- new CalibrationPoint(0,-0.001f), // 0
- new CalibrationPoint(1,1.002f), // 1
- new CalibrationPoint(2,2.003f), // 2
- new CalibrationPoint(3,3.004f), // 3
- new CalibrationPoint(4,4.005f), // 4
- new CalibrationPoint(5,5.006f), // 5
- },
- dut.CalibrationPointsMax // Extend to
- );
- RunTestCalibrationPoints(dut, new_calibration_points);
- // save and load what is read from device
- SaveCalPointsToTempFolder(dut, new_calibration_points);
- }
- { // --- Do a check of write of calibrations points that is not ordered correct ---
- Console.WriteLine($"Test writing calibration in wrong order is failing and Background check service is running");
- {
- var new_calibration_points = new CalibrationPoints(
- new List {
- new CalibrationPoint(0,-0.001f), // 0
- new CalibrationPoint(3,3.002f), // 1 Error this an error in order and need to brake calibrations
- new CalibrationPoint(2,2.003f), // 2
- },
- dut.CalibrationPointsMax // Extend to
- );
- var isOkay = SetCalibrationPoints(dut, new_calibration_points);
- if (isOkay)
- {
- throw new Exception($"Writing calibration in wrong order needs to Fail!\n{new_calibration_points}");
- }
- int maxWait_s = 5;
- while (maxWait_s-- > 0)
- {
- Console.Write($"\rWait timer out in {maxWait_s}s for getting Device Healthy is returning showing error: ");
- if (!dut.GetFlowRate_lps(out var value_out))
- {
- throw new Exception($"read of flow failed during polling Device Healthy!");
- }
- if (!GetDeviceHealthy(dut))
- {
- Console.WriteLine($"\nGot correct replay that is Device healthy is \"false\"");
- break; // Exit
- }
- Task.Delay(1000).GetAwaiter().GetResult();
- }
- if (maxWait_s <= 0)
- {
- throw new Exception($"Device Healthy was returning \"false\" when calibration was failing!\n{new_calibration_points}");
- }
- }
- {// Cleanup by returning calibration to default
- var isOkay = dut.PrepareDeviceForCalibration();
- if (!isOkay)
- {
- throw new Exception("Failing returning calibration to default!");
- }
- }
- }
- { // --- Test Sensor new_SN test ---
- Console.WriteLine($"--- Test Write a changed Sensor SN ---");
- // Read Sensor new_SN
- Console.WriteLine($"1)Read current Sensor SN");
- UInt32 current = GetSensorSerialNo(dut);
- // Create a new Sensor new_SN
- var write_new = current + 1;
- // Write function also check with a read and throw exception if failed
- Console.WriteLine($"2)Change Sensor SN to {write_new}");
- SetSensorSerialNo(dut, write_new);
- // Restore Sensor new_SN
- Console.WriteLine($"3)Restore Sensor SN to {write_new}");
- SetSensorSerialNo(dut, current);
- Console.WriteLine($"--- Finish Test ---");
- }
- { // --- Test Sensor DN test ---
- Console.WriteLine($"--- Test Write a changed Sensor DN Size ---");
- // SetDn_mm(dut, 20); // Insure a valid DN
-
- UInt16[] tests_dn_mm = { 50, 100 };
-
- // Read Sensor DN
- Console.WriteLine($"1)Read current Sensor DN Size");
- UInt16 current = GetDn_mm(dut);
-
- // Create a new Sensor DN
- var write_new = tests_dn_mm.FirstOrDefault(dn => dn != current);
- // Write function also check with a read and throw exception if failed
- Console.WriteLine($"2)Change Sensor DN Size as {write_new}");
- SetDn_mm(dut, write_new);
- // Restore Sensor DN
- Console.WriteLine($"3)Restore original Sensor DN Size as {current}");
- SetDn_mm(dut, current);
- Console.WriteLine($"--- Finish Test ---");
- }
- }
- }
- catch (Exception ex)
- {
- dut.OpenLogFile();
- throw ex;
- }
- }
- }
- }
-
- #endregion
- enum RUN_ACTION
- {
- UNKNOWN,
- TEST,
- SAVE_CAL,
- LOAD_CAL,
- ABORT_CAL,
- SET_DN_SN,
- SHOW_HELP,
- }
-
- class args_inputs
- {
- public List comports;
- public int? baudrate;
- public Parity? parity;
- public List loadedCalibrations;
- public UInt16? DN_mm;
- public UInt32? sensor_sn;
-
- public args_inputs()
- {
- comports = new List();
- baudrate = null;
- parity = null;
- loadedCalibrations = new List();
- sensor_sn = null;
- }
- }
-
-
- #region Handle if arguments
- static RUN_ACTION parse_arguments(string[] args, ref args_inputs ret_args_input)
- {
- bool gotArgs = (args.Length >= 1);
- var run_task = RUN_ACTION.UNKNOWN;
- var argErrors = gotArgs ? false : true;
- // Use Default connection if nothing is provided by arguments
- var arg_offset = 0;
- if (args.Length > arg_offset)
- {
- { /*--------- Parse What task to do ---------*/
- if (args.Length > arg_offset)
- {
- if ("-H" == args[arg_offset].ToUpper())
- {
- run_task = RUN_ACTION.SHOW_HELP;
- }
- else if ("TEST" == args[arg_offset].ToUpper())
- {
- run_task = RUN_ACTION.TEST;
- }
- else if ("SAVE_CAL" == args[arg_offset].ToUpper())
- {
- run_task = RUN_ACTION.SAVE_CAL;
- }
- else if ("ABORT_CAL" == args[arg_offset].ToUpper())
- {
- run_task = RUN_ACTION.ABORT_CAL;
- }
- else if (args[arg_offset].ToUpper().StartsWith("SET_DN_SN="))
- {
- run_task = RUN_ACTION.SET_DN_SN;
- var values_as_txt = args[arg_offset].Split('=').Last().Split(',');
- int value_offset = 0;
- { // parse DN
- var dn_mm_txt = values_as_txt[value_offset++];
- if (!UInt16.TryParse(dn_mm_txt, out var dn_mm))
- {
- throw new InvalidDataException($"Error parsing DN \n{dn_mm_txt} as [mm]\n{GetArgHelpMessage(true, args)}");
- }
- if ((dn_mm < 3) || (dn_mm > 3000))
- {
- throw new InvalidDataException($"Error parsing DN \n{dn_mm}[mm] only 3 - 3000mm is allowed\n{GetArgHelpMessage(true, args)}");
- }
- // Is okay
- ret_args_input.DN_mm = dn_mm;
- }
- { // parse Sensor SN
- var sn_txt = values_as_txt[value_offset++];
- if (!UInt32.TryParse(sn_txt, out var SN))
- {
- throw new InvalidDataException($"Error parsing Sensor SN \n{sn_txt}\n{GetArgHelpMessage(true, args)}");
- }
- // Is okay
- ret_args_input.sensor_sn = SN;
- }
-
- }
- else if (args[arg_offset].ToUpper().StartsWith("LOAD_CAL="))
- {
- run_task = RUN_ACTION.LOAD_CAL;
- var calFilePath = args[arg_offset].Split('=').Last();
- var cal = new CalibrationPoints();
- if (!File.Exists(calFilePath) || !cal.LoadFromFile(calFilePath))
- {
- throw new InvalidDataException($"Error load calibrations from\n {calFilePath}\n{GetArgHelpMessage(true, args)}");
- }
- ret_args_input.loadedCalibrations.Add(cal);
- }
- else
- {
- throw new NotImplementedException($"Missing support for parameter {args[arg_offset]}\n{GetArgHelpMessage(true, args)}");
- }
- }
- }
- arg_offset++; // Check next argument
- { /*--------- Parse com port / ports ---------*/
- var exit = false;
- var com_check_arg_offset = arg_offset;
- while (!exit)
- {
- if (args.Length > com_check_arg_offset)
- {
- var arg = args[com_check_arg_offset].ToUpper();
- if ("COM" == arg.Remove(3))
- {
- ret_args_input.comports.Add(arg);
- arg_offset = com_check_arg_offset; // Save ret location for last added com
- }
- else if (ret_args_input.comports.Count <= 0)
- {
- Console.WriteLine($"Com port {arg} not understood.");
- argErrors = true;
- exit = true;
- }
- else
- {
- exit = true; // No more com to connect to
- }
- com_check_arg_offset++; // Check next argument
- }
- else
- {
- exit = true; // No more com to connect to
- }
- }
- }
- arg_offset++; // Check next argument
- { /*--------- Parse Baud rate ---------*/
- if (args.Length > arg_offset)
- {
- var arg = args[arg_offset].ToUpper();
- var allowed_baudrate = new string[] { "9600", "19200", "38400", "57600", "115200", "230400" };
- if (allowed_baudrate.Contains(arg))
- {
- ret_args_input.baudrate = int.Parse(arg);
- }
- else
- {
- Console.WriteLine($"Baud rate {arg} not known.");
- ret_args_input.baudrate = -1;
- argErrors = true;
- }
- }
- }
- arg_offset++; // Check next argument
- { /*--------- Parse Parity ---------*/
- if (args.Length > arg_offset)
- {
- var arg = args[arg_offset].ToUpper();
- if (arg == "E")
- {
- ret_args_input.parity = Parity.Even;
- }
- else if (arg == "N")
- {
- ret_args_input.parity = Parity.None;
- }
- else if (arg == "O")
- {
- ret_args_input.parity = Parity.Odd;
- }
- else
- {
- Console.WriteLine($"Parity {arg} not known.");
- ret_args_input.parity = Parity.None;
- argErrors = true;
- }
- }
- }
- }
- if (argErrors)
- {
- string message = GetArgHelpMessage(argErrors, args);
- Console.WriteLine(message);
- if (argErrors)
- {
- throw new Exception(message); // exit main
- }
- }
- return run_task;
- }
- #endregion
-
- ///
- /// For unit testing setup
- ///
- ///
- static void Main(string[] args)
- {
- int ret_error = 0; // Is okay
- List duts = new List();
- try
- {
- var runMode = RUN_TYPE.Mock;
- if (LIVE_RUN)
- {
- runMode = RUN_TYPE.Normal;
- }
-
- // Just for internal testing
-#if (DEBUG)
- if (args.Length <= 0)
- {
- if (MAIN_ARGS_OVERWRITE)
- {
- args = MAIN_ARGS_OVERWRITE_WITH; //testing directly to metrology
- }
- }
-#endif
- var run_task = RUN_ACTION.UNKNOWN;
- bool gotArgs = ((args != null) && (args.Length >= 1));
- var inputs = new args_inputs();
- if (gotArgs)
- {
- run_task = parse_arguments(args, ref inputs);
- }
- else
- {
- run_task = RUN_ACTION.SHOW_HELP;
- }
- if (run_task == RUN_ACTION.SHOW_HELP)
- {
- string message = GetArgHelpMessage(false, null);
- Console.WriteLine(message);
- return;
- }
-
- // Set window to max size to better fit content
- // Not needed for now! Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight);
- #region Setup Communication to dut's
- foreach (var comport in inputs.comports)
- {
- if (runMode != RUN_TYPE.Normal)
- {
- Console.WriteLine($"{new string('!', 50)}\n Warning is in running in {runMode} mode\n{new string('!', 50)}");
- }
- MagFlux6200 dut = null;
- try
- { // Set up on DUT
- dut = new MagFlux6200(runMode);
- var log_path = Environment.GetEnvironmentVariable("USERPROFILE")+@"\Downloads\";
- var isOkay = dut.SetLogLocation(log_path, "logs_"+comport);
- Console.WriteLine($"Using program log path:\n{log_path}");
- isOkay &=gotArgs;
- if (isOkay)
- { // Use standard and just setup as port
- if (inputs.baudrate == null)
- {
- isOkay &=dut.Connect(comport);
- }
- else if ((inputs.baudrate != null) && (inputs.parity != null))
- {
- isOkay &=dut.Connect(comport, inputs.baudrate.Value, inputs.parity.Value);
- }
- else
- {
- isOkay = false; // Error in settings
- }
- }
-
- if (isOkay)
- {
- duts.Add(dut);
- }
- else
- {
- var port = comport;
- if (String.IsNullOrEmpty(port))
- {
- port = "COM ?";
- }
- throw new Exception($"Fail to setup device for {port}");
- }
- }
- catch (Exception ex)
- {
- if (dut!=null)
- {
- dut.OpenLogFile();
- }
- throw ex;
- }
- }
- #endregion //#region Setup Communication to dut's
- switch (run_task)
- {
- case RUN_ACTION.TEST:
- TEST(duts);
- break;
- case RUN_ACTION.SAVE_CAL:
- {
- SAVE_CAL(duts);
- }
- break;
- case RUN_ACTION.SET_DN_SN:
- {
- if(duts.Count() > 1)
- {
- throw new InvalidDataException($"Error support only a single device for setting DN and SN \n{GetArgHelpMessage(true, args)}");
- }
- SET_DN_SN(duts.First(), inputs.DN_mm.Value, inputs.sensor_sn.Value);
- int wait_ms = 15000;
- Console.WriteLine($"Wait {wait_ms/1000} for device to reset after a possible DN change");
- Task.Delay(15000).GetAwaiter().GetResult();
- }
- break;
- case RUN_ACTION.LOAD_CAL:
- {
- LOAD_CAL(duts, inputs.loadedCalibrations);
- }
- break;
- case RUN_ACTION.ABORT_CAL:
- {
- ABORT_CAL(duts);
- }
- break;
- default:
- {
- throw new NotImplementedException($"Missing support run mode {run_task}");
- }
- }
- Console.WriteLine("finished functional testing");
- // Is set to true when the monitoring values also needs to stop
- bool exitMonitoringLoop = false, pauseMonitoringLoop = false, _LastPauseMonitoringLoop = false;
- // Start a task for monitoring a key for exit
- Console.WriteLine("Press key 'x' exit, 'p' for pause read, 'c' continue read");
- Task.Run(() =>
- {
- ConsoleKeyInfo keyinfo;
- do
- {
- keyinfo = Console.ReadKey();
- if (keyinfo.Key == ConsoleKey.P)
- {
- pauseMonitoringLoop = true;
- }
- else if (keyinfo.Key == ConsoleKey.C)
- {
- pauseMonitoringLoop = false;
- }
- else
- {
- Console.WriteLine($"\n{keyinfo.Key} was pressed. Press key 'x' exit");
- }
- }
- while (keyinfo.Key != ConsoleKey.X);
- exitMonitoringLoop = true;
- });
- // Just read flow and other values for testing general measurement
- int count = 0;
- // "Structure of an interpolated string"
- // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
- while (!exitMonitoringLoop)
- {
- if (!pauseMonitoringLoop)
- {
- var message = "\r";
- var dutNum = 1;
- foreach (var dut in duts)
- {
- { // Read Flow
- var isOkay = dut.GetFlowRate_lps(out var value_out);
- if (dutNum > 1)
- {
- message += " | ";
- }
- message += $"DUT{dutNum++}: ";
- if (!dut.GetDeviceHealthy())
- {
- message += $"Error:";
- if (dut.GetDeviceErrorMessages(out var errorList))
- {
- message += $"{errorList.ToSingleString(false)} ";
- }
- else
- {
- message += $"No Text to display!";
- }
- }
- else
- {
- const int w = 9;
- message += $"{(isOkay ? $"{value_out*3.6,w:F3} m3/h" : $"!Read failed!")} {dut.GetComCounters()}\t";
- if (!isOkay)
- {
- throw new Exception(message);
- }
- }
- }
- }
- Console.Write(message + $" msg={++count}\t");
- }
- { // Print out if paused read
- if (_LastPauseMonitoringLoop != pauseMonitoringLoop)
- {
- _LastPauseMonitoringLoop = pauseMonitoringLoop;
- if (pauseMonitoringLoop)
- {
- Console.Write("\rRead is Paused!\t\t\t\t\t\t\t\t");
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- var name_exe = System.AppDomain.CurrentDomain.FriendlyName;
- AppConst.Logger.AddFuncLog(true, name_exe, "main()", ex);
- AppConst.Logger.OpenProgramLogFile();
- ret_error = -1; //https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes
- }
- finally
- {
- // Close connection before exit
- try
- {
- if (duts.Count != 0)
- {
- foreach (var dut in duts)
- {
- dut.CloseConnection();
- }
- }
- }
- catch { }
- Environment.Exit(ret_error); //https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/Properties/AssemblyInfo.cs b/Common/modbus_master_csharp/Properties/AssemblyInfo.cs
deleted file mode 100644
index de710f69..00000000
--- a/Common/modbus_master_csharp/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("modbus_master_csharp")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Xylem Inc.")]
-[assembly: AssemblyProduct("modbus_master_csharp")]
-[assembly: AssemblyCopyright("Copyright © Xylem Inc. 2023")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("f14940f8-3c86-4bb7-a915-b021e4b3052d")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/Common/modbus_master_csharp/README.md b/Common/modbus_master_csharp/README.md
deleted file mode 100644
index fedab5ba..00000000
--- a/Common/modbus_master_csharp/README.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# README #
-
-### What is this repository for? ###
-
-* A simple basic Modbus Master console project that support read and write from MagFlux Next Gen.
-* "md_master_csharp_6200_reg_list.cs" is using the register list generated by [magflux_modbus_registers](https://bitbucket.org/xyleminc/magflux_modbus_registers/src/main/)
-
-### How do I get set up? ###
-
-* Open project (modbus_master_csharp.sln) in Visual studio (developed in Ver 2022)
-* In "Program.cs" Main() Set what com port MagFlux Next Gen is connected to*
-
-### Contribution guidelines ###
-
-* Writing tests if you can
-* Code review with minimum one from MJK team
-* Make sure that "md_master_csharp_6200_reg_list.cs" is updated
-
-
-### Who do I talk to? ###
-
-* Please contact MJK R & D team
diff --git a/Common/modbus_master_csharp/compiled_exe/2023-10-10 support Met reg v6200045.zip b/Common/modbus_master_csharp/compiled_exe/2023-10-10 support Met reg v6200045.zip
deleted file mode 100644
index ca112651..00000000
Binary files a/Common/modbus_master_csharp/compiled_exe/2023-10-10 support Met reg v6200045.zip and /dev/null differ
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/0_sensor_cal_for_testing.xml b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/0_sensor_cal_for_testing.xml
deleted file mode 100644
index d7a88f79..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/0_sensor_cal_for_testing.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
- 0
- 0
-
-
- 1
- 1.1
-
-
- 5.0
- 5.1
-
-
- 0
- 0
-
-
- 0
- 0
-
-
- 0
- 0
-
-
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/0_sensor_cal_set_ready_for_calibration.xml b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/0_sensor_cal_set_ready_for_calibration.xml
deleted file mode 100644
index d4c9e539..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/0_sensor_cal_set_ready_for_calibration.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
- 0
- 0
-
-
- 0
- 0
-
-
- 0
- 0
-
-
- 0
- 0
-
-
- 0
- 0
-
-
- 0
- 0
-
-
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_ABORT_CAL.cmd b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_ABORT_CAL.cmd
deleted file mode 100644
index e929f782..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_ABORT_CAL.cmd
+++ /dev/null
@@ -1,6 +0,0 @@
-@Echo off
-CALL modbus_master_csharp.exe ABORT_CAL COM38
-
-REM CALL modbus_master_csharp.exe ABORT_CAL COM41 COM42 COM43 COM44
-
-pause
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_LOAD_CAL.cmd b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_LOAD_CAL.cmd
deleted file mode 100644
index 8d4caa62..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_LOAD_CAL.cmd
+++ /dev/null
@@ -1,19 +0,0 @@
-@echo off
-setlocal
-:PROMPT
-SET /P AREYOUSURE=Are you sure on overwrite DUT calibration (Y/[N])?
-IF /I "%AREYOUSURE%" NEQ "Y" GOTO END
-
-:: To connect to a metrology that is "bridged" to from application on RS485 (Using Default speed 9600 E)
-CALL modbus_master_csharp.exe LOAD_CAL=".\0_sensor_cal_for_testing.xml" COM38
-
-:: To connect directly to a metrology
-REM CALL modbus_master_csharp.exe LOAD_CAL=".\0_sensor_cal_for_testing.xml" COM41 115200 N
-
-pause
-EXIT(0)
-
-:END
-endlocal
-ECHO "Abort write of calibrations to DUT"
-pause
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_LOAD_CAL_set_ready_for_calibration.cmd b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_LOAD_CAL_set_ready_for_calibration.cmd
deleted file mode 100644
index 1ccdc12f..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_LOAD_CAL_set_ready_for_calibration.cmd
+++ /dev/null
@@ -1,19 +0,0 @@
-@echo off
-setlocal
-:PROMPT
-SET /P AREYOUSURE=Are you sure on return DUT to ready for calibration with all zero's (Y/[N])?
-IF /I "%AREYOUSURE%" NEQ "Y" GOTO END
-
-:: To connect to a metrology that is "bridged" to from application on RS485 (Using Default speed 9600 E)
-CALL modbus_master_csharp.exe LOAD_CAL=".\0_sensor_cal_set_ready_for_calibration.xml" COM38
-
-:: To connect directly to a metrology
-REM CALL modbus_master_csharp.exe LOAD_CAL=".\0_sensor_cal_set_ready_for_calibration.xml" COM41 115200 N
-
-pause
-EXIT(0)
-
-:END
-endlocal
-ECHO "Abort write of calibrations to DUT"
-pause
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_SAVE_CAL.cmd b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_SAVE_CAL.cmd
deleted file mode 100644
index 68a7d49c..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_SAVE_CAL.cmd
+++ /dev/null
@@ -1,12 +0,0 @@
-@Echo off
-
-:: To connect to a metrology that is "bridged" to from application on RS485 (Using Default speed 9600 E)
-CALL modbus_master_csharp.exe SAVE_CAL COM38
-
-:: To connect directly to a metrology
-REM CALL modbus_master_csharp.exe SAVE_CAL COM41 115200 N
-
-:: To connect to a many metrology that is "bridged" to from application on RS485 (Using Default speed 9600 E)
-REM CALL modbus_master_csharp.exe SAVE_CAL COM41 COM42 COM43 COM44
-
-pause
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_SET_DN_SN.cmd b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_SET_DN_SN.cmd
deleted file mode 100644
index 4f37b2ca..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_SET_DN_SN.cmd
+++ /dev/null
@@ -1,19 +0,0 @@
-@echo off
-setlocal
-:PROMPT
-SET /P AREYOUSURE=Are you sure on overwrite DUT DN Size and Sensor SN (Y/[N])?
-IF /I "%AREYOUSURE%" NEQ "Y" GOTO END
-
-:: To connect to a metrology that is "bridged" to from application on RS485 (Using Default speed 9600 E)
-CALL modbus_master_csharp.exe SET_DN_SN=00,00000000 COM38
-
-:: To connect directly to a metrology
-REM CALL modbus_master_csharp.exe SET_DN_SN=00,00000000 COM38 COM41 115200 N
-
-pause
-EXIT(0)
-
-:END
-endlocal
-ECHO "Abort write of calibrations to DUT"
-pause
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_TEST.cmd b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_TEST.cmd
deleted file mode 100644
index a9c46382..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_TEST.cmd
+++ /dev/null
@@ -1,17 +0,0 @@
-@echo off
-setlocal
-:PROMPT
-SET /P AREYOUSURE=Are you sure on Test that will overwrite DUT calibration (Y/[N])?
-IF /I "%AREYOUSURE%" NEQ "Y" GOTO END
-
-CALL modbus_master_csharp.exe TEST COM38
-
-REM CALL modbus_master_csharp.exe TEST COM2 COM5
-
-EXIT(0)
-
-:END
-endlocal
-ECHO "Abort TEST on DUT"
-
-pause
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_help.cmd b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_help.cmd
deleted file mode 100644
index 270e1bc4..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/run_help.cmd
+++ /dev/null
@@ -1,4 +0,0 @@
-@Echo off
-CALL modbus_master_csharp.exe -h
-
-pause
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/update_log.txt b/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/update_log.txt
deleted file mode 100644
index c2426cfe..00000000
--- a/Common/modbus_master_csharp/compiled_exe/202x-xx-xx support Met reg v6200xxx BETA/update_log.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-Log of changes since last release
-
-Version 2023-10-10
-Updated to Metrology register list version 6200045
-Added support for write DN and Sensor Serial number using arguments (Use help for more)
-
-Version 2023-10-03
-Fix problem setting Baudrate for COM port
-
-Version 2023-08-11
-Now only make a warning if register list is not the same as program was original written to.
-Added a cmd example for returning dut to ready for calibrations with callibration all set to 0
-
-Version 2023-06-02
-Added Support for Abort calibration
-Also print out device info before doing Save and Load Cal
-Some optimization for solving read problem when using MagFlux USB C connection
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/compiled_exe/bitbucket link for modbus_master_csharp.url b/Common/modbus_master_csharp/compiled_exe/bitbucket link for modbus_master_csharp.url
deleted file mode 100644
index 854b3cf8..00000000
--- a/Common/modbus_master_csharp/compiled_exe/bitbucket link for modbus_master_csharp.url
+++ /dev/null
@@ -1,5 +0,0 @@
-[{000214A0-0000-0000-C000-000000000046}]
-Prop3=19,11
-[InternetShortcut]
-IDList=
-URL=https://bitbucket.org/xyleminc/modbus_master_csharp/src/main/
diff --git a/Common/modbus_master_csharp/docs/dummy_file.txt b/Common/modbus_master_csharp/docs/dummy_file.txt
deleted file mode 100644
index e69de29b..00000000
diff --git a/Common/modbus_master_csharp/modbus_master_csharp.csproj b/Common/modbus_master_csharp/modbus_master_csharp.csproj
deleted file mode 100644
index 02a2573a..00000000
--- a/Common/modbus_master_csharp/modbus_master_csharp.csproj
+++ /dev/null
@@ -1,89 +0,0 @@
-
-
-
-
- Debug
- AnyCPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}
- Exe
- XYLEM
- modbus_master_csharp
- v4.8
- 512
- true
- true
-
-
- AnyCPU
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- AnyCPU
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/scripts/dummy_file.txt b/Common/modbus_master_csharp/scripts/dummy_file.txt
deleted file mode 100644
index e69de29b..00000000
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp.sln b/Common/modbus_master_csharp/src/modbus_master_csharp.sln
deleted file mode 100644
index 96fc53b0..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp.sln
+++ /dev/null
@@ -1,25 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 17
-VisualStudioVersion = 17.3.32929.385
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "modbus_master_csharp", "modbus_master_csharp\modbus_master_csharp.csproj", "{F14940F8-3C86-4BB7-A915-B021E4B3052D}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {F14940F8-3C86-4BB7-A915-B021E4B3052D}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(ExtensibilityGlobals) = postSolution
- SolutionGuid = {38CBBBD6-7446-4F8C-B002-D8EA9AF0BBE8}
- EndGlobalSection
-EndGlobal
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/App.config b/Common/modbus_master_csharp/src/modbus_master_csharp/App.config
deleted file mode 100644
index 193aecc6..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/App.config
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/AppConst.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/AppConst.cs
deleted file mode 100644
index 9d974cff..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/AppConst.cs
+++ /dev/null
@@ -1,111 +0,0 @@
-using XYLEM.Base.Files;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Reflection;
-
-namespace XYLEM.Base
-{
- internal static class AppConst
- {
- static ProgramLogCSVFileClass _Logger = new ProgramLogCSVFileClass();
-
- internal static ProgramLogCSVFileClass Logger { get { return _Logger; } }
-
- internal static bool IsBeta
- {
- get
- {
- return true;
- //return false;
- }
- }
-
- //
- // Summary:
- // Gets the product version associated with this application.
- //
- // Returns:
- // The product version.
- internal static string ProductVersion
- {
- get { return "1.0.0.1"; }
- }
-
-
- ///
- /// Return application MJK No.
- /// Have to be manuel changed by programmer for every application to fit install!
- ///
- /// return ex. "840126"
- internal static string ProductMainMJKNo()
- {
- return "MJK_MAGFLUX_MODBUS";
- }
-
- ///
- /// Return MJK Programs standard folder in My documents.
- ///
- /// return ex. "c:\...\My Documents\MJK Automation\"
- internal static string ProgramsUserFolderRootPath()
- {
- return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MJK Automation\\");
- }
-
-
- ///
- /// Return application folder in My documents.
- /// Have to be manuel changed by programmer for every application to fit install!
- ///
- /// return ex. "c:\...\My Documents\MJK Automation\840126\"
- internal static string ProgramUserFolderRootPath()
- {
- return Path.Combine(ProgramsUserFolderRootPath(), ProductMainMJKNo() + "\\");
- }
-
- ///
- /// Return application folder to use for user files.
- /// Have to be manuel changed by programmer for every application to fit install!
- ///
- /// return ex. "c:\...\My Documents\MJK Automation\- UserFileSave\"
- internal static string UserFileSavePath()
- {
- return Path.Combine(ProgramsUserFolderRootPath(), "- UserFileSave\\");
- }
-
- ///
- /// Return application folder to use for program user settings .
- /// Have to be manual changed by programmer for every application to fit install!
- ///
- /// return ex. "c:\...\My Documents\MJK Automation\840126\UserSettings\"
- internal static string UserFileSettingsPath()
- {
- return Path.Combine(ProgramUserFolderRootPath(), "UserSettings\\");
- }
-
- ///
- /// Try Create UserFileSavePath and SettingPath
- ///
- internal static void CreateStandardUserFolders()
- {
- try
- {
- if (!Directory.Exists(UserFileSavePath()))
- {
- Directory.CreateDirectory(UserFileSavePath());
- }
- if (!Directory.Exists(ProgramUserFolderRootPath()))
- {
- Directory.CreateDirectory(ProgramUserFolderRootPath());
- }
- }
- catch (Exception ex)
- {
- Logger.AddToProgramLogFile(true, "Error creating default user folders ", ex.Message);
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/ByteArrayExtensionClass.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/ByteArrayExtensionClass.cs
deleted file mode 100644
index ce2c4631..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/ByteArrayExtensionClass.cs
+++ /dev/null
@@ -1,314 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- internal static class ByteArrayExtensionClass
- {
- ///
- /// Compare if values in to array's is equal
- ///
- ///
- ///
- ///
- public static bool Compare(this byte[] b1, byte[] b2)
- {
- // Validate buffers are the same length.
- // This also ensures that the count does not exceed the length of either buffer.
- return b1.SequenceEqual(b2);
- }
-
- ///
- /// Copy a chunk of bytes from start index to a specific LongLength
- ///
- ///
- /// start offset 0..x
- /// LongLength of returned byte data array
- /// Return copy of byte data
- public static byte[] Copy(this byte[] from, long startIndex, long LongLength)
- {
- try
- {
- byte[] bArray = new byte[LongLength];
- Array.Copy(from, startIndex, bArray, 0, LongLength);
- return bArray;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "Copy()"));
- }
- }
-
- ///
- /// Copy a chunk of bytes to the end of array, starting from start offset
- ///
- ///
- /// start offset 0..x
- /// Return copy of byte data
- public static byte[] Copy(this byte[] from, long startIndex)
- {
- try
- {
- long LongLength = from.LongLength - startIndex;
- byte[] bArray = new byte[LongLength];
- Array.Copy(from, startIndex, bArray, 0, LongLength);
- return bArray;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "Copy()"));
- }
- }
-
- ///
- /// Remove a chunk of bytes at the end of array, staring from offset index
- ///
- ///
- /// offset 0..x
- /// Return copy of byte data
- public static byte[] Remove(this byte[] from, long fromIndex)
- {
- try
- {
- byte[] bArray = new byte[fromIndex];
- if (bArray.LongLength < fromIndex)
- {
- return from;
- }
- Array.Copy(from, 0, bArray, 0, fromIndex);
- return bArray;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "Remove()"));
- }
- }
-
-
- ///
- /// Copy bytes until this character
- ///
- /// bytes to find character in
- /// detection character
- ///
- internal static IEnumerable CopyUntil(this IEnumerable toInSeach, char untilThisCharacter)
- {
- try
- {
- if (toInSeach != null)
- {
- var withCharacter = toInSeach.TakeWhile(ch => ch != untilThisCharacter);
- // has any data after this
- if (withCharacter.Count() > 1)
- {
- return withCharacter;
- }
- }
- return null; // nothing to return
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "CopyUntil()"));
- }
- }
-
- ///
- /// Copy bytes after this character
- ///
- /// bytes to find character in
- /// detection character
- ///
- internal static IEnumerable CopyAfterThis(this IEnumerable toInSeach, char afterFirstCharacterOfThis)
- {
- try
- {
- if (toInSeach != null)
- {
- var withCharacter = toInSeach.SkipWhile(ch => ch != afterFirstCharacterOfThis);
- // has any data after this
- if (withCharacter.Count() > 1)
- {
- return withCharacter.Skip(1);
- }
- }
- return null; // nothing to return
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "CopyAfterThis()"));
- }
- }
-
- ///
- /// Copy bytes after this sequence of bytes
- ///
- /// bytes to find character in
- /// detection sequence
- ///
- internal static IEnumerable CopyAfterThis(this IEnumerable toSeachIn, IEnumerable afterSequenceThis)
- {
- try
- {
- var toSeachNow = toSeachIn;
- while ((toSeachNow != null) && (toSeachNow.Count() > 0) && (afterSequenceThis != null))
- {
- var startCh = afterSequenceThis.First();
- var sequenceLng = afterSequenceThis.Count();
- toSeachNow = toSeachNow.SkipWhile(ch => ch != startCh);
- // If there is data after a possible sequence.. check if it have sequnece
- if ((toSeachNow.Count() > sequenceLng) && afterSequenceThis.SequenceEqual(toSeachNow.Take(sequenceLng)))
- {
- if (toSeachNow.Count() > sequenceLng)
- {
- return toSeachNow.Skip(afterSequenceThis.Count());
- }
- return null; // nothing after sequence to return
- }
- // Not found
- if ((toSeachNow == null) || (toSeachNow.Count() == 0))
- {
- return null; // nothing to return
- }
- // increase to next to find next start
- toSeachNow = toSeachNow.Skip(1);
- }
- return null; // nothing to return
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "CopyAfterThis()"));
- }
- }
-
- ///
- /// Swap high and low byte in a word(16bit) for all words in a byte array (use ex. to a line data correct for conversion to computer U16 from modbus u16)
- ///
- /// Data to swap (SWAP IS NOT DONE ON A COPY, BUT ON THE ARRAY GIVEN AS INPUT
- /// return swapped input array reference (done to help supporting single line code use ex. "var data = byteArrayNeedingSwap.SwapByteInWord();")
- public static byte[] SwapByteInWord(this byte[] data)
- {
- try
- {
- if (data != null)
- {
- for (long i = 0; i < data.LongLength; i += 2)
- {
- byte b = data[i];
- data[i] = data[i + 1];
- data[i + 1] = b;
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "SwapByteInWord()"));
- }
- }
-
-
- ///
- /// Compare if to array's has the same content (like array1 == array2)
- ///
- ///
- ///
- /// return true if the same
- public static bool IsEqual(this byte[] array1, byte[] array2)
- {
- try
- {
- if ((array1 != null) && (array2 != null) && (array1.LongLength == array2.LongLength))
- {
- // To speed up
- var result = array1.SequenceEqual(array2);
- //{
- //#if (!DEBUG)
- //#error Test code!!!
- //#endif
- //if (!result) {
- // var test = "Not the same!!";
- // }
- //}
- return result;
- }
- return false;// not the same
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "IsEqual()"));
- }
- }
-
- ///
- /// Slice an array of bytes in the same sizes
- ///
- /// Data to slice an array of bytes from
- /// start in data for beginning slice of bytes
- /// The length of each slice of bytes
- /// List of byte slices with the same size
- public static List SliceSameSize(this byte[] source, long startIndex, long eachSliceLength)
- {
- try
- {
- if (source == null)
- {
- return null;
- }
- var LongLength = source.LongLength;
- var slices = new List();
- for (long offset = startIndex; offset < LongLength; offset += eachSliceLength)
- {
- slices.Add(Copy(source, offset, eachSliceLength));
- }
- return slices;
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "SliceSameSize()"));
- }
- }
-
- ///
- /// Slice a single array with a specific length
- ///
- /// Data to slice an array of bytes from
- /// start in data for beginning slice of bytes
- /// how long is the slice from start index
- ///
- public static byte[] Slice(this byte[] source, long startIndex, long length)
- {
- try
- {
- var returnValue = new byte[length];
- Array.Copy(source, startIndex, returnValue, 0, length);
- return returnValue;
- }
- catch (Exception ex)
- {
- throw new InvalidOperationException(ex.ToFuncErrorText(typeof(ByteArrayExtensionClass).ToString(), "Slice()"));
- }
- }
-
-
- ///
- /// Fill or pad array with a specific value
- ///
- ///
- ///
- ///
- public static byte[] Fill(this byte[] data, byte valueForFill)
- {
- if (data != null)
- {
- for (long i = 0; i < data.LongLength; i++)
- {
- data[i] = valueForFill;
- }
- }
- return data;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Convert1970SecToTime.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Convert1970SecToTime.cs
deleted file mode 100644
index 6dfa2ad8..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Convert1970SecToTime.cs
+++ /dev/null
@@ -1,153 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- internal enum TimeType
- {
- UTC,
- Local
- };
-
- internal static class TimeConvertClass
- {
- ///
- /// convert to a text showing file time ex. [20151201-135917]
- ///
- ///
- ///
- internal static string ToFileTimeTxt(this DateTime time)
- {
- return String.Format("[{0}{1:00}{2:00}-{3:00}{4:00}{5:00}]", time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second);
- }
-
- ///
- /// Convert 1970Sec to 32-bit time to Time
- ///
- ///
- ///
- internal static TimeSpan ConvertTimeSpan(this UInt32 timeSec)
- {
- return new TimeSpan((int)(timeSec/3600), (int)(timeSec%3600/60), (int)(timeSec%60));
- }
-
- internal static string ConvertSecondsToTimeSpanTxt(this Int32 timeSec)
- {
- return (timeSec >= 0 ? "" : "-") + ((UInt32)Math.Abs(timeSec)).ConvertSecondsToTimeSpanTxt();
- }
-
- internal static string ConvertToTimeSpanTxt(this TimeSpan time)
- {
- if (time.Days > 0)
- {
- return string.Format((time.Days > 1 ? "{0} days " : "1 day ") + "{1:00}:{2:00}:{3:00}", time.Days, time.Hours, time.Minutes, time.Seconds);
- }
- return string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
- }
-
- internal static string ConvertSecondsToTimeSpanTxt(this UInt32 timeSec)
- {
- TimeSpan time = new TimeSpan((int)(timeSec / 3600), (int)(timeSec % 3600 / 60), (int)(timeSec % 60));
- return time.ConvertToTimeSpanTxt();
- }
-
- internal static string ConvertSecondsToTimeSpanTxt(this Int16 timeSec)
- {
- return ConvertSecondsToTimeSpanTxt((Int32)timeSec);
- }
-
- internal static string ConvertSecondsToTimeSpanTxt(this UInt16 timeSec)
- {
- return ConvertSecondsToTimeSpanTxt((UInt32)timeSec);
- }
-
- internal static string ConvertMinuteToTimeSpanTxt(this Int16 timeMin)
- {
- return ConvertSecondsToTimeSpanTxt((Int32)timeMin * 60);
- }
-
- internal static string ConvertMinuteToTimeSpanTxt(this UInt16 timeMin)
- {
- return ConvertSecondsToTimeSpanTxt((UInt32)timeMin * 60);
- }
-
- internal static string ConvertHourToTimeSpanTxt(this Int16 timeHour)
- {
- return ConvertSecondsToTimeSpanTxt((Int32)timeHour * 3600);
- }
-
- internal static string ConvertHourToTimeSpanTxt(this UInt16 timeHour)
- {
- return ConvertSecondsToTimeSpanTxt((UInt32)timeHour * 3600);
- }
-
-
-
- ///
- /// Convert 1970Sec to 32-bit time to Time
- ///
- ///
- ///
- internal static DateTime Convert1970SecToTime(this UInt32 timeSec1970, TimeType timetype)
- {
- return timetype == TimeType.Local ?
- (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).AddSeconds(timeSec1970)
- : (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(timeSec1970);
- }
-
- ///
- /// Convert Time to 1970Sec
- ///
- ///
- ///
- internal static UInt32 ConvertTimeTo1970Sec(this DateTime time, TimeType timetype)
- {
- TimeSpan ts = timetype == TimeType.Local ?
- (time - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local))
- : (time.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
- return Convert.ToUInt32(ts.TotalSeconds);
- }
-
- ///
- /// Convert 2000Sec to 32-bit time to Time
- ///
- ///
- ///
- internal static DateTime Convert2000SecToTime(this UInt32 timeSec2000)
- {
- return (new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(timeSec2000);
- }
-
- ///
- /// Convert Time to 2000Sec
- ///
- ///
- ///
- internal static UInt32 ConvertTimeTo2000Sec(this DateTime time, TimeType timetype)
- {
- TimeSpan ts = timetype == TimeType.Local ?
- (time - new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Local))
- : (time.ToUniversalTime() - new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc));
- return Convert.ToUInt32(ts.TotalSeconds);
- }
-
- ///
- /// Convert time to a String
- ///
- ///
- ///
- public static String ToLocalDateTimeString(this DateTime time)
- {
- DateTime localTime;
- localTime = (time.Kind == DateTimeKind.Utc) ? time.ToLocalTime() : time;
- return (localTime.Year.ToString().PadLeft(4, '0') + "/" + localTime.Month.ToString().PadLeft(2, '0') + "/" + localTime.Day.ToString().PadLeft(2, '0') + " "
- + localTime.Hour.ToString().PadLeft(2, '0') + ":" + localTime.Minute.ToString().PadLeft(2, '0') + ":" + localTime.Second.ToString().PadLeft(2, '0'));
- }
-
- public static readonly bool IsLocalHourFormatAM_PM = new DateTime(2000, 1, 1, 13, 0, 0).ToLongTimeString().ToLower().Contains("pm");
- }
-}
-
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/DataUnion.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/DataUnion.cs
deleted file mode 100644
index e4c7c0f1..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/DataUnion.cs
+++ /dev/null
@@ -1,459 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- public static class DataUnionTools
- {
- public static byte[] Reverse(this byte[] data)
- {
- Array.Reverse(data);
- return data;
- }
- }
-
- ///
- /// Convert DataObjClass.DataType to Byte
- ///
- [StructLayout(LayoutKind.Explicit)]
- public struct DataUnion
- {
- //----------------------------- Data String to Convert Rx to ----------------------
- #region ---- Inset Data Bytes in union --------
- public enum DataByteLayoutType
- {
- Normal,
- SwapAll,
- SwapWords // KellerType
- }
-
- internal UInt32 Conv32BitToLowAdrHighValue(UInt32 input)
- {
- return (input >> 16) | (input << 16);
- }
-
- ///
- /// Convert input byte data to union data
- ///
- ///
- ///
- public DataUnion PutByteArray(Byte[] bInputArray, DataByteLayoutType byteType)
- {
- if (byteType == DataByteLayoutType.SwapAll)
- {
- Array.Reverse(bInputArray);
- }
- //dataRxText = "";
- if ((bInputArray == null) || (bInputArray.Length == 0))
- {
- u64Data = 0;
- return this;
- }
- bData = bInputArray[0];
- if (bInputArray.Length == 1)
- {
- return this;
- }
-
- bData1 = bInputArray[1];
- if (bInputArray.Length == 2)
- { // 16bit / 2 x 8bit
- return this;
- }
-
- bData2 = bInputArray[2];
- if (bInputArray.Length == 3)
- {
- if (byteType == DataByteLayoutType.SwapWords)
- {
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- bData3 = bInputArray[3];
- if (bInputArray.Length == 4)
- {// 32bit / 4 x 8bit
- if (byteType == DataByteLayoutType.SwapWords)
- {
- u32Data = Conv32BitToLowAdrHighValue(u32Data);
- }
- return this;
- }
-
- bData4 = bInputArray[4];
- if (bInputArray.Length == 5)
- {
- if (byteType == DataByteLayoutType.SwapWords)
- {
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- bData5 = bInputArray[5];
- if (bInputArray.Length == 6)
- {
- if (byteType == DataByteLayoutType.SwapWords)
- {
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- bData6 = bInputArray[6];
- if (bInputArray.Length == 7)
- {
- if (byteType == DataByteLayoutType.SwapWords)
- {
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- bData7 = bInputArray[7];
- if (byteType == DataByteLayoutType.SwapWords)
- { // 64bit / 8 x 8bit
- throw new Exception("SwapWords Not Supported!");
- }
- return this;
- }
-
- #endregion
-
- #region ---- Put data as Value in to union -----
- public void PutValue(UInt32 u32DataIn)
- {
- u32Data = u32DataIn;
- }
-
- public void PutValue(Int32 s32DataIn)
- {
- s32Data = s32DataIn;
- }
-
- public void PutValue(Single f32DataIn)
- {
- f32Data = f32DataIn;
- }
-
- public void PutValue(UInt64 u64DataIn)
- {
- u64Data = u64DataIn;
- }
-
- public void PutValue(Int64 s64DataIn)
- {
- s64Data = s64DataIn;
- }
-
- public void PutValue(double f64DataIn)
- {
- f64Data = f64DataIn;
- }
- #endregion
-
- #region ---- Get ByteArray from input as a value ----
- public byte[] GetByteArray()
- {
- return new byte[] { bData, bData1, bData2, bData3, bData4, bData5, bData6, bData7 };
- }
-
-
- void DoTxByteLayout(ref byte[] txData, DataByteLayoutType type)
- {
- try
- {
- if ((txData == null) || (txData.Length == 0))
- {
- throw new Exception("Has no txData");
- }
- switch (type)
- {
- case DataByteLayoutType.SwapAll: Array.Reverse(txData); break;
- case DataByteLayoutType.SwapWords:
- if (txData.Length == 4)
- { // 32bit / 2 x word
- byte[] firstWord = new byte[2];
- Array.Copy(txData, firstWord, 2);
- Array.Copy(txData, 2, txData, 0, 2);
- Array.Copy(firstWord, 0, txData, 2, 2);
- }
- else if (txData.Length == 8)
- { // 64bit / 2 x word
- throw new Exception("SwapWords Not Supported!");
- }
- break;
- case DataByteLayoutType.Normal: break; // Do nothing
- default: throw new Exception("Unkown type = " + type.ToString());
- }
- }
- catch (Exception ex)
- {
- throw new Exception("Error in " + this + " in func. DoTxByteLayout()! message = " + ex.Message);
- }
- }
-
-
- ///
- /// Convert to Tx data to unsigned 16bit
- ///
- ///
- ///
- public byte[] GetByteArray(UInt16 u16DataIn, DataByteLayoutType byteType)
- {
- byte[] bDataRet = new byte[2];
- u16Data = u16DataIn;
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to signed 16bit
- ///
- ///
- ///
- public byte[] GetByteArray(Int16 s16DataIn, DataByteLayoutType byteType)
- {
- byte[] bDataRet = new byte[2];
- s16Data = s16DataIn;
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to unsigned 32bit
- ///
- ///
- ///
- public byte[] GetByteArray(UInt32 u32DataIn, DataByteLayoutType byteType)
- {
- PutValue(u32DataIn);
- byte[] bDataRet = new byte[4];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to sign 32bit
- ///
- ///
- ///
- public byte[] GetByteArray(Int32 s32DataIn, DataByteLayoutType byteType)
- {
- PutValue(s32DataIn);
- byte[] bDataRet = new byte[4];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to Single 32bit
- ///
- ///
- ///
- public byte[] GetByteArray(Single f32DataIn, DataByteLayoutType byteType)
- {
- PutValue(f32DataIn);
- byte[] bDataRet = new byte[4];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to unsigned 64bit
- ///
- ///
- ///
- public byte[] GetByteArray(UInt64 u64DataIn, DataByteLayoutType byteType)
- {
- PutValue(u64DataIn);
- byte[] bDataRet = new byte[8];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- bDataRet[4] = bData4;
- bDataRet[5] = bData5;
- bDataRet[6] = bData6;
- bDataRet[7] = bData7;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to double (F64bit)
- ///
- ///
- ///
- public byte[] GetByteArray(Int64 s64DataIn, DataByteLayoutType byteType)
- {
- PutValue(s64DataIn);
- byte[] bDataRet = new byte[8];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- bDataRet[4] = bData4;
- bDataRet[5] = bData5;
- bDataRet[6] = bData6;
- bDataRet[7] = bData7;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- ///
- /// Convert to Tx data to unsigned 64bit
- ///
- ///
- ///
- public byte[] GetByteArray(double f64DataIn, DataByteLayoutType byteType)
- {
- PutValue(f64DataIn);
- byte[] bDataRet = new byte[8];
- bDataRet[0] = bData;
- bDataRet[1] = bData1;
- bDataRet[2] = bData2;
- bDataRet[3] = bData3;
- bDataRet[4] = bData4;
- bDataRet[5] = bData5;
- bDataRet[6] = bData6;
- bDataRet[7] = bData7;
- DoTxByteLayout(ref bDataRet, byteType);
- return bDataRet;
- }
-
- #endregion
-
- #region ---- Return Union data as a value ----
- public byte U8Data { get { return bData; } set { u16Data = bData; } }
- public byte U8Data0 { get { return bData; } }
- public byte U8Data1 { get { return bData1; } }
- public byte U8Data2 { get { return bData2; } }
- public byte U8Data3 { get { return bData3; } }
- public byte U8Data4 { get { return bData4; } }
- public byte U8Data5 { get { return bData5; } }
- public byte U8Data6 { get { return bData6; } }
- public byte U8Data7 { get { return bData7; } }
-
- public UInt16 U16Data { get { return u16Data; } set { u16Data = value; } }
- public UInt16 U16Data0 { get { return u16Data; } }
- public UInt16 U16Data1 { get { return u16Data1; } }
- public UInt16 U16Data2 { get { return u16Data2; } }
- public UInt16 U16Data3 { get { return u16Data3; } }
-
- public Int16 S16Data { get { return s16Data; } }
- public Int16 S16Data0 { get { return s16Data; } }
- public Int16 S16Data1 { get { return s16Data1; } }
- public Int16 S16Data2 { get { return s16Data2; } }
- public Int16 S16Data3 { get { return s16Data3; } }
-
- public UInt32 U32Data { get { return u32Data; } set { u32Data = value; } }
- public UInt32 U32Data0 { get { return u32Data; } }
- public UInt32 U32Data1 { get { return u32Data1; } }
-
- public Int32 S32Data { get { return s32Data; } set { s32Data = value; } }
- public Int32 S32Data0 { get { return s32Data; } }
- public Int32 S32Data1 { get { return s32Data1; } }
-
- public Single F32Data { get { return f32Data; } set { f32Data = value; } }
-
- public UInt64 U64Data { get { return u64Data; } }
- public Int64 S64Data { get { return s64Data; } }
- public double F64Data { get { return f64Data; } }
- #endregion
-
- ///
- /// Clear all data and return emptyunion
- ///
- ///
- public DataUnion ClearData()
- {
- u64Data = 0;
- return this;
- }
-
- #region ---- Field Union Array ----
- //----------------------------- Field Union array -----------------------------
- [FieldOffset(0)]
- private byte bData;
- [FieldOffset(1)]
- private byte bData1;
- [FieldOffset(2)]
- private byte bData2;
- [FieldOffset(3)]
- private byte bData3;
- [FieldOffset(4)]
- private byte bData4;
- [FieldOffset(5)]
- private byte bData5;
- [FieldOffset(6)]
- private byte bData6;
- [FieldOffset(7)]
- private byte bData7;
-
- [FieldOffset(0)]
- private UInt16 u16Data;
- [FieldOffset(2)]
- private UInt16 u16Data1;
- [FieldOffset(4)]
- private UInt16 u16Data2;
- [FieldOffset(6)]
- private UInt16 u16Data3;
-
- [FieldOffset(0)]
- private Int16 s16Data;
- [FieldOffset(2)]
- private Int16 s16Data1;
- [FieldOffset(4)]
- private Int16 s16Data2;
- [FieldOffset(6)]
- private Int16 s16Data3;
-
- [FieldOffset(0)]
- private UInt32 u32Data;
- [FieldOffset(4)]
- private UInt32 u32Data1;
-
- [FieldOffset(0)]
- private Int32 s32Data;
- [FieldOffset(4)]
- private Int32 s32Data1;
-
- [FieldOffset(0)]
- private Single f32Data;
- [FieldOffset(4)]
- private Single f32Data1;
-
- [FieldOffset(0)]
- private UInt64 u64Data;
-
- [FieldOffset(0)]
- private Int64 s64Data;
-
- [FieldOffset(0)]
- private double f64Data;
- #endregion
-
- };
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Files/PathTools.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Files/PathTools.cs
deleted file mode 100644
index 912c9e0b..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Files/PathTools.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base.Files
-{
- internal class PathTools
- {
- ///
- /// File path trunk
- ///
- /// ex. c:\mainDir\subDir\text.text
- /// ex. 12 char
- /// ex. will return "...\subDir\text.text" because "subDir\text.text" is > 12
- public static string FilePathStartTrunk(string dirPath, int trunkLength)
- {
- try
- {
- if (!String.IsNullOrEmpty(dirPath) && (dirPath.Length > 40))
- { // if to big .. then trunk it
- var pathSplits = dirPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
- if (pathSplits.Length > 0)
- { // are able to trunk
- dirPath = "";
- foreach (var item in pathSplits.Reverse())
- {
- dirPath = CombineDirAndFileSubPath(item, dirPath);
- if (dirPath.Length > 40)
- {
- dirPath = CombineDirAndFileSubPath("...", dirPath);
- break; // max length is now then just exit loop
- }
- }
- }
- }
- return dirPath;
- }
- catch (Exception ex)
- {
- AppConst.Logger.AddFuncLog(true, "PathTools", "FilePathStartTrunk()", ex);
- }
- return "?";
- }
-
- ///
- /// Create the directory path
- ///
- ///
- ///
- public static Boolean CreateDirPath(string dirPath)
- {
- try
- {
- // Determine whether the directory exists.
- if (Directory.Exists(dirPath))
- {
- //That path exists already
- return false;
- }
-
- // Try to create the directory.
- DirectoryInfo di = Directory.CreateDirectory(dirPath);
- return false;
- }
- catch
- {
- return true;
- }
- }
-
- ///
- /// Create the directory for a file path
- ///
- ///
- /// return true on error
- public static bool CreateDirPathForFile(string pathForFile)
- {
- try
- {
- return CreateDirPath(GetDirPath(pathForFile));
- }
- catch
- {
- return true;
- }
- }
-
- ///
- /// Combine a directory path and sub path to a compleate path
- ///
- ///
- ///
- ///
- public static string CombineDirAndFileSubPath(string dirPath, string subFilePath)
- {
- dirPath = dirPath.Trim().EndsWith("\\") ?
- dirPath.Trim().Remove(dirPath.LastIndexOf("\\")) :
- dirPath.Trim();
- return Path.Combine(dirPath, subFilePath.Trim());
- }
-
- ///
- /// Get directory path
- ///
- ///
- /// return true on error
- public static string GetDirPath(string filePath)
- {
- return filePath.Remove(filePath.Trim().LastIndexOf("\\"));
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Files/ProgramLogCSVFileClass.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Files/ProgramLogCSVFileClass.cs
deleted file mode 100644
index 3a573247..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/Files/ProgramLogCSVFileClass.cs
+++ /dev/null
@@ -1,232 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Runtime.CompilerServices;
-using System.Text;
-using System.Threading.Tasks;
-
-
-namespace XYLEM.Base.Files
-{
- public class ProgramLogCSVFileClass
- {
- private int _LogCountErrors = -1;
- private int _LogCountTotal = -1;
-
- public int LogCountErrors { get { return _LogCountErrors; } }
- public int LogCountTotal { get { return _LogCountTotal; } }
-
- public string StdLogFilePath = null;
-
- public event EventHandler OnErrorIsAdded;
-
-#if (!DEBUG)
- public bool DoTimeStamp = false;
-#else
- /*#warning DoTimeStamp is true!!!!!!!!!!!!!!!!
- public bool DoTimeStamp = true;*/
- public bool DoTimeStamp = false;
-#endif
- ///
- /// init standard program logger
- ///
- /// use a custom log folder or null if use default
- /// set a custom log file name without extension (ex. "UserCustomLogFile") or null if use default
- public ProgramLogCSVFileClass(string stdLogFolderPath = null, string filename = null)
- {
- if (String.IsNullOrEmpty(filename))
- {
- filename = $"{AppConst.ProductVersion}_program_log";
- }
- if (!string.IsNullOrEmpty(stdLogFolderPath))
- {
- if (!Directory.Exists(stdLogFolderPath))
- {
- PathTools.CreateDirPath(stdLogFolderPath);
- }
- StdLogFilePath=Path.Combine(stdLogFolderPath, filename + ".txt");
- }
- else
- {
- this.StdLogFilePath = Path.Combine(AppConst.ProgramUserFolderRootPath(), filename + ".txt");
-#if (DEBUG)
- Console.WriteLine($"Using standard program log path:\n{this.StdLogFilePath}");
-#endif
- }
- }
-
- ///
- /// Automated get function name for the function calling this
- /// Used for automating getting a function name to write in a log
- ///
- /// Add extra message to log with function name
- /// "[CALLING_FUNCTION_NAME]() -> [inclMsg]"
- [MethodImpl(MethodImplOptions.NoInlining)]
- public string GetCurrentMethod(string inclMsg = null)
- {
- var st = new StackTrace();
- var sf = st.GetFrame(1);
-
- var nameTxt = $"{sf.GetMethod().Name}()";
- if (!String.IsNullOrEmpty(inclMsg))
- {
- nameTxt += " -> " + inclMsg;
- }
- return nameTxt;
- }
-
- ///
- /// Automated get function name for the function calling this
- /// Used for automating getting a function name to write in a log
- ///
- /// Add extra message to log with function name
- /// "[CALLING_FUNCTION_NAME]() -> [inclMsg]"
- [MethodImpl(MethodImplOptions.NoInlining)]
- public static string GetCurrentStaticMethod(string inclMsg = null)
- {
- var st = new StackTrace();
- var sf = st.GetFrame(1);
-
- var nameTxt = $"{sf.GetMethod().Name}()";
- if (!String.IsNullOrEmpty(inclMsg))
- {
- nameTxt += " -> " + inclMsg;
- }
- return nameTxt;
- }
-
- internal void AddToLogFile(bool isError, string nameSingleLine, string infoMultibleLines)
- {
- AddToLogFile(isError, StdLogFilePath, nameSingleLine, infoMultibleLines);
- }
-
- internal void AddToLogFile(bool isError, string LogFilePath, string nameSingleLine, string infoMultibleLines)
- {
- try
- {
- if (isError)
- {
- _LogCountErrors++;
- try
- {
- if (OnErrorIsAdded != null)
- {
- OnErrorIsAdded(null, null);
- }
- }
- catch { } // Don't handle this if something breaks down
- }
- _LogCountTotal++;
- if (System.IO.File.Exists(LogFilePath))
- {
- FileInfo f = new FileInfo(LogFilePath);
- if (f.Length > (DoTimeStamp ? 1000000 : 10000))
- {
- f.Delete();
- }
- }
- else
- {
- PathTools.CreateDirPathForFile(LogFilePath);
- }
- var message = infoMultibleLines;
- var length = message.Length;
- File.AppendAllText(LogFilePath, "¤¤¤ " + nameSingleLine.Trim() + " \"" + DateTime.Now.ToString() + "\" ¤¤¤ " + Environment.NewLine
- + message + Environment.NewLine);
-#if (DEBUG)
- System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff ") +
- " ¤¤¤ " + nameSingleLine.Trim() + " ¤¤¤ " + Environment.NewLine
- + message
- );
-#endif
- }
- catch (Exception ex)
- { // Ups just to make sure that this don't result in program is closed
- string test = ex.ToMessageText();
- }
- }
-
- ///
- /// Add a time stamp in program log file.. used to time differend code / controls load time
- ///
- /// class or window / control obkject to make time stamp for
- /// description text
- /// Force making log and ignore DoTimeStamp setting
- internal void AddToTimestampLog(object processObj, string desc, bool forceLog = false)
- {
- try
- {
- if (DoTimeStamp || forceLog)
- {
- AddToLogFile(false, StdLogFilePath, processObj.ToString() + DateTime.Now.ToString(" [HH:mm:ss fff]"), desc);
- }
- }
- catch { }
- }
-
- internal void AddToProgramLogFile(bool isError, string nameSingleLine, string infoMultibleLines)
- {
- AddToLogFile(isError, StdLogFilePath, nameSingleLine, infoMultibleLines);
- }
-
- ///
- /// Add to program log
- ///
- /// Exception to log
- /// Is an error or just as log
- /// what class or where function is located in
- /// what function it was in like "myFunc()" and null if not used
- /// Additional information also to include like "while doing x and y..."
- internal void ToLog(Exception ex, bool isError, string className, string functionName = null, string dataInfo = null)
- {
- AddToProgramLogFile(isError, LogMessageTool.ToFuncText(isError, className, functionName),
- (String.IsNullOrEmpty(dataInfo) ? "" : dataInfo + ((ex != null) ? Environment.NewLine : "")) // Add data info if used
- + ((ex != null) ? ex.ToMessageText() : ""));
- }
-
- internal void AddFuncLog(bool isError, string className, string functionName, string dataInfo, Exception ex)
- {
- ToLog(ex, isError, className, functionName, dataInfo);
- }
-
- internal void AddFuncLog(bool isError, string className, string functionName, Exception ex)
- {
- AddFuncLog(isError, className, functionName, null, ex);
- }
-
- internal void AddFuncLog(bool isError, string className, string functionName, string dataInfo)
- {
- AddFuncLog(isError, className, functionName, dataInfo, null);
- }
-
- internal void AddClassInitLog(bool isError, string className, Exception ex)
- {
- AddToProgramLogFile(isError, LogMessageTool.ToInitText(isError, className), ((ex != null) ? ex.ToMessageText() : ""));
- }
-
- internal void AddClassInitLog(bool isError, string className, string dataInfo, Exception ex)
- {
- AddToProgramLogFile(isError, LogMessageTool.ToInitText(isError, className, dataInfo), ((ex != null) ? ex.ToMessageText() : ""));
- }
-
- internal void OpenProgramLogFile()
- {
- OpenLogFile(StdLogFilePath);
- }
-
-
- internal void OpenLogFile(string LogFilePath)
- {
- try
- {
- Process.Start(LogFilePath);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error Open Log " + Environment.NewLine + ex.ToMessageText());
- }
- }
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/LogMessageTool.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/LogMessageTool.cs
deleted file mode 100644
index 5229e356..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/LogMessageTool.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- public static class LogMessageTool
- {
- ///
- /// Return Type Name as a string
- ///
- ///
- ///
- ///
- static public string TypeName(this T obj)
- {
- Type t;
- if (obj == null)
- {
- t = typeof(T);
- }
- else
- {
- t = obj.GetType();
- }
- return t.Name;
- }
-
- public static string ToMessageText(this Exception ex)
- {
- if (ex != null)
- {
- var message = "";
- var innerMessage = "";
- if (ex.InnerException != null)
- {
- innerMessage = ToMessageText(ex.InnerException);
- }
- if ((ex.Message != null) && !String.IsNullOrEmpty(ex.Message))
- {
- message = ex.Message;
- }
- if (!String.IsNullOrEmpty(innerMessage))
- {
- message += (!String.IsNullOrEmpty(message) ? Environment.NewLine : "") + innerMessage;
- }
- return message;
- }
- return "";
- }
-
- public static string ToFuncText(bool isError, string className, string functionName)
- {
- var message = (isError ? "Error in class" : "Class ") + className + " and func. " + functionName;
-#if(DEBUG)
- System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff ") + message);
-#endif
- return message;
- }
-
- public static string ToInitText(bool isError, string className)
- {
- var message = (isError ? "Error in init of " : "Init of ") + className;
-#if(DEBUG)
- System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff ") + message);
-#endif
- return message;
- }
-
- public static string ToInitText(bool isError, string className, string dataInfo)
- {
- return ToInitText(isError, className + " info = " + dataInfo);
- }
-
- public static string ToFuncErrorText(this Exception ex, string className, string functionName)
- {
- return ToFuncText(true, className, functionName + ((ex == null) ? "" : Environment.NewLine + "Message = " + ex.ToMessageText()));
- }
-
- public static string ToFuncErrorText(this Exception ex, string className, string functionName, string dataInfo)
- {
- return ToFuncText(true, className, functionName + Environment.NewLine + dataInfo + ((ex == null) ? "" : Environment.NewLine + "Message = " + ex.ToMessageText()));
- }
-
- public static string ToFuncErrorText(string className, string functionName, string dataInfo)
- {
- return ToFuncText(true, className, functionName + Environment.NewLine + dataInfo);
- }
-
- public static string ToFuncErrorText(string className, string functionName)
- {
- return ToFuncText(true, className, functionName);
- }
-
- public static string ToInitErrorText(this Exception ex, string className)
- {
- return ToInitText(true, className + ((ex == null) ? "" : Environment.NewLine + "Message = " + ex.ToMessageText()));
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/NumberConvert.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/NumberConvert.cs
deleted file mode 100644
index 6d8b975d..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/NumberConvert.cs
+++ /dev/null
@@ -1,602 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base
-{
- public static class NumberConvert
- {
- public static readonly string ColumnSeperatorCSV = ((2.3).ToString().Contains(".") ? "," : ";");
- private static readonly int base10 = 10;
- private static readonly char[] cHexa = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
- private static readonly int[] iHexaNumeric = new int[] { 10, 11, 12, 13, 14, 15 };
- private static readonly int[] iHexaIndices = new int[] { 0, 1, 2, 3, 4, 5 };
- private static readonly int asciiDiff = 48;
-
- public static string PadLeft(this String text, int minLength)
- {
- int iCount = minLength - text.Length;
- String textRet = "";
- if (iCount > 0)
- {
- textRet = new String('0', iCount);
- }
- return textRet + text;
- }
-
- ///
- /// Tag for values input is done as "decimal" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsDecimalTag = "decimal";
-
- ///
- /// Tag for values input is done as "binary" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsBinaryTag = "binary";
-
-
- ///
- /// Tag for values input is done as "octal" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsOctalEndTag = "octal";
-
- ///
- /// Tag for values input is done as "0o" and is placed ex. in front the value that needs to be converted
- ///
- public static readonly string ValueInputAsOctalFrontTag = "0o";
-
- ///
- /// Tag for values input is done as "hex" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsHexEndTag = "hex";
-
- ///
- /// Tag for values input is done as "0x" and is placed ex. in front the value that needs to be converted
- ///
- public static readonly string ValueInputAsHexFrontTag = "0x";
-
-
- ///
- /// Tag for values input is done as "bin" and is placed ex. in front or behinde the value that needs to be converted
- ///
- public static readonly string ValueInputAsBinaryEndTag = "bin";
-
- ///
- /// Tag for values input is done as "0b" and is placed ex. in front the value that needs to be converted
- ///
- public static readonly string ValueInputAsBinaryFrontTag = "0b";
-
- ///
- /// Convert byte values as in a string byte array
- ///
- /// must be like "0x12, 0x12, 0x12" or "1010bin; 1010bin; 1010bin" or "decimal 123, 123, 123"
- ///
- public static byte[] ValuesToBytes(this string byteValues)
- {
- try
- {
- List ret = new List();
- var isHexadecimal = false;
- var isDecimal = false;
- var isBinary = false;
- byteValues = byteValues.Trim().ToLower();
- bool isBinaryMatch = (new Regex(@"^[01 ]+$")).IsMatch(byteValues);
- bool isHexMatch = (new Regex(@"^[0-9a-f ]+$")).IsMatch(byteValues);
- if (!string.IsNullOrEmpty(byteValues) && (byteValues.Contains(ValueInputAsHexEndTag) || byteValues.Contains("0x") || (isHexMatch && !isBinaryMatch)))
- {
- byteValues = byteValues.ToLower().Replace(ValueInputAsHexEndTag, "");
- isHexadecimal = true;
- }
- else if (!string.IsNullOrEmpty(byteValues) && (byteValues.Contains(ValueInputAsDecimalTag) || isBinaryMatch))
- {
- byteValues = byteValues.Replace(ValueInputAsDecimalTag, "");
- isDecimal = true;
- }
- else if (!string.IsNullOrEmpty(byteValues) && byteValues.Contains(ValueInputAsBinaryTag))
- {
- byteValues = byteValues.Replace(ValueInputAsBinaryTag, "");
- isBinary = true;
- }
- var chunks = byteValues.Trim(new char[] { ' ' }).Split(new string[] { ",", ";", " ", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
- foreach (var value in chunks)
- {
- var toConvert = value.Trim();
- if (!string.IsNullOrEmpty(toConvert))
- {
- if (isHexadecimal || !isBinary && !isDecimal && (toConvert.StartsWith(ValueInputAsHexFrontTag) || toConvert.ToLower().Contains(ValueInputAsHexEndTag)))
- {
- ret.Add(Convert.ToByte(toConvert.Replace(ValueInputAsHexFrontTag, "").ToLower().Replace(ValueInputAsHexEndTag, ""), 16));
- }
- else if (isBinary || !isDecimal && (toConvert.StartsWith(ValueInputAsBinaryFrontTag) || toConvert.ToLower().Contains(ValueInputAsBinaryEndTag)))
- {
- ret.Add(Convert.ToByte(toConvert.Replace(ValueInputAsBinaryFrontTag, "").ToLower().Replace(ValueInputAsBinaryEndTag, ""), 2));
- }
- else
- {
- ret.Add(Convert.ToByte(toConvert, 10));
- }
- }
- }
- return ret.ToArray();
- }
- catch
- {
- return null; // Error
- }
- }
-
- public static string UnsignedHexToDecimal(this string Hex)
- {
- try
- {
- return Convert.ToUInt64(Hex, 16).ToString();
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToHex(this string iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return UnsignedDecimalToHex(Convert.ToUInt64(iDec), padLeft, Add_0x);
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToHex(this UInt32 iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return ((Add_0x) ? ValueInputAsHexFrontTag : "") + String.Format("{0:X}", iDec).PadLeft(padLeft, '0');
- }
- catch
- {
- return "?";
- }
- }
-
- public static string DecimalToHex(this Int32 iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return ((Add_0x) ? ValueInputAsHexFrontTag : "") + String.Format("{0:X}", iDec).PadLeft(padLeft, '0');
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToHex(this UInt64 iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return ((Add_0x) ? ValueInputAsHexFrontTag : "") + String.Format("{0:X}", iDec).PadLeft(padLeft, '0');
- }
- catch
- {
- return "?";
- }
- }
-
- public static string DecimalToHex(this Int64 iDec, int padLeft, bool Add_0x)
- {
- try
- {
- return ((Add_0x) ? ValueInputAsHexFrontTag : "") + String.Format("{0:X}", iDec).PadLeft(padLeft, '0');
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToBin(this string dec, bool Add_0b)
- {
- try
- {
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + UnsignedDecimalToBase(Convert.ToUInt64(dec), 2);
- }
- catch
- {
- return "?";
- }
- }
-
- static string DoAutoPadLeft(this string valueAsStr)
- {
- var numberToPad = (valueAsStr.Length <= 8) ? 8 : (valueAsStr.Length <= 16) ? 16 : (valueAsStr.Length <= 32) ? 32 : 64;
- return valueAsStr.PadLeft(numberToPad, '0');
- }
-
- static string DoAutoSpcaePadEvery4Char(this string ValueAsStr)
- {
- if (String.IsNullOrEmpty(ValueAsStr))
- {
- return ValueAsStr;
- }
- else
- {
- ValueAsStr = ValueAsStr.Trim();
- var MissingChar = ValueAsStr.Length % 4;
- ValueAsStr = ValueAsStr.PadLeft(ValueAsStr.Length + 4 - MissingChar, '0');
- return Regex.Replace(ValueAsStr.Trim(), @"(.{4})", "$1 ").Trim();
- }
- }
-
- public static string ToUnsignedBin(this int value, bool Add_0b)
- {
- try
- {
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + UnsignedDecimalToBase((UInt32)value, 2).DoAutoPadLeft();
- }
- catch
- {
- return "?";
- }
- }
-
- public static string ToUnsignedBin(this uint value, bool Add_0b)
- {
- try
- {
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + UnsignedDecimalToBase(value, 2).DoAutoPadLeft();
- }
- catch
- {
- return "?";
- }
- }
-
- public static string ToUnsignedBin(this Int64 value)
- {
- try
- {
- return UnsignedDecimalToBase((UInt32)value, 2).DoAutoPadLeft();
- }
- catch
- {
- return "?";
- }
- }
-
- ///
- /// To string like 0bxxxxxxx depending of selection
- ///
- /// what value to show
- /// add 0b in front to indicate it is binary
- /// "true" if pad left front with all 0 for the actual value type else "false" only pad with up to 4 bits 0 to easy read
- ///
- public static string ToUnsignedBin(this UInt64 value, bool Add_0b, bool DoAutoPadLeft = true)
- {
- try
- {
- var ret = UnsignedDecimalToBase(value, 2);
- if (ret.Length == 0)
- {
- ret += "0"; // Always show 0 if no 1 is set
- }
- if (DoAutoPadLeft)
- {
- ret = ret.DoAutoPadLeft();
- }
- else
- {
- ret = ret.DoAutoSpcaePadEvery4Char();
- }
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + ret;
- }
- catch
- {
- return "?";
- }
- }
-
- public static string ToBin(this byte value, bool Add_0b)
- {
- try
- {
- return ((Add_0b) ? ValueInputAsBinaryFrontTag : "") + UnsignedDecimalToBase(value, 2).DoAutoPadLeft();
- }
- catch
- {
- return "?";
- }
- }
-
- public static string ToDec(this byte value)
- {
- return value.ToString("D3");
- }
-
- public static string ToHex(this byte value, bool Add_0x)
- {
- return DecimalToHex(value, 2, Add_0x);
- }
-
- public static string ToHex(this byte[] values, bool Add_0x, bool seperatorForCSV)
- {
- if (values == null) { return "Array is empty!"; }
- string ret = "";
- foreach (var value in values)
- {
- ret += (!String.IsNullOrEmpty(ret) ? (seperatorForCSV ? ColumnSeperatorCSV + " " : ", ") : "") + value.ToHex(Add_0x);
- }
- return ret;
- }
-
- public static string ToDec(this byte[] values)
- {
- if (values == null) { return "Array is empty!"; }
- string ret = "";
- foreach (var value in values)
- {
- ret += (!String.IsNullOrEmpty(ret) ? ", " : "") + value.ToDec();
- }
- return ret;
- }
-
- public static string ToBin(this byte[] values, bool Add_0b)
- {
- if (values == null) { return "Array is empty!"; }
- string ret = "";
- foreach (var value in values)
- {
- ret += (!String.IsNullOrEmpty(ret) ? ", " : "") + value.ToBin(Add_0b);
- }
- return ret;
- }
-
-
- public static string ToHex(this Int16 value, bool Add_0x)
- {
- return DecimalToHex(value, 4, Add_0x);
- }
-
- public static string ToHex(this UInt16 value, bool Add_0x)
- {
- return UnsignedDecimalToHex(value, 4, Add_0x);
- }
-
- public static string ToHex(this Int32 value, bool Add_0x)
- {
- return DecimalToHex(value, 8, Add_0x);
- }
-
- public static string ToHex(this UInt32 value, bool Add_0x)
- {
- return UnsignedDecimalToHex(value, 8, Add_0x);
- }
-
- public static string ToHex(this Int64 value, bool Add_0x)
- {
- return DecimalToHex(value, 16, Add_0x);
- }
-
- public static string ToHex(this UInt64 value, bool Add_0x)
- {
- return UnsignedDecimalToHex(value, 16, Add_0x);
- }
-
- public static string UnsignedDecimalToBase(this string iDec, int numbase)
- {
- try
- {
- return UnsignedDecimalToBase(Convert.ToUInt64(iDec), numbase);
- }
- catch
- {
- return "?";
- }
- }
-
- public static string UnsignedDecimalToBase(this UInt64 iDec, int numbase)
- {
- try
- {
- String strBin = "";
- int[] result = new int[64];
- int MaxBit = 64;
- for (; iDec > 0; iDec /= (UInt64)numbase)
- {
- int rem = (int)(iDec % Convert.ToUInt64(numbase));
- result[--MaxBit] = rem;
- }
- for (int i = 0; i < result.Length; i++)
- {
- if ((int)result.GetValue(i) >= base10)
- {
- strBin += cHexa[(int)result.GetValue(i) % base10];
- }
- else
- {
- strBin += result.GetValue(i);
- }
- }
- strBin = strBin.TrimStart(new char[] { '0' });
- return strBin;
- }
- catch
- {
- return "?";
- }
- }
-
- ///
- /// Converter string to a value (0x or 0b is not legal)
- ///
- ///
- ///
- ///
- public static UInt64 UnsignedBaseToDecimal(this String sBase, int numbase)
- {
- UInt64 result = 0;
- UInt64 b;
- UInt64 iProduct = 1;
- String sHexa = "";
- if (numbase > base10)
- {
- for (int i = 0; i < cHexa.Length; i++)
- {
- sHexa += cHexa.GetValue(i).ToString();
- }
- }
- for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= (UInt64)numbase)
- {
- String sValue = sBase[i].ToString();
- if (sValue.IndexOfAny(cHexa) >= 0)
- {
- b = (UInt64)iHexaNumeric[sHexa.IndexOf(sBase[i])];
- }
- else
- {
- b = (UInt64)sBase[i] - (UInt64)asciiDiff;
- }
- result += (b * iProduct);
- }
- return result;
- }
-
- ///
- /// Converter string to a value use 0x or 0b
- ///
- ///
- ///
- ///
- public static UInt64 ToUInt64(this String sBase)
- {
- UInt64 result = 0;
- UInt64 b;
- UInt64 iProduct = 1;
- String sHexa = "";
- int numbase;
- sBase = sBase.Trim().ToLower();
- if (sBase.StartsWith(ValueInputAsOctalFrontTag))
- {
- numbase = 8;
- sBase = sBase.Replace(ValueInputAsOctalFrontTag, "");
- }
- else if (sBase.StartsWith(ValueInputAsHexFrontTag))
- {
- numbase = 16;
- sBase = sBase.Replace(ValueInputAsHexFrontTag, "");
- }
- else if (sBase.StartsWith(ValueInputAsBinaryFrontTag))
- {
- numbase = 2;
- sBase = sBase.Replace(ValueInputAsBinaryFrontTag, "");
- }
- else
- {
- return Convert.ToUInt64(sBase);
- }
- if (numbase > base10)
- {
- for (int i = 0; i < cHexa.Length; i++)
- {
- sHexa += cHexa.GetValue(i).ToString();
- }
- }
- for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= (UInt64)numbase)
- {
- String sValue = sBase[i].ToString();
- if (sValue.IndexOfAny(cHexa) >= 0)
- {
- b = (UInt64)iHexaNumeric[sHexa.IndexOf(sBase[i])];
- }
- else
- {
- b = (UInt64)sBase[i] - (UInt64)asciiDiff;
- }
- result += (b * iProduct);
- }
- return result;
- }
-
- ///
- /// Converter string to a value use 0x or 0b
- ///
- ///
- ///
- ///
- public static Int64 ToInt64(this String sBase)
- {
- Int64 result = 0;
- Int64 b;
- Int64 iProduct = 1;
- String sHexa = "";
- int numbase;
- bool isNegative = false;
- sBase = sBase.Trim().ToLower();
- if (sBase.StartsWith("-"))
- {
- sBase = sBase.TrimStart('-');
- isNegative = true;
- }
- else if (sBase.StartsWith("+"))
- {
- sBase = sBase.TrimStart('+');
- }
- if (sBase.StartsWith(ValueInputAsOctalFrontTag))
- {
- numbase = 8;
- sBase = sBase.Replace(ValueInputAsOctalFrontTag, "");
- }
- else if (sBase.StartsWith(ValueInputAsHexFrontTag))
- {
- numbase = 16;
- sBase = sBase.Replace(ValueInputAsHexFrontTag, "");
- }
- else if (sBase.StartsWith(ValueInputAsBinaryFrontTag))
- {
- numbase = 2;
- sBase = sBase.Replace(ValueInputAsBinaryFrontTag, "");
- }
- else
- {
- return isNegative ? -Convert.ToInt64(sBase) : Convert.ToInt64(sBase);
- }
- if (numbase > base10)
- {
- for (int i = 0; i < cHexa.Length; i++)
- {
- sHexa += cHexa.GetValue(i).ToString();
- }
- }
- for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= (Int64)numbase)
- {
- String sValue = sBase[i].ToString();
- if (sValue.IndexOfAny(cHexa) >= 0)
- {
- b = (Int64)iHexaNumeric[sHexa.IndexOf(sBase[i])];
- }
- else
- {
- b = (Int64)sBase[i] - (Int64)asciiDiff;
- }
- result += (b * iProduct);
- }
- return isNegative ? -result : result;
- }
-
- public static UInt16 SwapByte(this UInt16 value)
- {
- return (UInt16)(value >> 8 | (value & 0xFF) << 8);
- }
-
- public static UInt64 SwapWord(this UInt64 value)
- {
- return (UInt64)(value >> 16 | (value & 0xFFFF) << 16);
- }
-
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/StringConvert.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/StringConvert.cs
deleted file mode 100644
index 27bc320f..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/StringConvert.cs
+++ /dev/null
@@ -1,474 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-
-namespace XYLEM.Base {
- #region ---- SMS Char Convert ----
-
- internal class UniCode {
- internal UInt32 Value { get; set; }
- internal char Ch {
- get { return (char)Value; }
- set { Value = (UInt32)value; }
- }
-
- internal string InfoTxt { get; set; }
- public UniCode(UInt32 value, string infoTxt) {
- Value = value;
- InfoTxt = infoTxt;
- }
-
- public override string ToString( ) {
- return String.Format( "\"{0}\"=0x{1x} ({2})", (char)Value, Value, InfoTxt );
- }
- }
-
- // Look at /DOC/Siemens MC55i GSM-charset.pdf
- // And http://www.unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT
- static class StringConvertToSMSClass {
- readonly static Dictionary ConvTable = new Dictionary( ){
- //{ new Byte[]{0x00}, new UniCode( 0x0040 , "COMMERCIAL AT") }, TMO NOT IN USE
- { new Byte[]{0x40}, new UniCode( 0x0040, "@ Converted to \"INVERTED EXCLAMATION MARK\", Device then TX \"0x00\"") },
- //{ new Byte[]{0x40}, new UniCode( 0x00A1 , "INVERTED EXCLAMATION MARK") }, TMO NOT IN USE
- { new Byte[]{0x21,0x2A}, new UniCode( 0x00A1 , "INVERTED EXCLAMATION MARK to \"!*\"") },
- { new Byte[]{0x00}, new UniCode( 0x0000 , "NULL (see note above)") },
- { new Byte[]{0x01}, new UniCode( 0x00A3 , "POUND SIGN") },
- { new Byte[]{0x02}, new UniCode( 0x0024 , "DOLLAR SIGN") },
- { new Byte[]{0x03}, new UniCode( 0x00A5 , "YEN SIGN") },
- { new Byte[]{0x04}, new UniCode( 0x00E8 , "LATIN SMALL LETTER E WITH GRAVE") },
- { new Byte[]{0x05}, new UniCode( 0x00E9 , "LATIN SMALL LETTER E WITH ACUTE") },
- { new Byte[]{0x06}, new UniCode( 0x00F9 , "LATIN SMALL LETTER U WITH GRAVE") },
- { new Byte[]{0x07}, new UniCode( 0x00EC , "LATIN SMALL LETTER I WITH GRAVE") },
- { new Byte[]{0x08}, new UniCode( 0x00F2 , "LATIN SMALL LETTER O WITH GRAVE") },
- { new Byte[]{0x09}, new UniCode( 0x00E7 , "LATIN SMALL LETTER C WITH CEDILLA") },
- { new Byte[]{0x09}, new UniCode( 0x00C7 , "LATIN CAPITAL LETTER C WITH CEDILLA (see note above)") },
- { new Byte[]{0x0A}, new UniCode( 0x000A , "LINE FEED") },
- { new Byte[]{0x0B}, new UniCode( 0x00D8 , "LATIN CAPITAL LETTER O WITH STROKE") },
- { new Byte[]{0x0C}, new UniCode( 0x00F8 , "LATIN SMALL LETTER O WITH STROKE") },
- { new Byte[]{0x0D}, new UniCode( 0x000D , "CARRIAGE RETURN") },
- { new Byte[]{0x0E}, new UniCode( 0x00C5 , "LATIN CAPITAL LETTER A WITH RING ABOVE") },
- { new Byte[]{0x0F}, new UniCode( 0x00E5 , "LATIN SMALL LETTER A WITH RING ABOVE") },
- { new Byte[]{0x10}, new UniCode( 0x0394 , "GREEK CAPITAL LETTER DELTA") },
- { new Byte[]{0x11}, new UniCode( 0x005F , "LOW LINE") },
- { new Byte[]{0x12}, new UniCode( 0x03A6 , "GREEK CAPITAL LETTER PHI") },
- { new Byte[]{0x13}, new UniCode( 0x0393 , "GREEK CAPITAL LETTER GAMMA") },
- { new Byte[]{0x14}, new UniCode( 0x039B , "GREEK CAPITAL LETTER LAMDA") },
- { new Byte[]{0x15}, new UniCode( 0x03A9 , "GREEK CAPITAL LETTER OMEGA") },
- { new Byte[]{0x16}, new UniCode( 0x03A0 , "GREEK CAPITAL LETTER PI") },
- { new Byte[]{0x17}, new UniCode( 0x03A8 , "GREEK CAPITAL LETTER PSI") },
- { new Byte[]{0x18}, new UniCode( 0x03A3 , "GREEK CAPITAL LETTER SIGMA") },
- { new Byte[]{0x19}, new UniCode( 0x0398 , "GREEK CAPITAL LETTER THETA") },
- { new Byte[]{0x1A}, new UniCode( 0x039E , "GREEK CAPITAL LETTER XI") },
- { new Byte[]{0x1B}, new UniCode( 0x00A0 , "ESCAPE TO EXTENSION TABLE (or displayed as NBSP, see note above)") },
- { new Byte[]{0x1B,0x0A}, new UniCode( 0x000C , "FORM FEED") },
- { new Byte[]{0x1B,0x14}, new UniCode( 0x005E , "CIRCUMFLEX ACCENT") },
- { new Byte[]{0x1B,0x28}, new UniCode( 0x007B , "LEFT CURLY BRACKET") },
- { new Byte[]{0x1B,0x29}, new UniCode( 0x007D , "RIGHT CURLY BRACKET") },
- { new Byte[]{0x1B,0x2F}, new UniCode( 0x005C , "REVERSE SOLIDUS") },
- { new Byte[]{0x1B,0x3C}, new UniCode( 0x005B , "LEFT SQUARE BRACKET") },
- { new Byte[]{0x1B,0x3D}, new UniCode( 0x007E , "TILDE") },
- { new Byte[]{0x1B,0x3E}, new UniCode( 0x005D , "RIGHT SQUARE BRACKET") },
- { new Byte[]{0x1B,0x40}, new UniCode( 0x007C , "VERTICAL LINE") },
- { new Byte[]{0x1B,0x65}, new UniCode( 0x20AC , "EURO SIGN") },
- { new Byte[]{0x1C}, new UniCode( 0x00C6 , "LATIN CAPITAL LETTER AE") },
- { new Byte[]{0x1D}, new UniCode( 0x00E6 , "LATIN SMALL LETTER AE") },
- { new Byte[]{0x1E}, new UniCode( 0x00DF , "LATIN SMALL LETTER SHARP S (German)") },
- { new Byte[]{0x1F}, new UniCode( 0x00C9 , "LATIN CAPITAL LETTER E WITH ACUTE") },
- { new Byte[]{0x20}, new UniCode( 0x0020 , "SPACE") },
- { new Byte[]{0x21}, new UniCode( 0x0021 , "EXCLAMATION MARK") },
- { new Byte[]{0x22}, new UniCode( 0x0022 , "QUOTATION MARK") },
- { new Byte[]{0x23}, new UniCode( 0x0023 , "NUMBER SIGN") },
- { new Byte[]{0x24}, new UniCode( 0x00A4 , "CURRENCY SIGN") },
- { new Byte[]{0x25}, new UniCode( 0x0025 , "PERCENT SIGN") },
- { new Byte[]{0x26}, new UniCode( 0x0026 , "AMPERSAND") },
- { new Byte[]{0x27}, new UniCode( 0x0027 , "APOSTROPHE") },
- { new Byte[]{0x28}, new UniCode( 0x0028 , "LEFT PARENTHESIS") },
- { new Byte[]{0x29}, new UniCode( 0x0029 , "RIGHT PARENTHESIS") },
- { new Byte[]{0x2A}, new UniCode( 0x002A , "ASTERISK") },
- { new Byte[]{0x2B}, new UniCode( 0x002B , "PLUS SIGN") },
- { new Byte[]{0x2C}, new UniCode( 0x002C , "COMMA") },
- { new Byte[]{0x2D}, new UniCode( 0x002D , "HYPHEN-MINUS") },
- { new Byte[]{0x2E}, new UniCode( 0x002E , "FULL STOP") },
- { new Byte[]{0x2F}, new UniCode( 0x002F , "SOLIDUS") },
- { new Byte[]{0x30}, new UniCode( 0x0030 , "DIGIT ZERO") },
- { new Byte[]{0x31}, new UniCode( 0x0031 , "DIGIT ONE") },
- { new Byte[]{0x32}, new UniCode( 0x0032 , "DIGIT TWO") },
- { new Byte[]{0x33}, new UniCode( 0x0033 , "DIGIT THREE") },
- { new Byte[]{0x34}, new UniCode( 0x0034 , "DIGIT FOUR") },
- { new Byte[]{0x35}, new UniCode( 0x0035 , "DIGIT FIVE") },
- { new Byte[]{0x36}, new UniCode( 0x0036 , "DIGIT SIX") },
- { new Byte[]{0x37}, new UniCode( 0x0037 , "DIGIT SEVEN") },
- { new Byte[]{0x38}, new UniCode( 0x0038 , "DIGIT EIGHT") },
- { new Byte[]{0x39}, new UniCode( 0x0039 , "DIGIT NINE") },
- { new Byte[]{0x3A}, new UniCode( 0x003A , "COLON") },
- { new Byte[]{0x3B}, new UniCode( 0x003B , "SEMICOLON") },
- { new Byte[]{0x3C}, new UniCode( 0x003C , "LESS-THAN SIGN") },
- { new Byte[]{0x3D}, new UniCode( 0x003D , "EQUALS SIGN") },
- { new Byte[]{0x3E}, new UniCode( 0x003E , "GREATER-THAN SIGN") },
- { new Byte[]{0x3F}, new UniCode( 0x003F , "QUESTION MARK") },
-
- { new Byte[]{0x41}, new UniCode( 0x0041 , "LATIN CAPITAL LETTER A") },
- { new Byte[]{0x41}, new UniCode( 0x0391 , "GREEK CAPITAL LETTER ALPHA") },
- { new Byte[]{0x42}, new UniCode( 0x0042 , "LATIN CAPITAL LETTER B") },
- { new Byte[]{0x42}, new UniCode( 0x0392 , "GREEK CAPITAL LETTER BETA") },
- { new Byte[]{0x43}, new UniCode( 0x0043 , "LATIN CAPITAL LETTER C") },
- { new Byte[]{0x44}, new UniCode( 0x0044 , "LATIN CAPITAL LETTER D") },
- { new Byte[]{0x45}, new UniCode( 0x0045 , "LATIN CAPITAL LETTER E") },
- { new Byte[]{0x45}, new UniCode( 0x0395 , "GREEK CAPITAL LETTER EPSILON") },
- { new Byte[]{0x46}, new UniCode( 0x0046 , "LATIN CAPITAL LETTER F") },
- { new Byte[]{0x47}, new UniCode( 0x0047 , "LATIN CAPITAL LETTER G") },
- { new Byte[]{0x48}, new UniCode( 0x0048 , "LATIN CAPITAL LETTER H") },
- { new Byte[]{0x48}, new UniCode( 0x0397 , "GREEK CAPITAL LETTER ETA") },
- { new Byte[]{0x49}, new UniCode( 0x0049 , "LATIN CAPITAL LETTER I") },
- { new Byte[]{0x49}, new UniCode( 0x0399 , "GREEK CAPITAL LETTER IOTA") },
- { new Byte[]{0x4A}, new UniCode( 0x004A , "LATIN CAPITAL LETTER J") },
- { new Byte[]{0x4B}, new UniCode( 0x004B , "LATIN CAPITAL LETTER K") },
- { new Byte[]{0x4B}, new UniCode( 0x039A , "GREEK CAPITAL LETTER KAPPA") },
- { new Byte[]{0x4C}, new UniCode( 0x004C , "LATIN CAPITAL LETTER L") },
- { new Byte[]{0x4D}, new UniCode( 0x004D , "LATIN CAPITAL LETTER M") },
- { new Byte[]{0x4D}, new UniCode( 0x039C , "GREEK CAPITAL LETTER MU") },
- { new Byte[]{0x4E}, new UniCode( 0x004E , "LATIN CAPITAL LETTER N") },
- { new Byte[]{0x4E}, new UniCode( 0x039D , "GREEK CAPITAL LETTER NU") },
- { new Byte[]{0x4F}, new UniCode( 0x004F , "LATIN CAPITAL LETTER O") },
- { new Byte[]{0x4F}, new UniCode( 0x039F , "GREEK CAPITAL LETTER OMICRON") },
- { new Byte[]{0x50}, new UniCode( 0x0050 , "LATIN CAPITAL LETTER P") },
- { new Byte[]{0x50}, new UniCode( 0x03A1 , "GREEK CAPITAL LETTER RHO") },
- { new Byte[]{0x51}, new UniCode( 0x0051 , "LATIN CAPITAL LETTER Q") },
- { new Byte[]{0x52}, new UniCode( 0x0052 , "LATIN CAPITAL LETTER R") },
- { new Byte[]{0x53}, new UniCode( 0x0053 , "LATIN CAPITAL LETTER S") },
- { new Byte[]{0x54}, new UniCode( 0x0054 , "LATIN CAPITAL LETTER T") },
- { new Byte[]{0x54}, new UniCode( 0x03A4 , "GREEK CAPITAL LETTER TAU") },
- { new Byte[]{0x55}, new UniCode( 0x0055 , "LATIN CAPITAL LETTER U") },
- { new Byte[]{0x56}, new UniCode( 0x0056 , "LATIN CAPITAL LETTER V") },
- { new Byte[]{0x57}, new UniCode( 0x0057 , "LATIN CAPITAL LETTER W") },
- { new Byte[]{0x58}, new UniCode( 0x0058 , "LATIN CAPITAL LETTER X") },
- { new Byte[]{0x58}, new UniCode( 0x03A7 , "GREEK CAPITAL LETTER CHI") },
- { new Byte[]{0x59}, new UniCode( 0x0059 , "LATIN CAPITAL LETTER Y") },
- { new Byte[]{0x59}, new UniCode( 0x03A5 , "GREEK CAPITAL LETTER UPSILON") },
- { new Byte[]{0x5A}, new UniCode( 0x005A , "LATIN CAPITAL LETTER Z") },
- { new Byte[]{0x5A}, new UniCode( 0x0396 , "GREEK CAPITAL LETTER ZETA") },
- { new Byte[]{0x5B}, new UniCode( 0x00C4 , "LATIN CAPITAL LETTER A WITH DIAERESIS") },
- { new Byte[]{0x5C}, new UniCode( 0x00D6 , "LATIN CAPITAL LETTER O WITH DIAERESIS") },
- { new Byte[]{0x5D}, new UniCode( 0x00D1 , "LATIN CAPITAL LETTER N WITH TILDE") },
- { new Byte[]{0x5E}, new UniCode( 0x00DC , "LATIN CAPITAL LETTER U WITH DIAERESIS") },
- { new Byte[]{0x5F}, new UniCode( 0x00A7 , "SECTION SIGN") },
- { new Byte[]{0x60}, new UniCode( 0x00BF , "INVERTED QUESTION MARK") },
- { new Byte[]{0x61}, new UniCode( 0x0061 , "LATIN SMALL LETTER A") },
- { new Byte[]{0x62}, new UniCode( 0x0062 , "LATIN SMALL LETTER B") },
- { new Byte[]{0x63}, new UniCode( 0x0063 , "LATIN SMALL LETTER C") },
- { new Byte[]{0x64}, new UniCode( 0x0064 , "LATIN SMALL LETTER D") },
- { new Byte[]{0x65}, new UniCode( 0x0065 , "LATIN SMALL LETTER E") },
- { new Byte[]{0x66}, new UniCode( 0x0066 , "LATIN SMALL LETTER F") },
- { new Byte[]{0x67}, new UniCode( 0x0067 , "LATIN SMALL LETTER G") },
- { new Byte[]{0x68}, new UniCode( 0x0068 , "LATIN SMALL LETTER H") },
- { new Byte[]{0x69}, new UniCode( 0x0069 , "LATIN SMALL LETTER I") },
- { new Byte[]{0x6A}, new UniCode( 0x006A , "LATIN SMALL LETTER J") },
- { new Byte[]{0x6B}, new UniCode( 0x006B , "LATIN SMALL LETTER K") },
- { new Byte[]{0x6C}, new UniCode( 0x006C , "LATIN SMALL LETTER L") },
- { new Byte[]{0x6D}, new UniCode( 0x006D , "LATIN SMALL LETTER M") },
- { new Byte[]{0x6E}, new UniCode( 0x006E , "LATIN SMALL LETTER N") },
- { new Byte[]{0x6F}, new UniCode( 0x006F , "LATIN SMALL LETTER O") },
- { new Byte[]{0x70}, new UniCode( 0x0070 , "LATIN SMALL LETTER P") },
- { new Byte[]{0x71}, new UniCode( 0x0071 , "LATIN SMALL LETTER Q") },
- { new Byte[]{0x72}, new UniCode( 0x0072 , "LATIN SMALL LETTER R") },
- { new Byte[]{0x73}, new UniCode( 0x0073 , "LATIN SMALL LETTER S") },
- { new Byte[]{0x74}, new UniCode( 0x0074 , "LATIN SMALL LETTER T") },
- { new Byte[]{0x75}, new UniCode( 0x0075 , "LATIN SMALL LETTER U") },
- { new Byte[]{0x76}, new UniCode( 0x0076 , "LATIN SMALL LETTER V") },
- { new Byte[]{0x77}, new UniCode( 0x0077 , "LATIN SMALL LETTER W") },
- { new Byte[]{0x78}, new UniCode( 0x0078 , "LATIN SMALL LETTER X") },
- { new Byte[]{0x79}, new UniCode( 0x0079 , "LATIN SMALL LETTER Y") },
- { new Byte[]{0x7A}, new UniCode( 0x007A , "LATIN SMALL LETTER Z") },
- { new Byte[]{0x7B}, new UniCode( 0x00E4 , "LATIN SMALL LETTER A WITH DIAERESIS") },
- { new Byte[]{0x7C}, new UniCode( 0x00F6 , "LATIN SMALL LETTER O WITH DIAERESIS") },
- { new Byte[]{0x7D}, new UniCode( 0x00F1 , "LATIN SMALL LETTER N WITH TILDE") },
- { new Byte[]{0x7E}, new UniCode( 0x00FC , "LATIN SMALL LETTER U WITH DIAERESIS") },
- { new Byte[]{0x7F}, new UniCode( 0x00E0 , "LATIN SMALL LETTER A WITH GRAVE") },
- };
-
- readonly static string[][] ConvertCh = new string[][]{
- new string[]{ "\r", ""},
- new string[]{ Environment.NewLine, "\n"},
- };
-
- internal static string RemoveIllegalATCh(this string value) {
- string ret = value;
- foreach (string[] replaceTxt in ConvertCh) {
- if (!String.IsNullOrEmpty( replaceTxt[ 0 ] )) {
- ret = ret.Replace( replaceTxt[ 0 ], "" );
- }
- }
- return ret;
- }
-
- internal static string ReplaceIllegalATCh(this string value) {
- string ret = value;
- foreach (string[] replaceTxt in ConvertCh) {
- if (!String.IsNullOrEmpty( replaceTxt[ 0 ] )) {
- ret = ret.Replace( replaceTxt[ 0 ], replaceTxt[ 1 ] );
- }
- }
- return ret;
- }
-
- internal static UniCode[] GetUniCodes(this byte[] data) {
- try {
- List list = new List( );
- for (int offset = 0; offset < data.Length; offset++) {
- bool found = false;
- // check if byte sequens is in convert table
- foreach (var code in ConvTable) {
- if (data[ offset ] == code.Key.First( )) {
- if (code.Key.Length == 1) {
- list.Add( code.Value );
- found = true;
- break;
- // Check if it is a combination of to bytes
- } else if ((code.Key.Length == 2) && (offset + 1 < data.Length) && (data[ offset + 1 ] == code.Key[ 1 ])) {
- offset++;
- list.Add( code.Value );
- found = true;
- break;
- }
- }
- }
- if (!found) {
- list.Add( new UniCode( data[ offset ], "(The Same)" ) );
- }
- }
- return list.ToArray( );
- } catch (Exception ex) {
- throw new Exception( "Unable to convert data to " + typeof( UniCode ).ToString( ), ex );
- }
- }
-
-
- internal static string ToPcChFromSmsTxt(this byte[] data) {
- string txt = "";
- try {
- for (int offset = 0; offset < data.Length; offset++) {
- bool found = false;
- // check if byte sequens is in convert table
- foreach (var code in ConvTable) {
- if (data[ offset ] == code.Key.First( )) {
- if (code.Key.Length == 1) {
- txt += code.Value.Ch;
- found = true;
- break;
- // Check if it is a combination of to bytes
- } else if ((code.Key.Length == 2) && (offset + 1 < data.Length) && (data[ offset + 1 ] == code.Key[ 1 ])) {
- offset++;
- txt += code.Value.Ch;
- found = true;
- break;
- }
- }
- }
- if (!found) {
- txt += (char)data[ offset ];
- }
- }
- return txt.Replace( "\n", Environment.NewLine );
- } catch (Exception ex) {
- throw new Exception( "Unable to convert char after this \"" + txt + "\"", ex );
- }
- }
-
- internal static byte[] ToByteFromPcChSMS(this String Txt) {
- List ret = new List( );
- try {
- foreach (var ch in Txt.ReplaceIllegalATCh( )) {
- bool found = false;
- // check if byte sequens is in convert table
- foreach (var code in ConvTable) {
- if (ch == code.Value.Ch) {
- ret.AddRange( code.Key );
- found = true;
- break;
- }
- }
- if (!found) {
- ret.AddRange( ASCIIEncoding.Default.GetBytes( ch.ToString( ) ) );
- }
- }
- return ret.ToArray( );
- } catch (Exception ex) {
- throw new Exception( "Unable to convert char after this \"" + (ret.Count > 0 ? ret.ToArray( ).ToPcChFromSmsTxt( ) : "None, Is Empty!!") + "\"", ex );
- }
- }
-
- internal static string ToStringFromPcChSMS(this String Txt) {
- string ret = "";
- try {
- foreach (var ch in Txt.ReplaceIllegalATCh( )) {
- bool found = false;
- // check if byte sequens is in convert table
- foreach (var code in ConvTable) {
- if (ch == code.Value.Ch) {
- foreach (var cdByte in code.Key) {
- ret += (char)cdByte;
- }
- found = true;
- break;
- }
- }
- if (!found) {
- foreach (var cdByte in ASCIIEncoding.Default.GetBytes( ch.ToString( ) )) {
- ret += (char)cdByte;
- }
- }
- }
- return ret;
- } catch (Exception ex) {
- throw new Exception( "Unable to convert char after this \"" + ret + "\"", ex );
- }
- }
-
-
- #region ---- To String ----
- private static string ToInfoTxt(byte[] data, UniCode unicode) {
- return string.Format( "SMS Ch = 0x{0x}{1} \t\t unicode Ch = {2}",
- data.First( ), // 0
- ((data.Length > 1) ? string.Format( "0x{0x}", data[ 0 ] ) : ""), //1
- unicode.ToString( ) ); // 2
- }
-
- public static string GetInfoTable( ) {
- string txt = "";
- foreach (var data in ConvTable) {
- txt += ToInfoTxt( data.Key, data.Value ) + Environment.NewLine;
- }
- return txt;
- }
- #endregion
- }
-
- #endregion
-
- internal static class StringConvert {
- ///
- /// Combine string array to a single text
- ///
- /// items that is null or empty will be removed
- /// inset string to join between to items (set to null if none)
- ///
- internal static string ToSingleString(this string[] array, string joinWithText) {
- string ret = "";
- if ((array != null) && (array.Length > 0)) {
- ret = array.Select( item => (String.IsNullOrEmpty( item ) ? "" : item) ).Aggregate( (current, next) => current + ((joinWithText != null) ? joinWithText : "") + next );
- }
- return ret;
- }
-
-
- ///
- /// Combine string array to a single text
- ///
- /// items that is null or empty will be removed
- /// new line or a single space is use to join between to item
- ///
- internal static string ToSingleString(this string[] array, bool addNewLine) {
- return ToSingleString( array, (addNewLine ? Environment.NewLine : " ") );
- }
-
-
- internal static string ToSingleString(this List list, bool addNewLine) {
- return ToSingleString( list.ToArray( ), addNewLine );
- }
-
- internal static string ToSingleString(this IEnumerable list, bool addNewLine) {
- return ToSingleString( list.ToArray( ), addNewLine );
- }
-
- internal static byte[] ToBytes(this string value) {
- return ASCIIEncoding.Default.GetBytes( value );
- }
-
- ///
- /// Convert PC string to at AT OK string (No new line)
- ///
- ///
- ///
- internal static byte[] ToBytesOkATCh(this string value) {
- return ASCIIEncoding.Default.GetBytes( value.RemoveIllegalATCh( ) );
- }
-
- internal static string ToPcCh(this byte[] value) {
- return ASCIIEncoding.Default.GetString( value );
- }
-
- ///
- /// Convert and remove all none printable char
- ///
- ///
- ///
- internal static string ToPcPrintableCh(this byte[] value) {
- return ToPcPrintableCh( value as IEnumerable );
- }
-
- ///
- /// Convert and remove all none printable char
- ///
- ///
- ///
- internal static string ToPcPrintableCh(this IEnumerable value) {
- string ret = "";
- if (value != null) {
- foreach (var b in value) {
- if (b >= 32) {
- ret += ASCIIEncoding.Default.GetString( new byte[] { b } );
- } else if (b == '\r') {
- ret += Environment.NewLine;
- }
- }
- }
- return ret;
- }
-
- internal static string ToPcChFromATCh(this byte[] value) {
- return ASCIIEncoding.Default.GetString( value ).Replace( "\r", "" ).Replace( "\n", Environment.NewLine );
- }
-
- ///
- /// Get all digit sequence in a string and return it as strings
- ///
- ///
- ///
- internal static string[] GetDecValues(this string values) {
- //http://regexhero.net/tester/
- //COM8.45 78.463 -676,67 6.454.54.45,4545,4545 (Selecting only the values)
- //
- MatchCollection matches = Regex.Matches( values, @"[-]|[.]|[-.]|[0-9][0-9]*[.]|[,]*[0-9]+" ); // ([0,1]|([0,1]?\.[0-9]+)) or "^[0-9]*[.]?[0-9]+$"
- if (matches.Count != 0) {
- List ret = new List( );
- foreach (Match value in matches) {
- ret.Add( value.Value );
- }
- return ret.ToArray( );
- }
- return null;
- }
-
- ///
- /// Get first digit sequence in a string and return it as strings
- ///
- ///
- ///
- internal static string GetDecValue(this string value) {
- string[] values = GetDecValues( value );
- if (values != null) {
- return values.First( );
- }
- return null;
- }
-
- internal static string RemoveZeroTerm(this string value) {
- if (!string.IsNullOrEmpty( value ) && value.Contains( '\0' )) {
- return value.Remove( value.IndexOf( '\0' ) );
- }
- return value;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/XML/XMLStringClass.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/XML/XMLStringClass.cs
deleted file mode 100644
index 69fb1e0a..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/XML/XMLStringClass.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-
-namespace XYLEM.Base.XML
-{
- public static class XMLStringClass
- {
- public enum XMLVersion
- {
- V1_0,
- V1_1
- }
-
- ///
- /// Strips non-printable ascii characters
- /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
- ///
- ///
- ///
- public static string StripIllegalXMLChars(this string txtToClean)
- {
- return StripIllegalXMLChars(txtToClean, XMLVersion.V1_1);
- }
-
- ///
- /// Strips non-printable ascii characters
- /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
- /// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
- ///
- ///
- ///
- ///
- public static string StripIllegalXMLChars(this string txtToClean, XMLVersion version)
- {
- try
- {
- string pattern = String.Empty;
- txtToClean = txtToClean.
- Replace("&", "&").
- Replace("<", "<").
- Replace(">", ">").
- Replace("\"", """).
- Replace("'", "'").
- Replace("\r", "
").
- Replace("\n", "
");
- switch (version)
- {
- case XMLVersion.V1_0:
- pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|7F|8[0-46-9A-F]9[0-9A-F])";
- break;
- case XMLVersion.V1_1:
- pattern = @"#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF])";
- break;
- }
-
- Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
- if (regex.IsMatch(txtToClean))
- {
- txtToClean = regex.Replace(txtToClean, String.Empty);
- }
- if (txtToClean.Contains('\0'))
- {
- txtToClean = txtToClean.Remove(txtToClean.IndexOf('\0'));
- }
- if (txtToClean.Contains((char)0x1E))
- {
- txtToClean = txtToClean.Replace((char)0x1E, ' ');
- }
- {
- // Replace any character that has survived this done before
- // Replace illegal character in XML documents with blank
- // See here for reference http://www.w3.org/TR/xml/#charsets
- txtToClean = Regex.Replace(txtToClean, "[\x00-\x08\x0B\x0C\x0E-\x1F]", String.Empty, RegexOptions.Compiled);
- }
- return txtToClean;
- }
- catch (Exception ex)
- {
- throw new Exception("Error in XMLFileIOClass and StripIllegalXMLChars() " + (txtToClean != null ? " txtToClean = " + txtToClean.ToString() : "txtToClean is null"), ex);
- }
- }
-
- ///
- /// reinset non-printable ascii characters
- /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
- ///
- ///
- ///
- public static string ReinsetIllegalXMLChars(this string txtToClean)
- {
- return ReinsetIllegalXMLChars(txtToClean, XMLVersion.V1_1);
- }
-
- ///
- /// reinset non-printable ascii characters
- /// Refer to http://www.w3.org/TR/xml11/#charsets for XML 1.1
- /// Refer to http://www.w3.org/TR/2006/REC-xml-20060816/#charsets for XML 1.0
- ///
- ///
- ///
- ///
- public static string ReinsetIllegalXMLChars(string txtToReinset, XMLVersion version)
- {
- try
- {
- string pattern = String.Empty;
- txtToReinset = txtToReinset.
- Replace("&", "&").
- Replace("<", "<").
- Replace(">", ">").
- Replace(""", "\"").
- Replace("'", "'").
- Replace("
", "\r").
- Replace("
", "\n");
- return txtToReinset;
- }
- catch (Exception ex)
- {
- throw new Exception("Error in XMLFileIOClass and StripIllegalXMLChars() " + (txtToReinset != null ? " txtToClean = " + txtToReinset.ToString() : "txtToClean is null"), ex);
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/XML/XMLWriteFuncClass.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Base/XML/XMLWriteFuncClass.cs
deleted file mode 100644
index 4f7d60be..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Base/XML/XMLWriteFuncClass.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Xml.Serialization;
-using System.Xml;
-using System.Net.Sockets;
-using XYLEM.Base.Files;
-
-namespace XYLEM.Base.XML
-{
- internal class XMLWriteFuncClass
- {
- ///
- /// Writes the given object instance to an XML file.
- /// Only Public properties and variables will be written to the file. These can be any type though, even other classes.
- /// If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.
- /// Object type must have a parameterless constructor.
- ///
- /// The type of object being written to the file.
- /// The file path to write the object instance to.
- /// The object instance to write to the file.
- /// If false the file will be overwritten if it already exists. If true the contents will be appended to the file.
- public static void WriteToXmlFile(string filePath, T objectToWrite, bool append = false) where T : new()
- {
- // from https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
- TextWriter writer = null;
- try
- {
- writer = new StreamWriter(filePath, append);
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- xmlSerializer.Serialize(writer, objectToWrite);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(XMLWriteFuncClass).ToString(), ProgramLogCSVFileClass.GetCurrentStaticMethod()));
- }
- finally
- {
- if (writer != null)
- writer.Close();
- }
- }
-
- ///
- /// Reads an object instance from an XML file.
- /// Object type must have a parameterless constructor.
- ///
- /// The type of object to read from the file.
- /// The file path to read the object instance from.
- /// Returns a new instance of the object read from the XML file.
- public static T ReadFromXmlFile(string filePath) where T : new()
- {
- // from https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
-
- TextReader reader = null;
- try
- {
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- reader = new StreamReader(filePath);
- return (T)xmlSerializer.Deserialize(reader);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(XMLWriteFuncClass).ToString(), ProgramLogCSVFileClass.GetCurrentStaticMethod()));
- }
- finally
- {
- if (reader != null)
- reader.Close();
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/DeviceExceptionData.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/DeviceExceptionData.cs
deleted file mode 100644
index e8895bc2..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/DeviceExceptionData.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Communication
-{
- ///
- /// Class to contain data for a exception
- ///
- public struct DeviceExceptionData
- {
- ///
- /// Special function has to be done when this com
- /// https://mjksvn.world.fluidtechnology.net:4443/svn/development/- MJK Standards/- Communication protocols/Modbus/Modbus Specifications.doc
- /// "2.2.1 MODBUS Exception Responses:"
- ///
- public enum SpecialType
- {
- DriverError = -1,
- WaitForReset = 14, // Wait x sec befor next tx
- WaitForFinishMax5s = 252, // Wait Exception OK (max 5s)
- OnlyAnInforead = 253, // Used internal to only make an info read about data to read / write (Not intentet for normal TX)
- WaitForFinishMax60s = 254, // Wait Exception OK (max 60s)
- WaitForFinishMax5Min = 255, // Wait Exception OK (max 5min)
- }
-
- ///
- /// Exception No.
- ///
- private int _ExcNo;
-
- ///
- /// Exception Info
- ///
- private string _Info;
- ///
- /// Preload All data.. used when init data array
- ///
- ///
- ///
- public DeviceExceptionData(int excNo, string info)
- {
- this._ExcNo = excNo;
- this._Info = info;
- }
-
- ///
- /// Exception code number
- ///
- public int ExcNo
- {
- get { return _ExcNo; }
- set { _ExcNo = value; }
- }
-
- ///
- /// Info text to exception no.
- ///
- public String Info
- {
- get { return _Info; }
- set { _Info = value; }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/FuncTypes.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/FuncTypes.cs
deleted file mode 100644
index 00e940f5..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/FuncTypes.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Communication
-{
- public enum Func_RD : int
- {
- NoSupport = -1,
- No3 = 3,
- No4 = 4,
- };
-
- public enum Func_WR : int
- {
- NoSupport = -1,
- No15 = 15,
- No16 = 16,
- };
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ModbusCom.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ModbusCom.cs
deleted file mode 100644
index e33716aa..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ModbusCom.cs
+++ /dev/null
@@ -1,634 +0,0 @@
-using MagFlux6200_metrology_reg_list;
-using XYLEM.Device;
-using XYLEM.Communication.ValueEncoders;
-using System;
-using System.Collections.Generic;
-using System.IO.Ports;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Numerics;
-using System.Xml.Linq;
-using static System.Net.Mime.MediaTypeNames;
-using XYLEM.Base;
-using System.Text.RegularExpressions;
-using System.Data;
-using System.Security.Policy;
-using System.Threading;
-
-namespace XYLEM.Communication
-{
- ///
- /// Modbus read and write return data type
- ///
- ///
- public class ModbusDataResult where T : IComparable, IFormattable, IComparable, IEquatable/*, IConvertible is not compatible with BigInteger*/
- {
- ///
- /// Has the task succeded
- ///
- internal bool IsOkay;
-
- ///
- /// Data readed from or written to device
- ///
- internal T Data;
-
- ///
- /// What device value info for Data
- ///
- internal Device_value Info;
-
- public ModbusDataResult(bool IsOkay, T DataRW, Device_value Info)
- {
- this.IsOkay = IsOkay;
- this.Data = DataRW;
- this.Info = Info;
- }
- }
-
- public class ModbusDataRequest
- {
- ///
- /// Has the task succeded
- ///
- internal bool IsOkay;
-
- ///
- /// Data for return read in from device
- ///
- internal object Data;
-
- ///
- /// What device value info for Data
- ///
- internal Device_value Info;
-
- public ModbusDataRequest(bool IsOkay, object returnReadIn, Device_value Info)
- {
- this.IsOkay = IsOkay;
- this.Data = returnReadIn;
- this.Info = Info;
- }
- }
-
-
- public class ModbusCom
- {
- const int ch_lng_dv = -15;
- const int ch_lng_Version = -3;
- const int ch_lng_MD_adr = -7;
- const int dig_value = 10;
-
- ///
- /// Min delay before a DUT message is expected faild
- // Is 1s for testing out that default modbus settings com don't fail
- ///
- private readonly int _MaxWaitForComRX_ms = 1000;
-
- ///
- /// Message ended detection delay
- /// Min delay before bytes count received and haven't changed result in modbus message ended
- /// The 50ms is found to be needed when using DUT RS485 and modbus messages is transparent to Metrology
- ///
- private readonly int _DelayBetweenRxByteCheck_ms = 50;
- SerialPort _serial;
- int _retry;
-
-
- public int MsgErrorCount { get; private set; }
- public int MsgCount { get; private set; }
-
- public void ResetMsgCounters()
- {
- MsgCount = MsgErrorCount = 0;
- }
-
- public ModbusCom(string serial_port, int baudRate, Parity parity, int retry = 3)
- {
- ResetMsgCounters();
- this._serial = new SerialPort();
- _serial.PortName = serial_port;
- _serial.BaudRate = baudRate;
- _serial.Parity= parity;
- _serial.DtrEnable = _serial.RtsEnable = true; // Need to be on for Application USB Serial com to detect a connection
- //_serial.Handshake = Handshake.RequestToSendXOnXOff;
- _serial.ReadTimeout = 100;
- if (!_serial.IsOpen)
- {
- _serial.Open();
- }
- _retry=retry;
- Console.WriteLine($"Serial connection {_serial.PortName}, {_serial.BaudRate}, {_serial.Parity}, retry = {_retry}");
- }
-
-
- ///
- /// Is communication port connected
- ///
- ///
- public bool IsConnected()
- {
- return _serial.IsOpen;
- }
-
- ///
- /// Generic value Read of a modbus value ex. "var ret = await Read(_serial, _device_id, req, new Single());"
- ///
- /// UInt16, Single ...
- /// device ID to use for read
- /// device value to read
- /// a new value of the type to read, to use for init and return
- /// as ModbusDataResult where Item1 is true if okay and Item2 is the value read
- public ModbusDataResult Read(int device_id, Device_value dv, T retValue) where T : IComparable, IFormattable, IComparable, IEquatable/*, IConvertible is not compatible with BigInteger*/
- {
- ModbusDataResult ret = null;
- try
- {
- byte[] answer = Read_bytes(device_id, dv.MD_adr, dv.Datatype.Length());
- retValue = (T)DeviceValueEncoder.Decode(answer, dv.Datatype);
- ret = new ModbusDataResult(true, retValue, dv); // Okay
- }
- catch (Exception ex)
- {
- var message = $"Read error! from ID={device_id} name={dv.Name} adr={dv.MD_adr} with {dv.Datatype.Length()}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Read()", message);
- ret = new ModbusDataResult(false, retValue, dv); // Error
- }
- return ret;
- }
-
- ///
- /// Read multiple value optimized in one or more telegrams from device
- ///
- /// Device ID to use for read
- /// A list of values to read
- /// List with read okay or failed values
- public List Read(int device_id, List dvList)
- {
- List ret = null;
- try
- {
- // ----------- Generate blocks to read -----------
- dvList.Sort((dvA, dvB) =>
- {
- return dvA.MD_adr.CompareTo(dvB.MD_adr);
- });
- List> blocks = new List>();
- foreach (var dv in dvList)
- {
- // if first item, just add it
- if ((blocks.Count == 0) || (blocks.Last().Count == 0))
- {
- if (blocks.Count == 0)
- {
- blocks.Add(new List());
- }
- blocks.Last().Add(new ModbusDataRequest(false, null, dv));
- }
- else
- {
- var dvLast = blocks.Last().Last().Info;
- // Only add it if a new value not already to be read
- if (dvLast.Name != dv.Name)
- {
- var nextAdr = dvLast.MD_adr + (dvLast.Datatype.Length()/2);
- // If not next to read in current block
- if (dv.MD_adr != nextAdr)
- {
- // then add it to the next read block
- blocks.Add(new List());
- }
- blocks.Last().Add(new ModbusDataRequest(false, null, dv));
- }
- }
- }
- // ----------- Read blocks -----------
- foreach (var dv_group in blocks)
- {
- try
- {
- var dvi_first = dv_group.First().Info;
- var dvi_last = dv_group.Last().Info;
- var startAdr = dvi_first.MD_adr;
- var LenBytes = (dvi_last.MD_adr+(dvi_last.Datatype.Length()/2)-startAdr)*2;
- if ((LenBytes < 0) || (LenBytes > 250))
- {
- throw new Exception($"Block length limit Error is {LenBytes}");
- }
- byte[] answer = Read_bytes(device_id, startAdr, LenBytes);
- if (answer == null)
- {
- throw new Exception($"Read block error! from ID={device_id} from {dvi_first} to {dvi_last}");
- }
- foreach (var dv_data in dv_group)
- {
- var dv = dv_data.Info;
- var start_idx = (dv.MD_adr-startAdr)*2;
- var value_bytes = answer.Copy(start_idx, dv.Datatype.Length());
- var value = DeviceValueEncoder.Decode(value_bytes, dv.Datatype);
- if (ret == null)
- {
- ret = new List();
- }
- ret.Add(new ModbusDataRequest(true, value, dv)); // Okay
- }
- }
- //catch (Exception ex)
- catch
- {
- // Retry read it as single values
- foreach (var dv_data in dv_group)
- {
- var dv = dv_data.Info;
- byte[] answer = Read_bytes(device_id, dv.MD_adr, dv.Datatype.Length());
- var value = DeviceValueEncoder.Decode(answer, dv.Datatype);
- if (ret == null)
- {
- ret = new List();
- }
- ret.Add(new ModbusDataRequest(true, value, dv)); // Okay
- }
- }
- }
- return ret;
- }
- catch (Exception ex)
- {
- if ((dvList != null) && (dvList.Count() > 0))
- {
- foreach (var dv in dvList)
- {
- var message = $"Read error! from ID={device_id} name={dv.Name} adr={dv.MD_adr}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Read()", message);
- }
- }
- else
- {
- var message = $"Read error! from ID={device_id}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Read()", message);
- }
- ret = null; // Error
- }
- return ret;
- }
-
-
- ///
- /// Generic value Write of a modbus value ex. "await Write(_serial, _device_id, req, value)"
- ///
- /// UInt16, Single ..
- /// device ID to use for write
- /// device value to write
- /// the value to write
- ///
- public bool Write(int device_id, Device_value dv, T value) where T : IComparable, IFormattable, IConvertible, IComparable, IEquatable
- {
- bool isOkay = true;
- try
- {
- byte[] tx_data = DeviceValueEncoder.Encode(value, dv.Datatype);
- if (!Write_bytes(device_id, dv.MD_adr, tx_data))
- {
- var message = $"Write failed={dv,ch_lng_dv}: Reg_Ver={dv.Version,ch_lng_Version} Adr={dv.MD_adr,-7} value={value,dig_value}";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write()", message);
- isOkay = false;
- }
- }
- catch (Exception ex)
- {
- var message = $"Write error! to ID={device_id} name={dv.Name} adr={dv.MD_adr} with {dv.Datatype.Length()}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write()", message);
- isOkay = false;
- }
- return isOkay;
- }
-
- ///
- /// Write multiple value optimized in one or more telegrams to device
- ///
- /// device ID to use for write
- /// a list of values to write
- /// A list of values written okay or failed to device
- public List Write(int device_id, List reqList)
- {
- List ret = null;
- try
- {
- // ----------- Generate blocks to write -----------
- reqList.Sort((dvA, dvB) =>
- {
- return dvA.Info.MD_adr.CompareTo(dvB.Info.MD_adr);
- });
- List> blocks = new List>();
- foreach (var req in reqList)
- {
- // if first item, just add it
- if ((blocks.Count == 0) || (blocks.Last().Count == 0))
- {
- if (blocks.Count == 0)
- {
- blocks.Add(new List());
- }
- blocks.Last().Add(req);
- }
- else
- {
- var req_Last = blocks.Last().Last();
- // Only add it if a new value not already written
- if (req_Last.Info.Name != req.Info.Name)
- {
- var nextAdr = req_Last.Info.MD_adr + (req_Last.Info.Datatype.Length()/2);
- // If not next to read in current block
- if (req.Info.MD_adr != nextAdr)
- {
- // then add it to the next read block
- blocks.Add(new List());
- }
- blocks.Last().Add(req);
- }
- else
- {
- throw new Exception($"Only a single Write object to {req_Last.Info.Name} is allowed!");
- }
- }
- }
- // ----------- Write blocks -----------
- foreach (var req_group in blocks)
- {
- try
- {
- var dvi_first = req_group.First().Info;
- var dvi_last = req_group.Last().Info;
- var startAdr = dvi_first.MD_adr;
- var LenBytes = (dvi_last.MD_adr+(dvi_last.Datatype.Length()/2)-startAdr)*2;
- if ((LenBytes < 0) || (LenBytes > 250))
- {
- throw new Exception($"Block length limit Error is {LenBytes}");
- }
- var tx_group_data = new List();
- foreach (var wr in req_group)
- {
- byte[] tx_data = DeviceValueEncoder.Encode(wr.Data, wr.Info.Datatype);
- if (tx_data == null)
- {
- throw new Exception($"Fail getting write byte data for {wr.Info.Name}");
- }
- tx_group_data.AddRange(tx_data);
- }
- if (LenBytes != tx_group_data.Count)
- {
- throw new Exception($"Group write from {dvi_first.Name} to {dvi_last.Name} expected={LenBytes} bytes, encoded was={tx_group_data.Count} bytes");
- }
- var isOkay = Write_bytes(device_id, startAdr, tx_group_data.ToArray());
- if (!isOkay)
- {
- throw new Exception($"Write block error! from ID={device_id} from {dvi_first} to {dvi_last}");
- }
- ret = new List();
- foreach (var req in req_group)
- {
- req.IsOkay = true;
- ret.Add(req); // add request that succeed
- }
- }
- //catch (Exception ex) //For debugging
- catch
- {
- ret = new List();
- // Retry write as single values
- foreach (var req in req_group)
- {
- var dv = req.Info;
- byte[] tx_data = DeviceValueEncoder.Encode(req.Data, req.Info.Datatype);
- req.IsOkay = Write_bytes(device_id, dv.MD_adr, tx_data);
- ret.Add(req); //
- }
- }
- }
- return ret;
- }
- catch (Exception ex)
- {
- if ((reqList != null) && (reqList.Count() > 0))
- {
- foreach (var dv in reqList)
- {
- var message = $"Write error! from ID={device_id} name={dv.Info.Name} adr={dv.Info.MD_adr}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write()", message);
- }
- }
- else
- {
- var message = $"Write error! from ID={device_id}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write()", message);
- }
- ret = null; // Error
- }
- return ret;
- }
-
- ///
- /// A general modbus read function for just a bunch of bytes
- ///
- /// device ID to use for modbus command
- /// Start address to data accessed
- /// Number of bytes to request
- /// byte data read from device and is null if none / error
- public byte[] Read_bytes(int device_id, int md_adr, int num_of_bytes)
- {
- var is_write = false;
- try
- {
- // Read address 0 device
- var p_transate = new ProtocolTranslateModbusRTUClass();
- byte[] tx_data = p_transate.CreateTxData(device_id, (int)Func_RD.No3, md_adr, num_of_bytes, null, is_write);
- return modbus_com(md_adr, tx_data, is_write, p_transate);
- }
- catch (Exception ex)
- {
- var message = $"!error No data received from ID={device_id} adr={md_adr} with {num_of_bytes} to {(is_write ? "Write" : "Read")}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Read_bytes()", message);
- return null;
- }
- }
-
- ///
- /// A general modbus write function for just a bunch of bytes
- ///
- /// device ID to use for modbus command
- /// Start address to data accessed
- /// Byte data to Write
- /// Is true on write is okay
- public bool Write_bytes(int device_id, int md_adr, byte[] write_data)
- {
- var is_write = true;
- try
- {
- // Read address 0 device
- var p_transate = new ProtocolTranslateModbusRTUClass();
- byte[] tx_data = p_transate.CreateTxData(device_id, (int)Func_WR.No16, md_adr, write_data.Length, write_data, is_write);
- var result = modbus_com(md_adr, tx_data, is_write, p_transate);
- if (result != null)
- {
- return true; // Okay
- }
- }
- catch (Exception ex)
- {
- var message = $"!error writting data to ID={device_id} adr={md_adr} to {(is_write ? "Write" : "Read")}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "Write_bytes()", message);
- }
- return false; // Error
- }
-
- ///
- /// A general modbus read / write function for just a bunch of bytes
- ///
- /// Start address to data accessed
- /// a complet modbus telegram byte data to transmit
- /// is the modbus telegram a write or read type to use for eval received result
- /// Modbus protocol translater for eval received result
- /// will return null on error or received message on okay
- public byte[] modbus_com(int md_adr, byte[] tx_data, bool is_write, ProtocolTranslateModbusRTUClass p_transate)
- {
- lock (_serial)
- {
- try
- {
- byte[] answer = null;
- var retry = 0;
- do
- {
- MsgCount++;
- if (!_serial.IsOpen)
- {
- _serial.Open();
- }
- _serial.DiscardInBuffer();
- _serial.Write(tx_data, 0, tx_data.Length);
-
- int received = 0;
- int max_count = _MaxWaitForComRX_ms/_DelayBetweenRxByteCheck_ms;
- do
- {
- received = _serial.BytesToRead;
- Thread.Sleep(_DelayBetweenRxByteCheck_ms);
- } while (((received == 0) || (received != _serial.BytesToRead)) && (--max_count>0));
- if (_serial.BytesToRead <= 0)
- {
- MsgErrorCount++;
- }
- } while ((_serial.BytesToRead <= 0) && (++retry < _retry));
- if (_serial.BytesToRead <= 0)
- {
- throw new Exception("!error No data received from device");
- }
-#if (DEBUG)
- // TODO just testing
- if (retry > 1)
- {
- Console.WriteLine($"Warning modbus com {retry-1} retry needed for ID={md_adr} to {(is_write ? "Write" : "Read")}");
- }
-#endif //#if (DEBUG)
- var bytesToRead = _serial.BytesToRead;
- var rx_data = new byte[bytesToRead];
- var rx_data_len = _serial.Read(rx_data, 0, bytesToRead);
- bool isRxRW = p_transate.IsDataRW(rx_data, true);
- // Check data func is Read or write
- if (isRxRW)
- {
- // Read
- if (!is_write)
- {
- if (p_transate.IsRead(rx_data, true))
- {
- answer = p_transate.GetReadData(rx_data, true);
- //buf.CallBackOK(bDataTemp, txData, CallBackOK_Single);
- }
- else
- {
- throw new Exception("Data Rx Wrong");
- }
- }
- else // Write
- {
- bool isWrite = p_transate.IsWrite(rx_data, true);
- int adr = p_transate.GetRxAdr(rx_data, true);
- if (isWrite && (!p_transate.IsAdrPossible(rx_data, true) ? true : (adr == md_adr)))
- {
- //buf.CallBackOK(null, txData, CallBackOK_Single);
- return rx_data; // Is okay return received message
- }
- else
- {
- throw new Exception("Data Rx Wrong");
- }
- }
-
- }
- else // Exception received
- {
- // Normal
- if (!p_transate.IsRxWaitForCommand(rx_data, true))
- {
- int exception = p_transate.GetRxAcknowledgeCode(rx_data, true);
- //buf.CallBackError(exception, txData, "");
- // If read .. try again after wait
- }
- else
- {
- if (!is_write)
- {
- //buf.Add(txData);
- // if Write.. then all must be okay and put event on delay
- }
- else
- {
- //buf.CallBackOK(null, txData, CallBackOK_Single);
- }
- if (p_transate.IsRxWaitForFinishMax60S(rx_data, true))
- {
- Thread.Sleep((int)(60 * 1000));
- }
- else if (p_transate.IsRxWaitForFinishMax5Min(rx_data, true))
- {
- Thread.Sleep((int)(5 * 60 * 1000));
- }
- else if (p_transate.IsRxWaitForFinishMax5S(rx_data, true))
- {
- Thread.Sleep((int)(5 * 1000));
- }
- else
- {
- int waitTime = 5 * 1000; // default
- Thread.Sleep(waitTime); // Wait for reset
- }
- }
- }
- return answer;
- }
- catch (Exception ex)
- {
- var message = "Error: \n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "modbus_com()", message);
- return null;
- }
- finally
- {
- _serial.Close();
- }
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ProtocolTranslateModbusRTUClass.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ProtocolTranslateModbusRTUClass.cs
deleted file mode 100644
index 8f6f4ed2..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ProtocolTranslateModbusRTUClass.cs
+++ /dev/null
@@ -1,572 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net.Sockets;
-using XYLEM.Base;
-
-namespace XYLEM.Communication
-{
- public class ProtocolTranslateModbusRTUClass
- {
- public enum FunctionNumber : byte
- {
- NoSupport = 0,
- Read_No3 = 3,
- Read_No4 = 4,
- Write_No15 = 15,
- Write_No16 = 16,
-
- };
-
- ///
- /// Modbus Byte Offset for write data telegram
- ///
- private enum BaseOffset
- {
- ID = 0,
- FuncCode
- }
-
- ///
- /// Modbus Byte Offset for write data telegram
- ///
- private enum TxOffset_W
- {
- AdrHigh = (int)BaseOffset.FuncCode + 1,
- AdrLow,
- RegCount_High,
- RegCount_Low,
- ByteCount,
- Data_Start
- };
-
- ///
- /// Modbus Byte Offset for read data telegram
- ///
- private enum TxOffset_R
- {
- AdrHigh = (int)BaseOffset.FuncCode + 1,
- AdrLow,
- RegCount_High, RegCount_Low
- };
-
- ///
- /// Modbus Byte Offset for read data telegram
- ///
- private enum RxOffset_R
- {
- ByteCount = (int)BaseOffset.FuncCode + 1,
- Data_Start
- };
-
- ///
- /// Modbus Byte Offset for read data telegram
- ///
- private enum RxOffset_W
- {
- AdrHigh = (int)BaseOffset.FuncCode + 1,
- AdrLow,
- RegCount_High, RegCount_Low
- };
-
- ///
- /// Modbus Byte Offset for exception data telegram
- ///
- private enum TxRxOffset_Exc
- {
- ExceptionCode = (int)BaseOffset.FuncCode + 1
- };
-
- ///
- /// Calc CRC
- ///
- ///
- ///
- ///
- private UInt16 CalcCrc(Byte[] bByteData, int iDataCount)
- {
- int u8CountByte;
- byte u8Temp, u8CountBit;
- UInt16 u16RetCRCvalue;
- u16RetCRCvalue = 0xffff;
- for (u8CountByte = 0; u8CountByte < iDataCount; u8CountByte++)
- { // Udregn CRC værdien
- u16RetCRCvalue ^= bByteData[u8CountByte];
- for (u8CountBit = 0; u8CountBit < 8; u8CountBit++)
- {
- u8Temp = (Byte)(u16RetCRCvalue & 1);
- u16RetCRCvalue >>= 1;
- if (u8Temp == 1)
- {
- u16RetCRCvalue ^= 0xa001;
- }
- }
- }
- return u16RetCRCvalue;
- }
-
-
- #region IProtocolTranslateClass Members
- public int MaxDataReadBSize()
- {
- return 250; ////(252-1"Number of bytes to read")/2=125 MODBUS over _serial line specification and implementation guide V1.02 (Page 13) + Func 4/3
- }
-
- public int MaxDataWriteBSize()
- {
- return 230; //
- }
-
- public void StampReset() { }
-
- public byte StampNow
- {
- get { return 0; } // Off
- }
-
- ///
- /// Create a tx modbus message
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public byte[] CreateTxData(int slaveID, int rwFuncNo, int adr, int dataByteSize, Byte[] writeData, bool IsDeviceResponse)
- {
- try
- {
- Byte bTemp;
- Byte[] txData = null;
- int count = 0, iCRC;
- // Convert to modb us func number
- FunctionNumber funcNo;
- switch (rwFuncNo)
- {
- case (int)Func_RD.No3: funcNo = FunctionNumber.Read_No3; break;
- case (int)Func_RD.No4: funcNo = FunctionNumber.Read_No4; break;
- case (int)Func_WR.No15: funcNo = FunctionNumber.Write_No15; break;
- case (int)Func_WR.No16: funcNo = FunctionNumber.Write_No16; break;
- default: throw new Exception(LogMessageTool.ToFuncErrorText(this.ToString(), "CreateTxData()", "Incorrect func = " + rwFuncNo.ToString()));
- }
- #region ---- Read ----
- if ((funcNo == FunctionNumber.Read_No3) || (funcNo == FunctionNumber.Read_No4))
- {
- if (IsDeviceResponse)
- {
- if ((writeData == null) && (dataByteSize != writeData.Length))
- {
- var dataBLng = (writeData == null ? 0 : writeData.Length);
- throw new Exception("Data length is not the same expected " + dataByteSize + " but is " + dataBLng);
- }
- count = (int)RxOffset_R.Data_Start + dataByteSize;
- txData = new Byte[count + 2/*to crc*/ ];
- txData[(int)BaseOffset.ID] = (byte)slaveID;
- txData[(int)BaseOffset.FuncCode] = (byte)funcNo;
- txData[(int)RxOffset_R.ByteCount] = (byte)dataByteSize;
- // Copy and Swap High And Low byte in word
- for (int offset = 0; offset < dataByteSize; offset += 2)
- {
- bTemp = writeData[offset];
- txData[(int)RxOffset_R.Data_Start + offset] = writeData[offset + 1];
- txData[(int)RxOffset_R.Data_Start + offset + 1] = bTemp;
- }
- }
- else
- {
- dataByteSize = (dataByteSize == 1) ? 2 : dataByteSize;
- txData = new Byte[(int)TxOffset_R.RegCount_Low + 3];
- txData[(int)BaseOffset.ID] = (byte)slaveID;
- txData[(int)BaseOffset.FuncCode] = (byte)funcNo;
- txData[(int)TxOffset_R.AdrHigh] = (byte)(adr >> 8);
- txData[(int)TxOffset_R.AdrLow] = (byte)adr;
- txData[(int)TxOffset_R.RegCount_High] = (byte)0;
- txData[(int)TxOffset_R.RegCount_Low] = (byte)(dataByteSize >> 1);
- count = (int)TxOffset_R.RegCount_Low + 1;
- }
- }
- #endregion// Read
- #region ---- Write ----
- if ((funcNo == FunctionNumber.Write_No16) || (funcNo == FunctionNumber.Write_No15))
- {
- dataByteSize = writeData.Length;
- dataByteSize = (dataByteSize == 1) ? 2 : dataByteSize;
- txData = new Byte[(int)TxOffset_W.Data_Start + dataByteSize + 2];
- txData[(int)BaseOffset.ID] = (byte)slaveID;
- txData[(int)BaseOffset.FuncCode] = (byte)funcNo;
- txData[(int)TxOffset_W.AdrHigh] = (byte)(adr >> 8);
- txData[(int)TxOffset_W.AdrLow] = (byte)adr;
- txData[(int)TxOffset_W.RegCount_High] = (byte)0;
- txData[(int)TxOffset_W.RegCount_Low] = (byte)(dataByteSize >> 1);
- txData[(int)TxOffset_W.ByteCount] = (byte)dataByteSize;
- // Copy and Swap High And Low byte in word
- for (count = 0; count < dataByteSize; count += 2)
- {
- bTemp = writeData[count];
- txData[(int)TxOffset_W.Data_Start + count] = writeData[count + 1];
- txData[(int)TxOffset_W.Data_Start + count + 1] = bTemp;
- }
- count = dataByteSize + (int)TxOffset_W.Data_Start;
- }
- #endregion// Write
- iCRC = CalcCrc(txData, count);
- txData[count] = (byte)iCRC;
- txData[count + 1] = (byte)(iCRC >> 8);
- return txData; // OK
- }
- catch
- {
- return null; // Error
- }
- }
-
- public bool IsDataOkay(byte[] data, bool IsDeviceResponse)
- {
- int iCRC;
- int length = (data != null) ? data.Length : 0;
- iCRC = data[length - 1];
- iCRC = data[length - 2] + (iCRC << 8);
- return (CalcCrc(data, length - 2) == iCRC) || (CalcCrc(data, length - 2) == (((iCRC & 0xff) << 8) | (iCRC >> 8))); // Keller Fix
- }
-
- public bool IsRxDataOkay(byte[] data)
- {
- return IsDataOkay(data, true);
- }
-
-
- public bool IsDataRW(byte[] data, bool IsDeviceResponse)
- {
- return (data[(int)BaseOffset.FuncCode] < 0x80);
- }
-
- public bool IsRead(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)BaseOffset.FuncCode] == (int)FunctionNumber.Read_No3
- || data[(int)BaseOffset.FuncCode] == (int)FunctionNumber.Read_No4;
- }
-
- public byte[] GetReadData(byte[] data, bool IsDeviceResponse)
- {
- try
- {
- Byte[] retData = new Byte[(int)data[(int)RxOffset_R.ByteCount]];
- int offset = 0, length = 0, func = data[(int)BaseOffset.FuncCode];
- if ((func == (int)FunctionNumber.Read_No3) || (func == (int)FunctionNumber.Read_No4))
- {
- offset = (int)RxOffset_R.Data_Start;
- length = retData.Length;
- if (data.Count() < length)
- {
- throw new Exception($"Data lng ={data.Count()} is expecting min. {length}");
- }
- if (length == 0)
- {
- return null; // Error
- }
- for (int iTemp = 0; (iTemp < length); iTemp += 2)
- {
- retData[iTemp + 1] = data[offset + iTemp];
- retData[iTemp] = data[offset + iTemp + 1];
- }
- }
- else
- {
- return null; // Error
- }
- return retData;
- }
- catch (Exception ex)
- {
- var dataAsTxt = (data==null) ? "Data is null" : data.ToHex(true, false);
- var message = $"Error: data={dataAsTxt}\n\r" + ex.Message + "\n\r";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), "GetReadData()", message);
- throw new Exception(message);
- }
- }
-
- public bool IsWrite(byte[] data, bool IsDeviceResponse)
- {
- return (data[(int)BaseOffset.FuncCode] == (int)FunctionNumber.Write_No16);
- }
-
- public bool IsAdrPossible(byte[] data, bool IsDeviceResponse)
- {
- return false;
- }
-
- public int GetRxAdr(byte[] data, bool IsDeviceResponse)
- {
- return ((int)data[(int)RxOffset_W.AdrHigh] << 8) | (int)data[(int)RxOffset_W.AdrLow];
- }
-
- public bool IsRxWaitForCommand(byte[] data, bool IsDeviceResponse)
- {
- return
- (data[(int)TxRxOffset_Exc.ExceptionCode] == (int)DeviceExceptionData.SpecialType.WaitForReset)
- || IsRxWaitForFinishMax5S(data, IsDeviceResponse)
- || IsRxWaitForFinishMax60S(data, IsDeviceResponse)
- || IsRxWaitForFinishMax5Min(data, IsDeviceResponse);
- }
-
- public bool IsRxWaitForFinishMax5S(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)TxRxOffset_Exc.ExceptionCode] == (int)DeviceExceptionData.SpecialType.WaitForFinishMax5s;
- }
-
- public bool IsRxWaitForFinishMax60S(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)TxRxOffset_Exc.ExceptionCode] == (int)DeviceExceptionData.SpecialType.WaitForFinishMax60s;
- }
-
- public bool IsRxWaitForFinishMax5Min(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)TxRxOffset_Exc.ExceptionCode] == (int)DeviceExceptionData.SpecialType.WaitForFinishMax5Min;
- }
-
- public bool IsAcknowledge(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)BaseOffset.FuncCode] >= 0x80;
- }
-
- public int GetRxAcknowledgeCode(byte[] data, bool IsDeviceResponse)
- {
- return data[(int)TxRxOffset_Exc.ExceptionCode];
- }
-
- public ProtocolType Protocol
- {
- get { return ProtocolType.ModbusRTU; }
- }
-
- public int GetFuncNo(byte[] rx_data, bool IsDeviceResponse)
- {
- return (int)rx_data[(int)BaseOffset.FuncCode];
- }
-
- public int GetStartAdr(byte[] rx_data, bool IsDeviceResponse)
- {
- if (IsWrite(rx_data, IsDeviceResponse))
- {
- return GetRxAdr(rx_data, IsDeviceResponse);
- }
- else if (IsRead(rx_data, IsDeviceResponse))
- {
- return GetRxAdr(rx_data, IsDeviceResponse); // Is master read
- }
- throw new Exception("Unknown protocol type and location for start adr.");
- }
-
- public int GetNumberOfDataBytes(byte[] rx_data, bool IsDeviceResponse)
- {
- if (IsWrite(rx_data, IsDeviceResponse))
- {
- return rx_data[(int)RxOffset_W.RegCount_Low] * 2;
- }
- else if (IsRead(rx_data, IsDeviceResponse))
- {
- if (IsDeviceResponse)
- {
- return rx_data[(int)RxOffset_R.ByteCount];
- }
- else
- {
- return rx_data[(int)RxOffset_W.RegCount_Low] * 2;
- }
- }
- throw new Exception("Unknown protocol type and location for number of bytes");
- }
-
- public int GetComID(byte[] rx_data, bool IsDeviceResponse)
- {
- return rx_data[(int)BaseOffset.ID];
- }
-
- public byte[] GetWriteData(byte[] rx_data, bool IsDeviceResponse)
- {
- var bytesToWrite = GetNumberOfDataBytes(rx_data, IsDeviceResponse);
- try
- {
- var data = Base.ByteArrayExtensionClass.SwapByteInWord(rx_data.Copy((int)TxOffset_W.Data_Start, bytesToWrite));
- return data;
- }
- catch (Exception)
- {
- throw new Exception("Fail to copy write data! data byte size = " + bytesToWrite);
- }
- }
-
- public byte[] CreateTxData(int slaveID, int rwFuncNo, int adr, int writeResponse, bool IsDeviceResponse)
- {
- throw new NotImplementedException();
- }
-
- public string ToInfo(byte[] input, bool IsDeviceResponse)
- {
- string ret = "";
- try
- {
- bool isOkay = IsDataOkay(input, IsDeviceResponse);
- if (isOkay)
- {
- int id = GetComID(input, IsDeviceResponse);
- int func = GetFuncNo(input, IsDeviceResponse);
- ret += string.Format("Type {0}" + Environment.NewLine, IsDeviceResponse ? "Response" : "Request");
- ret += string.Format("ID {0}" + Environment.NewLine, id);
- bool isExeption = !IsDataRW(input, IsDeviceResponse);
- try
- {
- var func2Test = func;
- if (isExeption)
- {
- func2Test -= 0x80; // Get function from exeption code
- ret += "Exception ";
- }
- ret += string.Format("Func. {0} / {1} hex", func2Test, func2Test.ToString("x"));
- switch (func2Test)
- {
- case (int)FunctionNumber.Read_No3:
- case (int)FunctionNumber.Read_No4:
- ret += " is Read";
- break;
- case (int)FunctionNumber.Write_No15:
- case (int)FunctionNumber.Write_No16:
- if (IsDeviceResponse)
- {
- ret += " Incorrect write replay from slave!!!!";
- }
- else
- {
- ret += " is Write";
- }
- break;
- default: ret += " Unknown func. type!"; break;
- }
- }
- catch { ret += string.Format(" Unknown func. type!"); }
- ret += Environment.NewLine;
- if (isExeption)
- {
- var exeptioncode = (int)input[(int)BaseOffset.FuncCode + 1];
- ret += string.Format("Exception code {0} / {1} hex", exeptioncode, exeptioncode.ToString("x"));
- }
- else
- {
- ret += string.Format("Number of Bytes {0}" + Environment.NewLine, GetNumberOfDataBytes(input, IsDeviceResponse));
- if (IsDeviceResponse)
- {
- byte[] data = null;
- if (IsRead(input, IsDeviceResponse))
- {
- data = GetReadData(input, IsDeviceResponse);
- }
- if (data != null)
- {
- data = Base.ByteArrayExtensionClass.SwapByteInWord(data);
- ret += string.Format("Data is = {0}", Base.NumberConvert.ToHex(data, true, false));
- }
- }
- else
- {
- byte[] data = null;
- ret += string.Format("Start Address {0}" + Environment.NewLine, GetStartAdr(input, IsDeviceResponse));
- if (IsWrite(input, IsDeviceResponse))
- {
- data = GetWriteData(input, IsDeviceResponse);
- }
- if (data != null)
- {
- data = Base.ByteArrayExtensionClass.SwapByteInWord(data);
- ret += string.Format("Data is = {0}\n", Base.NumberConvert.ToHex(data, true, false));
- }
- }
- }
- //No44, // or 68 as a Special myconnect IO module telegram for https://mjksvn.world.fluidtechnology.net:4443/svn/development/8440XX Connect and myConnect/myConnect/trunk/docs/IO modules communication.docx
- }
- else if ((input != null) && (input.Length >= (16 + 2)))
- { // Check if it is
- var telegrams = input.SliceSameSize(0, (16 + 2));
- foreach (var telegram in telegrams)
- {
- if (IsDataOkay(telegram, IsDeviceResponse))
- {
- ret += "¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤" + Environment.NewLine;
- int offset = 0;
- ret += "ID[" + telegram[offset++] + "]";
- ret += " func[" + telegram[offset++] + "]";
- int Quantity = telegram[offset++];
- int[] Descriptors = new int[] { telegram[offset++], 0 };
- { // print out Status
- ret += Environment.NewLine;
- int Status = telegram[offset++];
- switch (Status)
- {
- case 0x11: ret += "Both recognized"; break;
- case 0x01: ret += "Lower OK, upper ERROR"; break;
- case 0x10: ret += "Lower ERROR, upper OK"; break;
- case 0x00: ret += "Both ERROR"; break;
- default: ret += "Unknown status" + Status.ToHex(true); break;
- }
- }
- {// Print out Descriptor
- ret += Environment.NewLine;
- Descriptors[1] = telegram[offset++];
- foreach (var Descriptor in Descriptors)
- {
- ret += " Type[";
- switch (Descriptor)
- {
- case 0: ret += "none"; break;
- case 1: ret += "6DI"; break;
- case 2: ret += "6DO"; break;
- case 3: ret += "3AI"; break;
- case 4: ret += "3AO"; break;
- default: ret += "Unknown" + Descriptor.ToHex(true); break;
- }
- ret += "]";
- }
- }
- {// Print out data
- ret += Environment.NewLine + "Raw[" + telegram.Slice(offset, telegram.Length - offset).ToHex(true, false) + "]";
-
- var u32Values = telegram.SliceSameSize(offset, 4);
- foreach (var u32Value in u32Values)
- {
- ret += Environment.NewLine;
- ret += " DI&DO[" + u32Value[0].ToBin(true) + "]/AI&AO[" + (new DataUnion()).PutByteArray(u32Value, DataUnion.DataByteLayoutType.SwapWords).F32Data + "]";
- }
- }
- }
- else
- {
- ret += string.Format("Message is {0} is wrong!" + Environment.NewLine, telegram.ToHex(true, false));
- }
- ret += Environment.NewLine;
- }
- }
- else
- {
- ret += string.Format("Message is {0}" + Environment.NewLine, isOkay ? "okay" : "CRC is wrong!");
- }
- }
- catch (Exception ex)
- {
- ret += "Error = " + ex.Message;
- }
- return ret;
- }
-
- ///
- /// Added to IProtocolTranslateClass to use in Comli
- ///
- public byte[] CreateTxData(int slaveID, int rwFuncNo, int adr, int dataByteSize, byte[] writeData, bool IsDeviceResponse, ref int pageNumberNow)
- {
- throw new NotImplementedException();
- }
-
- #endregion
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ProtocolType.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ProtocolType.cs
deleted file mode 100644
index 9917f686..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ProtocolType.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-using System;
-
-namespace XYLEM.Communication
-{
- //------------------------------------- Define ------------------------------------------------
- public enum ProtocolType : int
- {
- ModbusRTU = 0,
- None,
- };
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/ArrayManipulator.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/ArrayManipulator.cs
deleted file mode 100644
index 437b8573..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/ArrayManipulator.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace XYLEM.Communication.ValueEncoders
-{
- static class ArrayManipulator
- {
- public static byte[] SwapPairWise(byte[] input)
- {
- byte[] swapped = new byte[input.Length];
- for (int i = 0; i < input.Length; i = i+2)
- {
- swapped[i + 1] = input[i];
- swapped[i] = input[i + 1];
- }
-
- return swapped;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/DeviceValueEncoder.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/DeviceValueEncoder.cs
deleted file mode 100644
index b485232c..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/DeviceValueEncoder.cs
+++ /dev/null
@@ -1,952 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using XYLEM.Communication;
-using System.Xml;
-using System.Xml.Linq;
-using XYLEM.Base;
-using XYLEM.Base.Files;
-using XYLEM.Device.Value;
-using System.Numerics;
-using XYLEM.Communication.ValueEncoders;
-using XYLEM.Base.XML;
-
-namespace XYLEM.Communication.ValueEncoders
-{
- ///
- /// Return used character set used for email or empty if not Loaded from setup
- ///
- /// ex. "iso-8859-1"
- public delegate string GetEmailCharacterSetToUse();
-
- public static class DeviceValueEncoder
- {
- public static object Default(this ValueDataType dataType)
- {
- try
- {
- switch (dataType)
- {
- case ValueDataType.U8:
- case ValueDataType.B8: return (byte)0;
- case ValueDataType.S8: return (sbyte)0;
-
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return (UInt16)0;
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC: return ((UInt32)0).Convert1970SecToTime(TimeType.UTC);
- case ValueDataType.U32TIME_Y2000: return ((UInt32)0).Convert2000SecToTime();
- case ValueDataType.U32MJK_SN: return ((UInt32)0);
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: return ((UInt32)0);
- //case DeviceValueDataType.U24:
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- case ValueDataType.B32:
- case ValueDataType.U32: return (UInt32)0;
- case ValueDataType.B64:
- case ValueDataType.U64: return (UInt64)0;
- case ValueDataType.F64: return (double)0;
- case ValueDataType.U128: return (BigInteger)0;
- case ValueDataType.S16: return (Int16)0;
- case ValueDataType.F32: return (Single)0;
- //case DeviceValueDataType.U32IPV4: return "0.0.0.0"; // handled as a string
- default:
- if (dataType.IsText())
- { // Do this as the last check to save CPU power
- return "";
- }
- throw new Exception(dataType.ToString() + "has no default value)");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Default()", "dataType = " + dataType.ToString()));
- }
- }
-
- public static string EncodeXML(this object value, ValueDataType type)
- {
- try
- {
- string valueAsTxt = value.ToString();
- switch (type)
- {
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- if (value is DateTime)
- {
- var value32bit = ((DateTime)value).ConvertTimeTo1970Sec(TimeType.Local);
- return XmlConvert.ToString(value32bit);
- }
- return XmlConvert.ToString((Double)value);
- case ValueDataType.U32TIME_Y2000:
- if (value is DateTime)
- {
- var value32bit = ((DateTime)value).ConvertTimeTo2000Sec(TimeType.Local);
- return XmlConvert.ToString(value32bit);
- }
- return XmlConvert.ToString((Double)value);
- case ValueDataType.U8:
- case ValueDataType.B8:
- case ValueDataType.S8:
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS:
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U24:
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.B64:
- case ValueDataType.U64:
- case ValueDataType.S16:
- case ValueDataType.S32:
- case ValueDataType.S64:
- case ValueDataType.F32:
- case ValueDataType.F64:
- case ValueDataType.U32MJK_SN:
- {
- if (typeof(Double) == value.GetType())
- {
- valueAsTxt = XmlConvert.ToString((Double)value);
- }
- else if (typeof(Single) == value.GetType())
- {
- valueAsTxt = XmlConvert.ToString((Single)value);
- }
- return valueAsTxt;
- }
- case ValueDataType.U128:
- if (typeof(BigInteger) == value.GetType())
- {
- valueAsTxt = ((BigInteger)value).ToString("X"); // enclode as hex
- }
- else
- {
- throw new Exception($"{value.GetType()} is not supported for U128 xml convert");
- }
- return valueAsTxt;
-
- //case DeviceValueDataType.U32IPV4: return valueAsTxt.Trim( ).StripIllegalXMLChars( );// handled as a string
- default:
- if (type.IsText())
- { // Do this as the last check to save CPU power
- return valueAsTxt.Trim().StripIllegalXMLChars();
- }
- throw new NotImplementedException("DataType '" + type + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "EncodeXML()", "dataType = " + type.ToString() + " Value is = " + value.ToString()));
- }
- }
-
- public static Object DecodeXML(this string valueInXml, ValueDataType type)
- {
- try
- {
- switch (type)
- {
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- return XmlConvert.ToUInt32(valueInXml).Convert1970SecToTime(TimeType.Local);
- case ValueDataType.U32TIME_Y2000:
- return XmlConvert.ToUInt32(valueInXml).Convert2000SecToTime();
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC: return XmlConvert.ToUInt32( valueInXml );
- case ValueDataType.B8:
- case ValueDataType.U8:
- return XmlConvert.ToByte(valueInXml);
- case ValueDataType.S8:
- return XmlConvert.ToSByte(valueInXml);
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return XmlConvert.ToUInt16(valueInXml);
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS:
- //case DeviceValueDataType.U24:
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- return XmlConvert.ToUInt32(valueInXml);
- case ValueDataType.B64:
- case ValueDataType.U64: return XmlConvert.ToUInt64(valueInXml);
- case ValueDataType.S16: return XmlConvert.ToInt16(valueInXml);
- case ValueDataType.S32: return XmlConvert.ToInt32(valueInXml);
- case ValueDataType.S64: return XmlConvert.ToInt64(valueInXml);
- case ValueDataType.F32: return XmlConvert.ToSingle(valueInXml);
- case ValueDataType.F64: return XmlConvert.ToDouble(valueInXml);
- case ValueDataType.U128: return BigInteger.Parse(valueInXml, System.Globalization.NumberStyles.HexNumber);
- //case DeviceValueDataType.U32IPV4: return valueInXml.ReinsetIllegalXMLChars( );// handled as a string
- default:
- if (type.IsText())
- { // Do this as the last check to save CPU power
- return valueInXml.ReinsetIllegalXMLChars();
- }
- throw new NotImplementedException("DataType '" + type + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "DecodeXML()", "dataType = " + type.ToString() + " Value is = " + valueInXml));
- }
- }
-
- ///
- /// do layout changes on byte stream
- ///
- ///
- ///
- ///
- static byte[] DoLayout(this byte[] bytes, LayoutType layout = LayoutType.Normal)
- {
- try
- {
- switch (layout)
- {
- case LayoutType.Normal: return bytes; ; // Do nothing
- case LayoutType.SwapAll: return bytes.Reverse();
- default:
- throw new NotSupportedException(layout + " is not supported");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "DoLayout", "layout = " + layout));
- }
- }
-
-
- ///
- /// Encode data with normal data layout
- ///
- ///
- ///
- /// Null if not used
- ///
- public static byte[] Encode(this object value, ValueDataType dataType, GetEmailCharacterSetToUse emailCharacterSet = null)
- {
- try
- {
- if (value == null)
- {
- throw new Exception("Value is null");
- }
- switch (dataType)
- {
- case ValueDataType.B8:
- case ValueDataType.U8:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(byte));// Try set type if not the correct one
- return BitConverter.GetBytes((byte)value);
- }
- case ValueDataType.S8:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(sbyte));// Try set type if not the correct one
- return BitConverter.GetBytes((sbyte)value);
- }
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return BitConverter.GetBytes((UInt16)value);
- case ValueDataType.U32TIME_Y1970:
- if (value is DateTime)
- {
- return BitConverter.GetBytes(((DateTime)value).ConvertTimeTo1970Sec(TimeType.Local));
- }
- return BitConverter.GetBytes((UInt32)value); // Work around on olde types
- case ValueDataType.U32TIME_Y1970_UTC:
- if (value is DateTime)
- {
- return BitConverter.GetBytes(((DateTime)value).ConvertTimeTo1970Sec(TimeType.UTC));
- }
- return BitConverter.GetBytes((UInt32)value); // Work around on olde types
- case ValueDataType.U32TIME_Y2000:
- if (value is DateTime)
- {
- return BitConverter.GetBytes(((DateTime)value).ConvertTimeTo2000Sec(TimeType.Local));
- }
- return BitConverter.GetBytes((UInt32)value);
- // Work around on olde types
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- // return BitConverter.GetBytes( TimeConvertClass.ToMidnightSecOffsetUTC( (UInt32)value ) );
- //case DeviceValueDataType.U24DateHH_MM_SS: {
- // var timeSpan = TimeConvertClass.ConvertTimeSpan( (UInt32)value );
- // return new byte[] { (byte)timeSpan.Seconds, (byte)timeSpan.Minutes, (byte)timeSpan.Hours };
- // }
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: {
- // var date = ((UInt32)value).Convert1970SecToTime( TimeType.Local );
- // return new byte[] {
- // (byte)date.Second,
- // (byte)date.Minute,
- // (byte)date.Hour,
- // (byte)date.Day,
- // (byte)date.Month,
- // (byte)(date.Year - 2000)
- // };
- // }
- //case DeviceValueDataType.U24: {
- // value = CorrectTypeIfNotTheSame( value, dataType, typeof( UInt32 ) );// Try set type if not the correct one
- // return BitConverter.GetBytes( (UInt32)value ).Remove( 3 );
- // }
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(UInt32));// Try set type if not the correct one
- return BitConverter.GetBytes((UInt32)value);
- }
- case ValueDataType.B64:
- case ValueDataType.U64:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(UInt64));// Try set type if not the correct one
- return BitConverter.GetBytes((UInt64)value);
- }
- case ValueDataType.S16:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(Int16));// Try set type if not the correct one
- return BitConverter.GetBytes((Int16)value);
- }
- case ValueDataType.S32:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(Int32));// Try set type if not the correct one
- return BitConverter.GetBytes((Int32)value);
- }
- case ValueDataType.F32:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(Single));// Try set type if not the correct one
- return BitConverter.GetBytes((Single)value);
- }
- case ValueDataType.F64:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(double));// Try set type if not the correct one
- return BitConverter.GetBytes((double)value);
- }
- case ValueDataType.U128:
- {
- value = CorrectTypeIfNotTheSame(value, dataType, typeof(BigInteger));// Try set type if not the correct one
- return ((BigInteger)value).ToByteArray(); // TODO: Is this okay or need always to be the 16 byte in size?
- }
- //case DeviceValueDataType.U32IPV4: return U32_IP_Encoder.Encode( value.ToString( ) );
- default:
- if (dataType.IsText())
- { // Do this as the last check to save CPU power
- var typeAsText = dataType.ToString();
- // is Email
- if (dataType.IsEmailText())
- {
- return StringEncoderEmail.Encode(value.ToString(), Length(dataType), ((emailCharacterSet == null) ? "" : emailCharacterSet()));
- }
- // is SMS
- if (dataType.IsSMSText())
- {
- return StringEncoderUnicode.Encode(value.ToString(), Length(dataType));
- }
- // is Windows 1252
- if (dataType.IsWindows1252Text())
- {
- return StringEncoder_W1252.Encode(value.ToString(), Length(dataType));
- }
- // is Windows 1252, but needs to have "<>" in frond and end
- // Ex. end result is "," or ""
- if (dataType.IsWindows1252TextRecipient())
- {
- var valueAsText = value.ToString().Trim();
- if (!String.IsNullOrEmpty(valueAsText))
- {
- // Remove manual added brackets or " if user has done it in the past
- if (valueAsText.Contains("\""))
- {
- valueAsText = valueAsText.Replace("\"", "");
- }
- //// work arround if user has already used "," as separation
- //if (valueAsText.Contains( "," )) {
- // valueAsText = valueAsText.Replace( ",", ">,<" ); //old modem firmware V1.003 and TDC NO
- //}
- // Replace ";" with correct "," as separation and add bracked ">" "<" to support RCF821
- if (valueAsText.Contains(";"))
- {
- //valueAsText = valueAsText.Replace( ";", ">,<" ); old modem firmware V1.003 and TDC NO
- valueAsText = valueAsText.Replace(";", ",");//new modem firmware V1.3 using mail.mjk-link.dk
- }
- // Trim
- valueAsText = valueAsText.Trim();
- // Add brackets "<>" around address / addresses and end with " to tell modem where it starts and end in MC55I at command
- //Ex. end result is "," or ""
- if (!String.IsNullOrEmpty(valueAsText))
- {
- //valueAsText = "\"<" + valueAsText + "\">"; old modem firmware V1.003 and TDC NO
- valueAsText = "\"" + valueAsText + "\""; //new modem firmware V1.3 using mail.mjk-link.dk
- }
- }
- return StringEncoder_W1252.Encode(valueAsText, Length(dataType));
- }
- // is Quoted Printable Text
- if (dataType.IsEmailQuotedPrintableText())
- {
- return StringEncoderEmail_Q_Types.Encode(value.ToString(), Length(dataType), ((emailCharacterSet == null) ? "" : emailCharacterSet()));
- }
- // Is is normal utf8
- return StringEncoder.Encode(value.ToString(), Length(dataType));
- }
- throw new NotImplementedException("DataType '" + dataType + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Encode", "dataType = " + dataType.ToString()));
- }
- }
-
- private static object CorrectTypeIfNotTheSame(object value, ValueDataType correctTypeTag, Type typeUsedForCast)
- {
- try
- {
- if (value.GetType() == typeUsedForCast)
- {
- return value; // Nothing to change
- }
- {
- AppConst.Logger.AddFuncLog(
-#if DEBUG //
- true // log as error
-#else
- false // Log silent in log
-#endif //#if DEBUG
- , typeof(DeviceValueEncoder).ToString(), "CorrectTypeIfNotTheSame()",
- "Warning! correction was needed. Is this a older setting else not okay? " + MakeCorrectTypeValueInfoText(value, correctTypeTag, typeUsedForCast)
- );
- }
- return ToValue(value.ToString(), correctTypeTag);
- }
- catch (Exception ex)
- {
- var valueInfo = MakeCorrectTypeValueInfoText(value, correctTypeTag, typeUsedForCast);
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "CorrectTypeIfNotTheSame", valueInfo));
- }
- }
-
- ///
- /// Generate the value info possible to get for a value to convert
- ///
- /// Value to correct
- /// correct value type tag
- /// type used for cast
- /// Text to show in log
- private static string MakeCorrectTypeValueInfoText(object value, ValueDataType correctTypeTag, Type typeUsedForCast)
- {
- var ValueInfo = "";
- try
- {
- if (ValueInfo == null)
- {
- ValueInfo += " Value= IS NULL and not possible to correct!";
- }
- else
- {
- ValueInfo += " Value=\"" + value.ToString() + "\"";
- ValueInfo += " From Type=\"" + value.GetType() + "\"";
- }
- ValueInfo += " To Type=\"" + correctTypeTag.ToString() + "\"";
- }
- catch { ValueInfo += " [Fail to get info ?] "; }
- return ValueInfo;
- }
-
- ///
- /// Encode data with data layout setting
- ///
- ///
- ///
- ///
- /// Null if not used
- ///
- public static byte[] Encode(this object value, ValueDataType dataType, LayoutType layout, GetEmailCharacterSetToUse emailCharacterSet = null)
- {
- try
- {
- var bytes = Encode(value, dataType, emailCharacterSet);
- if (bytes == null)
- {
- return bytes;
- }
- return bytes.DoLayout(layout);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Encode", "dataType = " + dataType.ToString()));
- }
- }
-
-
- ///
- /// Decode data with normal data layout
- ///
- ///
- ///
- /// Null if not used
- ///
- public static object Decode(this byte[] value, ValueDataType dataType, GetEmailCharacterSetToUse emailCharacterSet = null)
- {
- try
- {
- if (value == null)
- {
- throw new Exception("Value is null");
- }
- if (value.Count() == 0)
- {
- throw new Exception("Value Has no values in array");
- }
- switch (dataType)
- {
- case ValueDataType.B8:
- case ValueDataType.U8:
- return (byte)value.First();
- case ValueDataType.S8:
- return (sbyte)value.First();
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return BitConverter.ToUInt16(value, 0);
- case ValueDataType.U32TIME_Y1970:
- return BitConverter.ToUInt32(value, 0).Convert1970SecToTime(TimeType.Local);
- case ValueDataType.U32TIME_Y1970_UTC:
- return BitConverter.ToUInt32(value, 0).Convert1970SecToTime(TimeType.UTC).ToLocalTime();
- case ValueDataType.U32TIME_Y2000:
- return BitConverter.ToUInt32(value, 0).Convert2000SecToTime();
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- // return TimeConvertClass.FromMidnightSecOffsetUTC( BitConverter.ToUInt32( value, 0 ) );
- //case DeviceValueDataType.U24DateHH_MM_SS: {
- // return (UInt32)((UInt32)value[ 2 ] * 3600) + ((UInt32)value[ 1 ] * 60 + (UInt32)value[ 0 ]);
- // }
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: {
- // var date = new DateTime( (int)value[ 5 ] + 2000, value[ 4 ], value[ 3 ], value[ 2 ], value[ 1 ], value[ 0 ] );
- // return date.ConvertTimeTo1970Sec( TimeType.Local );
- // }
- //case DeviceValueDataType.U24: {
- // var as32bitValue = new byte[] { value[ 0 ], value[ 1 ], value[ 2 ], 0 };
- // return BitConverter.ToUInt32( as32bitValue, 0 );
- // }
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- return BitConverter.ToUInt32(value, 0);
- case ValueDataType.B64:
- case ValueDataType.U64: return BitConverter.ToUInt64(value, 0);
- case ValueDataType.S16: return BitConverter.ToInt16(value, 0);
- case ValueDataType.S32: return BitConverter.ToInt32(value, 0);
- case ValueDataType.F32: return BitConverter.ToSingle(value, 0);
- case ValueDataType.F64: return BitConverter.ToDouble(value, 0);
- case ValueDataType.U128:
- {
- // Need a zero in msb to avoid value is handled as signed
- var valueConverted = new BigInteger((value).Concat(new byte[1]).ToArray());
- return valueConverted;
- }
-
- case ValueDataType.Array6B:
- case ValueDataType.Array10B:
- case ValueDataType.Array12B:
- case ValueDataType.Array64B:
- case ValueDataType.Array128B:
- case ValueDataType.Array136B:
- case ValueDataType.Array250B: return value;
- //case DeviceValueDataType.U32IPV4: return U32_IP_Encoder.Decode( value );
- default:
- if (dataType.IsText())
- { // Do this as the last check to save CPU power
- var typeAsText = dataType.ToString();
- if (dataType.IsEmailText())
- { // is Email
- return StringEncoderEmail.Decode(value, Length(dataType), ((emailCharacterSet == null) ? "" : emailCharacterSet()));
- }
- if (dataType.IsSMSText())
- { // is SMS
- return StringEncoderUnicode.Decode(value, Length(dataType));
- }
- if (dataType.IsWindows1252Text())
- { // is Windows 1252
- return StringEncoder_W1252.Decode(value, Length(dataType));
- }
- if (dataType.IsWindows1252TextRecipient())
- { // is Windows 1252, but needs to have "<>" in frond and end
- var valueAsText = StringEncoder_W1252.Decode(value, Length(dataType));
- if (!String.IsNullOrEmpty(valueAsText))
- {
- // Remove added brackets or " nessesarry that is only to be
- // Ex. end result is "," or ""
- if (valueAsText.Contains("\""))
- {
- valueAsText = valueAsText.Replace("\"", "");
- }
- if (valueAsText.Contains("<"))
- {
- valueAsText = valueAsText.Replace("<", "");
- }
- if (valueAsText.Contains(">"))
- {
- valueAsText = valueAsText.Replace(">", "");
- }
- // Replace email seperation and replace it with correct the standard ";"
- if (valueAsText.Contains(","))
- {
- valueAsText = valueAsText.Replace(",", ";");
- }
- }
- return valueAsText;
- }
- if (dataType.IsEmailQuotedPrintableText())
- {
- return StringEncoderEmail_Q_Types.Decode(value, Length(dataType), ((emailCharacterSet == null) ? "" : emailCharacterSet()));
- }
- // Is allowed to have a variable length on a string / text
- var maxLng = dataType.Length();
- if (value.Length > maxLng)
- {
- throw new Exception(String.Format("Size of text is {0} and more than max {1}", value.Length, maxLng));
- }
- // Is is normal utf8
- return StringEncoder.Decode(value, value.Length);
- }
- throw new NotImplementedException("DataType '" + dataType + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Decode", "dataType = " + dataType.ToString()));
- }
- }
-
- ///
- /// Decode data with data layout setting
- ///
- ///
- ///
- /// Null if not used
- ///
- ///
- public static object Decode(this byte[] value, ValueDataType dataType, LayoutType layout, GetEmailCharacterSetToUse emailCharacterSet = null)
- {
- try
- {
- var bytes = value.DoLayout(layout);
- return Decode(value, dataType, emailCharacterSet);
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Encode", "dataType = " + dataType.ToString()));
- }
- }
-
- ///
- /// Convert a local defined string value to the correct value object according to dataType ("DeviceValueType")
- ///
- /// Value as string (floating point must use local setting for "," or ".") and DateTime as local time
- ///
- ///
- public static object ToValue(this string value, ValueDataType dataType)
- {
- try
- {
- if (value == null)
- {
- throw new Exception("Value is null");
- }
- switch (dataType)
- {
- case ValueDataType.B8:
- case ValueDataType.U8:
- return (byte)Convert.ToUInt16(value);
- case ValueDataType.S8:
- return (sbyte)Convert.ToInt16(value);
- case ValueDataType.B16:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- return Convert.ToUInt16(value);
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- case ValueDataType.U32TIME_Y2000:
- // Always expect this as local time
- return new DateTime(Convert.ToDateTime(value).Ticks, DateTimeKind.Local);
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U24:
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- return Convert.ToUInt32(value);
- case ValueDataType.B64:
- case ValueDataType.U64: return Convert.ToUInt64(value);
- case ValueDataType.S16: return Convert.ToInt16(value);
- case ValueDataType.S32: return Convert.ToInt32(value);
- case ValueDataType.F32: return Convert.ToSingle(value);
- case ValueDataType.F64: return Convert.ToDouble(value);
- case ValueDataType.U128:
- // Need a zero in msb to avoid value is handled as signed
- return BigInteger.Parse("0"+value, System.Globalization.NumberStyles.HexNumber);
- //case DeviceValueDataType.U32IPV4: {
- // if (dataType.IsText( )) {
- // return value.ToString( );
- // }
- // throw new NotImplementedException( "DataType '" + dataType + "' not recognized." );
- // }
- default:
- if (dataType.IsText())
- { // Do this as the last check to save CPU power
- var typeAsText = dataType.ToString();
- if (dataType.IsEmailText())
- { // is Email
- return value;
- }
- if (dataType.IsSMSText())
- { // is SMS
- return value;
- }
- if (dataType.IsWindows1252Text())
- { // is Windows 1252
- return value;
- }
- if (dataType.IsWindows1252TextRecipient())
- { // is Windows 1252, but needs to have "<>" in frond and end
- return value;
- }
- if (dataType.IsEmailQuotedPrintableText())
- { // is Special Email Quoted Printable
- return value;
- }
- // Is is normal utf8
- return value; //TODO: No converting is done. may have to be converted to utf8?
- }
- throw new NotImplementedException("DataType '" + dataType + "' not recognized.");
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "ToValue()", "dataType = " + dataType.ToString()));
- }
- }
-
- ///
- /// Return data Byte Length (1x8bit)
- ///
- ///
- public static int Length(this ValueDataType DataType)
- {
- try
- {
- switch (DataType)
- {
- case ValueDataType._Empty: return 0;
- #region ---- 8 Bit ----
- case ValueDataType.Bool:
- case ValueDataType.B8:
- case ValueDataType.S8:
- case ValueDataType.U8: return 1;
- #endregion // #region ---- 8 Bit ----
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U24: return 3;
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: return 6;
- default:
- return WLength(DataType) << 1;
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "Length"));
- }
- }
-
- ///
- /// Return data Word Length (2x8bit)
- ///
- ///
- public static int WLength(this ValueDataType DataType)
- {
- try
- {
- switch (DataType)
- {
- case ValueDataType._Empty: return 0;
- #region ---- 8 / 16 Bit ----
- case ValueDataType.Bool:
- case ValueDataType.B8:
- case ValueDataType.S8:
- case ValueDataType.U8:
- case ValueDataType.U16:
- case ValueDataType.U16MJK_SN:
- case ValueDataType.B16:
- case ValueDataType.S16:
- case ValueDataType.U16TEXTID:
- case ValueDataType.U16UNIT:
- case ValueDataType.U16UNITGROUP: return 1;
- #endregion
- //case DeviceValueDataType.U48DateYY_MM_DD_HH_MM_SS: return 3;
- //case DeviceValueDataType.U24DateHH_MM_SS:
- //case DeviceValueDataType.U24: return 2;
- #region ---- 32 Bit ----
- case ValueDataType.B32:
- case ValueDataType.U32:
- case ValueDataType.U32MJK_SN:
- case ValueDataType.S32:
- case ValueDataType.F32:
- //case DeviceValueDataType.U32TIMESPAN_MIDNIGHT_UTC:
- case ValueDataType.U32TIME_Y2000:
- case ValueDataType.U32TIME_Y1970:
- case ValueDataType.U32TIME_Y1970_UTC:
- //case DeviceValueDataType.U32IPV4:
- return 2;
- #endregion
- #region ---- 12 x 8 Bit Time Types ----
- case ValueDataType.TIME_ASCII_12B:
- case ValueDataType.TIME_ymdhms:
- return 6;
- #endregion
- #region ---- 64 Bit ----
- case ValueDataType.B64:
- case ValueDataType.U64:
- case ValueDataType.S64:
- case ValueDataType.F64:
- return 4;
- #endregion
- #region ---- 128 Bit ----
- case ValueDataType.U128:
- return 8;
- #endregion
- #region ---- Bit Arrays ----
- case ValueDataType.Array6B: return (6 / 2);
- case ValueDataType.Array10B: return (10 / 2);
- case ValueDataType.Array12B: return (12 / 2);
- case ValueDataType.Array64B: return (64 / 2);
- case ValueDataType.Array128B: return (128 / 2);
- case ValueDataType.Array136B: return (136 / 2);
- case ValueDataType.Array250B: return (250 / 2);
- #endregion
- #region ---- Strings / Text ----
- //6bytes
- case ValueDataType.STR6E:
- case ValueDataType.STR6S:
- //case DeviceValueDataType.STR6Q:
- //case DeviceValueDataType.STR6W1252:
- case ValueDataType.STR6: return 3;
- //8bytes
- case ValueDataType.STR8E:
- case ValueDataType.STR8S:
- //case DeviceValueDataType.STR8Q:
- //case DeviceValueDataType.STR8W1252:
- case ValueDataType.STR8: return 4;
- //10bytes
- case ValueDataType.STR10E:
- case ValueDataType.STR10S:
- //case DeviceValueDataType.STR10Q:
- //case DeviceValueDataType.STR10W1252:
- case ValueDataType.STR10: return 5;
- //16bytes
- case ValueDataType.STR16E:
- case ValueDataType.STR16S:
- //case DeviceValueDataType.STR16Q:
- //case DeviceValueDataType.STR16W1252:
- case ValueDataType.STR16: return 8;
- //18bytes
- case ValueDataType.STR18E:
- case ValueDataType.STR18S:
- //case DeviceValueDataType.STR18Q:
- //case DeviceValueDataType.STR18W1252:
- case ValueDataType.STR18: return 9;
- //20bytes
- case ValueDataType.STR20E:
- case ValueDataType.STR20S:
- //case DeviceValueDataType.STR20Q:
- //case DeviceValueDataType.STR20W1252:
- case ValueDataType.STR20: return 10;
- //22bytes
- case ValueDataType.STR22E:
- case ValueDataType.STR22S:
- //case DeviceValueDataType.STR22Q:
- //case DeviceValueDataType.STR22W1252:
- case ValueDataType.STR22: return 11;
- //30bytes
- case ValueDataType.STR30E:
- case ValueDataType.STR30S:
- //case DeviceValueDataType.STR30Q:
- //case DeviceValueDataType.STR30W1252:
- case ValueDataType.STR30: return 15;
- //32bytes
- case ValueDataType.STR32E:
- case ValueDataType.STR32S:
- //case DeviceValueDataType.STR32Q:
- //case DeviceValueDataType.STR32W1252:
- case ValueDataType.STR32: return 16;
- //64bytes
- case ValueDataType.STR64E:
- case ValueDataType.STR64S:
- //case DeviceValueDataType.STR64Q:
- //case DeviceValueDataType.STR64W1252:
- case ValueDataType.STR64: return 32;
- //100bytes
- case ValueDataType.STR100E:
- case ValueDataType.STR100S:
- //case DeviceValueDataType.STR100Q:
- //case DeviceValueDataType.STR100W1252:
- case ValueDataType.STR100: return 50;
- //128bytes
- case ValueDataType.STR128E:
- case ValueDataType.STR128S:
- //case DeviceValueDataType.STR128Q:
- //case DeviceValueDataType.STR128W1252:
- //case DeviceValueDataType.STR128W1252rec:
- case ValueDataType.STR128: return 64;
- //160bytes
- //case DeviceValueDataType.STR160E:
- //case DeviceValueDataType.STR160S:
- //case DeviceValueDataType.STR160Q:
- //case DeviceValueDataType.STR160W1252:
- //case DeviceValueDataType.STR160: return 80;
- //240bytes
- case ValueDataType.STR240E:
- case ValueDataType.STR240S:
- //case DeviceValueDataType.STR240Q:
- //case DeviceValueDataType.STR240W1252:
- case ValueDataType.STR240: return 240;
- #endregion
- default:
- throw (new Exception("No known length for tag = " + DataType.ToString()));
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "WLength"));
- }
- }
-
- ///
- /// Return the text length for value type if it is a text
- ///
- ///
- public static int StringLength(this ValueDataType DataType)
- {
- try
- {
- switch (DataType)
- {
- //case DeviceValueDataType.U32IPV4: return (4 * 3 + 3);
- default:
- if (DataType.IsSMSText())
- { // is SMS
- return DataType.Length() / 2; // is always 16bit
- }
- return Length(DataType);
- }
- }
- catch (Exception ex)
- {
- throw new Exception(ex.ToFuncErrorText(typeof(DeviceValueEncoder).ToString(), "StringLength"));
- }
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/LayoutType.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/LayoutType.cs
deleted file mode 100644
index e1cad01c..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/LayoutType.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Communication.ValueEncoders {
- public enum LayoutType {
- Normal,
- SwapAll,
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoder.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoder.cs
deleted file mode 100644
index b9654183..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoder.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-using System;
-using System.Text;
-using XYLEM.Communication;
-
-namespace XYLEM.Communication.ValueEncoders {
- public static class StringEncoder {
- public static Encoding GetDefaultEncoding( ) {
- try {
- return Encoding.GetEncoding( "Windows-1252"/*Strings._CONFIG_STD_String_DefaultCharacterEncoding*/ );
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rGetDefaultEncoding"+ "\n\rError when making default encoding with = "+ "\n\rWindows-1252"/*Strings._CONFIG_STD_String_DefaultCharacterEncoding*/, ex );
- }
- //Legacy code return Encoding.GetEncoding( 1252 );
- }
-
- ///
- /// Standard Windows iso-8859-1-encoding page.
- ///
- static Encoding s_Encoder = GetDefaultEncoding( ); // Default Fallback
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static byte[] Encode(string value, int lenght, string CharacterSet) {
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length is too long", "value" );
- }
- var result = new byte[ lenght ];
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- Encoding.GetEncoding( CharacterSet ).GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rEncode"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ + Environment.NewLine + ex.Message );
- }
- // Use defalt
- s_Encoder.GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static byte[] Encode(string value, int lenght) { return Encode( value, lenght, null ); }
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static string Decode(byte[] value, int lenght, string CharacterSet) {
- if (value.Length != lenght) {
- throw new ArgumentException( "value.Length wrong lenght", "value" );
- }
- string result = null;
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- result = Encoding.GetEncoding( CharacterSet ).GetString( value );
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rDecode()"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ + Environment.NewLine + ex.Message );
- }
- // Use defalt
- if (result == null) {
- result = s_Encoder.GetString( value );
- }
- var index = result.IndexOf( '\0' );
- if (index >= 0)
- return result.Substring( 0, result.IndexOf( '\0' ) );
- else
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static string Decode(byte[] value, int lenght) { return Decode( value, lenght, null ); }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail.cs
deleted file mode 100644
index 3d0850ce..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail.cs
+++ /dev/null
@@ -1,95 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace XYLEM.Communication.ValueEncoders {
- public static class StringEncoderEmail {
- public static Encoding GetDefaultEncoding( ) {
- try {
- return Encoding.GetEncoding( "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ );
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString( )+ "\n\rGetDefaultEncoding"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- // Legacy code return Encoding.GetEncoding( "iso-8859-1" );
- }
-
-
- ///
- /// Standard Windows iso-8859-1-encoding page.
- ///
- static Encoding s_Encoder = GetDefaultEncoding( ); // Default Fallback
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static byte[] Encode(string value, int lenght, string CharacterSet) {
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length is too long", "value" );
- }
- var result = new byte[ lenght ];
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- Encoding.GetEncoding( CharacterSet ).GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString( )+ "\n\rEncode()"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/,ex );
- }
- // Use defalt
- s_Encoder.GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static byte[] Encode(string value, int lenght) { return Encode( value, lenght, null ); }
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static string Decode(byte[] value, int lenght, string CharacterSet) {
- if (value.Length != lenght) {
- throw new ArgumentException( "value.Length wrong lenght", "value" );
- }
- string result = null;
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- result = Encoding.GetEncoding( CharacterSet ).GetString( value );
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString()+ "\n\rDecode()"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- // Use defalt
- if (result == null) {
- result = s_Encoder.GetString( value );
- }
- var index = result.IndexOf( '\0' );
- if (index >= 0) {
-
- return result.Substring( 0, result.IndexOf( '\0' ) );
- }
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static string Decode(byte[] value, int lenght) { return Decode( value, lenght, null ); }
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail_Q_Types.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail_Q_Types.cs
deleted file mode 100644
index 37dcb471..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderEmail_Q_Types.cs
+++ /dev/null
@@ -1,175 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Globalization;
-
-namespace XYLEM.Communication.ValueEncoders {
- public static class StringEncoderEmail_Q_Types {
- static string DefaultEncoding = "iso-8859-1";
-
- public static Encoding GetDefaultEncoding( ) {
- try {
- return Encoding.GetEncoding( "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ );
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString( ) + "\n\rGetDefaultEncoding" + "\n\rError when making default encoding with = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- // Legacy code return Encoding.GetEncoding( DefaultEncoding );
- }
-
- #region Converting to Quoted Printable
- //http://stackoverflow.com/questions/11793734/code-for-encode-decode-quotedprintable
-
- public static byte[] EncodeQ(byte[] value, int lenght) {
- if (value.First( ) == 0) {
- return value;
- }
- List ret = new List( );
- foreach (byte v in value) {
- // The following are not required to be encoded:
- // - Tab (ASCII 9)
- // - Space (ASCII 32)
- // - Characters 33 to 126, except for the equal sign (61).
- if ((v == 9) || ((v >= 32) && (v <= 60)) || ((v >= 62) && (v <= 126))) {
- if (ret.Count + 1 > lenght) { // Check for length is not over max
- break; // Stop converting
- }
- ret.Add( (byte)Convert.ToChar( v ) );
- } else {
- if (ret.Count + 3 > lenght) { // Check for length is not over max
- break; // Stop converting
- }
- if (v == 0) {
- ret.Add( 0 );
- break; // Stop terminate string
- }
- ret.AddRange( Encoding.UTF8.GetBytes( "=" + v.ToString( "X2" ) ) );
- }
- }
- char lastChar = (char)ret.Last( );
- if (char.IsWhiteSpace( lastChar )) {
- ret.RemoveAt( ret.Count( ) - 1 );
- if (!(ret.Count + 3 > lenght)) { // Check for length is not over max
- ret.AddRange( Encoding.UTF8.GetBytes( "=" + ((byte)lastChar).ToString( "X2" ) ) );
- }
- }
- if (ret.Count < lenght) { // Make sure length is correct
- ret.AddRange( new byte[ lenght - ret.Count ] );
- }
- return ret.ToArray( );
- }
-
- public static string DecodeQ(byte[] inputBytes, string charSet) {
- var input = (new UTF8Encoding( )).GetString( inputBytes );
- Encoding enc;
- try {
- enc = Encoding.GetEncoding( charSet );
- } catch {
- enc = new UTF8Encoding( );
- }
- var occurences = new Regex( @"(=[0-9A-Z]{2}){1,}", RegexOptions.Multiline );
- var matches = occurences.Matches( input );
-
- foreach (Match match in matches) {
- try {
- byte[] b = new byte[ match.Groups[ 0 ].Value.Length / 3 ];
- for (int i = 0; i < match.Groups[ 0 ].Value.Length / 3; i++) {
- b[ i ] = byte.Parse( match.Groups[ 0 ].Value.Substring( i * 3 + 1, 2 ), System.Globalization.NumberStyles.AllowHexSpecifier );
- }
- char[] hexChar = enc.GetChars( b );
- input = input.Replace( match.Groups[ 0 ].Value, new String( hexChar ) );
- } catch { ;}
- }
- input = input.Replace( "?=", "" ).Replace( "\r\n", "" );
- return input;
- }
- #endregion
-
- ///
- /// Standard Windows iso-8859-1-encoding page.
- ///
- static Encoding s_Encoder = GetDefaultEncoding( ); // Default Fallback
-
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static byte[] Encode(string value, int lenght, string CharacterSet) {
- byte[] ret = null;
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length is too long", "value" );
- }
- var result = new byte[ lenght ];
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- Encoding.GetEncoding( CharacterSet ).GetBytes( value ).CopyTo( result, 0 );
- ret = EncodeQ( result, lenght );
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString( )+ "\n\rEncode()" + "\n\rWith = " + "\n\riso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- if (ret == null) {
- // Use defalt
- s_Encoder.GetBytes( value ).CopyTo( result, 0 );
- ret = EncodeQ( result, lenght );
- }
- /*#warning "!!!!!!!!!!!!!!!!! Testing !!!!!!!!!!!!!!!!!!!!!!!"
- string test = new UTF8Encoding( ).GetString( ret );*/
- return ret;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static byte[] Encode(string value, int lenght) { return Encode( value, lenght, null ); }
-
- ///
- ///
- ///
- ///
- ///
- /// ex. "iso-8859-1"
- ///
- public static string Decode(byte[] value, int lenght, string CharacterSet) {
- if (value.Length != lenght) {
- throw new ArgumentException( "value.Length wrong lenght", "value" );
- }
- /*#warning "!!!!!!!!!!!!!!!!! Testing !!!!!!!!!!!!!!!!!!!!!!!"
- string test = new UTF8Encoding( ).GetString( value );*/
- string result = null;
- try {
- if (!String.IsNullOrEmpty( CharacterSet )) {
- result = DecodeQ( value, CharacterSet );
- }
- } catch (Exception ex) {
- throw new Exception( typeof( StringEncoderEmail ).ToString() + "\n\rDecode()" + "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/, ex );
- }
- // Use defalt
- if (result == null) {
- result = DecodeQ( value, DefaultEncoding );
- }
- var index = result.IndexOf( '\0' );
- if (index >= 0) {
- return result.Substring( 0, result.IndexOf( '\0' ) );
- }
- return result;
- }
-
- ///
- /// Use default characterSet
- ///
- ///
- ///
- ///
- public static string Decode(byte[] value, int lenght) { return Decode( value, lenght, null ); }
- }
-}
\ No newline at end of file
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderUnicode.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderUnicode.cs
deleted file mode 100644
index 0ac0ec5d..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoderUnicode.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-using System;
-using System.Text;
-using XYLEM.Communication;
-
-namespace XYLEM.Communication.ValueEncoders
-{
- public static class StringEncoderUnicode
- {
- ///
- /// Standard Windows 1252-encoding page.
- ///
- static Encoding s_Unicode = Encoding.BigEndianUnicode;
-
- public static byte[] Encode(string value, int lenght)
- {
- if (value.Length > lenght)
- {
- throw new ArgumentException("value.Length is too long", "value");
- }
-
- var result = new byte[lenght];
- s_Unicode.GetBytes(value).CopyTo(result, 0);
- return result;
- }
-
- public static string Decode(byte[] value, int lenght)
- {
- if (value.Length > lenght)
- {
- throw new ArgumentException("value.Length wrong lenght", "value");
- }
-
- var result = s_Unicode.GetString(value);
- var index = result.IndexOf('\0');
- if (index >= 0)
- return result.Substring(0, result.IndexOf('\0'));
- else
- return result;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoder_W1252.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoder_W1252.cs
deleted file mode 100644
index 25f0a58f..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/StringEncoder_W1252.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-using System;
-using System.Text;
-using XYLEM.Communication;
-
-namespace XYLEM.Communication.ValueEncoders {
- public static class StringEncoder_W1252 {
- public static Encoding GetDefaultEncoding( ) {
- return Encoding.GetEncoding( 1252 );
- }
-
- ///
- /// Standard Windows 1252-encoding page.
- ///
- static Encoding s_Win1252 = GetDefaultEncoding( );
-
- public static byte[] Encode(string value, int lenght) {
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length is too long", "value" );
- }
-
- var result = new byte[ lenght ];
- s_Win1252.GetBytes( value ).CopyTo( result, 0 );
- return result;
- }
-
- public static string Decode(byte[] value, int lenght) {
- if (value.Length > lenght) {
- throw new ArgumentException( "value.Length wrong lenght", "value" );
- }
-
- var result = s_Win1252.GetString( value );
- var index = result.IndexOf( '\0' );
- if (index >= 0)
- return result.Substring( 0, result.IndexOf( '\0' ) );
- else
- return result;
- }
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/U32_IP_Encoder.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/U32_IP_Encoder.cs
deleted file mode 100644
index 2f1770ea..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Communication/ValueEncoders/U32_IP_Encoder.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using XYLEM.Base;
-
-namespace XYLEM.Communication.ValueEncoders {
- ///
- /// IP Address encoder when it has to be converted to a u32 value
- ///
- internal static class U32_IP_Encoder {
- ///
- /// Check if string is okay and possible to encode
- ///
- ///
- ///
- internal static bool IsOkay(string stringForCheck) {
- try {
- if (string.IsNullOrEmpty( stringForCheck )) {
- return false; // if string empty, then this is off and there is nothing to check
- }
- try {
- var test = Encode( stringForCheck );
- } catch {
- return false; // Error is not possible to convert
- }
- return true; // Okay to convert
- } catch (Exception ex) {
- throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "IsOkay" ) );
- }
- }
-
- ///
- /// Encode xxx.xxx.xxx.xxx to bytes
- ///
- ///
- ///
- static internal byte[] Encode(string ip_XXX_XXX_XXX_XXX) {
- try {
- var splited = ip_XXX_XXX_XXX_XXX.Split( '.' );
- if (splited.Count( ) != 4) {
- throw new Exception( "IP must be formated xxx.xxx.xxx.xxx but is " + ip_XXX_XXX_XXX_XXX.ToString( ) );
- }
- var values = splited.Select( value => byte.Parse( value ) );
- return values.ToArray( );
- } catch (Exception ex) {
- throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "Encode" ) );
- }
- }
-
- ///
- /// decode bytes
- ///
- ///
- /// xxx.xxx.xxx.xxx
- static internal string Decode(byte[] data) {
- try {
- if ((data == null) || (data.Count( ) != 4)) {
- throw new Exception( "Must be 4 bytes" );
- }
- return String.Format( "{0}.{1}.{2}.{3}", data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ] );
- } catch (Exception ex) {
- throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "Decode" ) );
- }
- }
-
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Device/IMagFluxRequestProtocol.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Device/IMagFluxRequestProtocol.cs
deleted file mode 100644
index 0e91b68b..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Device/IMagFluxRequestProtocol.cs
+++ /dev/null
@@ -1,171 +0,0 @@
-using MagFlux6200_metrology_reg_list;
-using XYLEM.Communication;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO.Ports;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace XYLEM.Device
-{
- ///
- /// Command interface for MagFlux 6200
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7112855120/Command+Interface+Draft
- ///
- public interface IMagFluxRequestProtocol
- {
- ///
- /// Is connected
- ///
- /// true if yes
- Boolean IsConnected();
-
- ///
- /// Make communication connection to Meter
- /// !!NOTE!! Only one meter is supported for each com port
- ///
- /// Like "COM1"
- /// true on okay or false on error
- Boolean Connect(string comport);
-
- ///
- /// Close communication connection to Meter
- ///
- /// true on okay or false on error
- Boolean CloseConnection();
-
- ///
- /// Get printout of communication counters
- ///
- ///
- string GetComCounters();
-
- ///
- /// Set location for where log data can saved.
- ///
- /// path for where to log file should be saved
- /// set a custom log file name without extension (ex. "UserCustomLogFile") or null if use default
- /// true on okay or false on error
- Boolean SetLogLocation(String path, string filename = null);
-
- ///
- /// Open saved log file
- ///
- void OpenLogFile();
-
- ///
- /// MagFlux Sensor serial number
- ///
- /// a decimal serial number ex. 12345678 or NULL at error
- /// true on okay or false on error
- Boolean GetSensorSerialNo(out string value_out);
-
-
- ///
- /// Set MagFlux Sensor serial number
- ///
- ///
- /// true on okay or false on error
- Boolean SetSensorSerialNo(UInt32 new_serial_number);
-
- ///
- /// Unique-ID for the MagFlux electronics
- ///
- /// a hex decimal string 0x1234ABCDEF or NULL at error
- /// true on okay or false on error
- Boolean GetUniqueId(out string value_out);
-
- ///
- /// Get the firmware version
- ///
- /// like 1.2.4 (MAJOR.MINOR.REVISION)
- /// true on okay or false on error
- Boolean GetFirmwareVersion(out string value_out);
-
- ///
- /// Get the firmware build date
- ///
- /// like 2022/12/24 13:00:00 or 2022-12-24 13:45:10
- /// true on okay or false on error
- Boolean GetFwBuildDate(out string value_out);
-
- ///
- /// Git Hash to Unique identify firmware
- ///
- /// like 0xABCDE123
- /// true on okay or false on error
- Boolean GetFwGitHash(out string value_out);
-
- ///
- /// Flow rate calibrated
- ///
- /// Actual flow rate [l/s]
- /// true on okay or false on error
- Boolean GetFlowRate_lps(out Single value_out);
-
- ///
- /// MagFlux Sensor nominal DN size in millimeters
- ///
- /// DN size in [mm] is -1 on error
- /// true on okay or false on error
- Boolean GetDn_mm(out Int32 dn_mm_out);
-
- ///
- /// Set Sensor nominal DN size in millimeters
- ///
- /// DN size in [mm] ex 50 is 50mm or DN50
- /// true on okay or false on error
- Boolean SetDn_mm(UInt16 new_dn_mm);
-
- ///
- /// Check if there is problem with the DUT
- /// use " to get a list of error messages for debug problems
- ///
- /// >true if device operates correctly
- Boolean GetDeviceHealthy();
-
- ///
- /// get a list of error messages for debug problem
- ///
- /// Will return a empty list if there is no messages to return
- /// true on okay or false on error
- Boolean GetDeviceErrorMessages(out List status_list_out);
-
- ///
- /// This function prepares the DUT for the calibration.
- ///
- /// ATTENTION:
- /// This function needs to be called before the calibration process starts any flow of water.
- ///
- /// true on okay or false on error
- Boolean PrepareDeviceForCalibration();
-
- ///
- /// This function will abort started or failed calibration to bring DUT back to normal calibration state
- ///
- /// true on okay or false on error
- Boolean AbortDeviceForCalibration();
-
- ///
- /// The maximum calibration points that is supported by the device
- ///
- int CalibrationPointsMax { get; }
-
- ///
- /// Get list of calibration points saved in DUT
- ///
- /// The calibrations points from device
- /// true on okay or false on error
- Boolean GetCalibrationPoints(out CalibrationPoints values_read);
-
- ///
- /// set calibration in DUT.
- /// Remember to run before the calibration process is started.
- ///
- /// A list of calibration points to write to DUT
- /// true on okay or false on error
- Boolean SetCalibrationPoints(CalibrationPoints new_calibration_points);
- }
-}
diff --git a/Common/modbus_master_csharp/src/modbus_master_csharp/Device/MagFlux6200.cs b/Common/modbus_master_csharp/src/modbus_master_csharp/Device/MagFlux6200.cs
deleted file mode 100644
index f5ae46ea..00000000
--- a/Common/modbus_master_csharp/src/modbus_master_csharp/Device/MagFlux6200.cs
+++ /dev/null
@@ -1,1190 +0,0 @@
-using MagFlux6200_metrology_reg_list;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO.Ports;
-using System.Linq;
-using System.Numerics;
-using System.Runtime.CompilerServices;
-using System.Threading;
-using System.Threading.Tasks;
-using XYLEM.Base;
-using XYLEM.Base.Files;
-using XYLEM.Communication;
-
-namespace XYLEM.Device
-{
- public enum RUN_TYPE
- {
- ///
- /// Make real connections to a device
- ///
- Normal,
-
- ///
- /// Mock that just return static values and need not _serial connection or connected MagFlux hardware
- ///
- Mock
- }
-
- ///
- /// MagFlux 6200 "Metrology" device API.
- ///
- /// Handling serial communication with a single device during sensor Calibration and verification.
- ///
- /// Note: All Modbus register used needs to be documented in confluence, to show Modbus dependency and insure future support and comparability.
- /// Confluence page https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/7337054026/Modbus+register+-+Used+for+Sensor+calibration+and+verification+interface
- ///
- public class MagFlux6200 : ModbusDeviceCom, IMagFluxRequestProtocol
- {
- RUN_TYPE _runAs = RUN_TYPE.Normal;
-
- public MagFlux6200(RUN_TYPE runAs = RUN_TYPE.Normal) : base()
- {
- this._runAs = runAs;
- }
-
- public Boolean Connect(string comport)
- {
- try
- {
- /*metrology RS485 when transparent to metrology*/
- int baudRate = 9600;
- Parity parity = Parity.Even;
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- var result = Connect(comport, baudRate, parity);
- return result;
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail to open connection", ex);
- }
- return false; // failed
- }
-
- public override Boolean Connect(string comport, int baudRate, Parity parity)
- {
- try
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- {// Normal
- if (IsConnected())
- {
- CloseConnection();
- }
- var isOkay = base.Connect(comport, baudRate, parity);
- if (isOkay)
- {
- isOkay = Get_MdbsRegsVer(out var device_reglist_ver);
- var program_reglist_ver = (6200000 + reg_list.Met_U16DeviceType.Version);
- if (!isOkay)
- {
- var message = $"Device Modbus register list version is {(isOkay ? device_reglist_ver : "!Read failed!")}";
- Console.WriteLine(message);
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message);
- }
- else
- { // Check register list version
- var version = int.Parse(device_reglist_ver);
- if (program_reglist_ver != version)
- {
- // Warning to user that the register version is not the same as MagFlux has
- var message = $"Warning communicate!\nProgram use {program_reglist_ver} and may not supporting MagFlux {version}!";
- Console.WriteLine(message);
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message);
- isOkay = true;
- }
- else
- {
- Console.WriteLine($"Communication with Modbus register list ver. {program_reglist_ver}");
- }
- }
- if (!isOkay)
- {
- CloseConnection();
- }
- else
- {
- StartBackgroundChecking();
- }
- }
- return isOkay; // return result
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail to open connection", ex);
- }
- return false; // failed
- }
-
- #region Background service
- ///
- /// Device Healthy status that is periodically updated in background task
- ///
- private bool? _DeviceHealthy;
-
- ///
- /// List with info about what errors is detected
- ///
- private List _DeviceHealthyMsgList = new List();
-
- private UInt16 _Met_U16EmptyPipeStatus = 0;
- private UInt32 _Met_U32Errors = 0;
- private UInt16 _Met_U16Flow_CalibStatus = 0;
- private int _HandlerBackgroundReadStageNow = 0;
-
- ///
- /// Handle checking DUT and background reading device values
- ///
- ///
- protected override void RunBackgroundReadServiceFunction()
- {
- try
- {
- // Is just running as a Mock
- //if (true)
- if (_runAs == RUN_TYPE.Mock)
- {
- _DeviceHealthy = true; // is okay
- }
- else
- {// Normal
- // Run one value for every background task call
- switch (_HandlerBackgroundReadStageNow++)
- {
- case 0:
- { // Read errors
- var valueInfo = reg_list.Met_U32Errors;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- _Met_U32Errors = value.Value;
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- _Met_U32Errors = UInt32.MaxValue; // ERROR: Did not receive a value
- }
- }
- break;
- case 1:
- { // Read Empty pipe
- var valueInfo = reg_list.Met_U16EmptyPipeStatus;
- try
- {
- var value = read_U16(valueInfo);
- // Is okay
- if (value != null)
- {
- _Met_U16EmptyPipeStatus = value.Value;
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- _Met_U16EmptyPipeStatus = UInt16.MaxValue; // ERROR: Did not receive a value
- }
- }
- break;
- case 2:
- { // Read calibration state
- var valueInfo = reg_list.Met_U16Flow_CalibStatus;
- try
- {
- var value = read_U16(valueInfo);
- // Is okay
- if (value != null)
- {
- _Met_U16Flow_CalibStatus = value.Value;
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- _Met_U16Flow_CalibStatus = UInt16.MaxValue; // ERROR: Did not receive a value
- }
- }
- break;
- default:
- // Return to start
- _HandlerBackgroundReadStageNow=0;
- break;
-
- }
- UpdateDeviceHealthy();
- }
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail background service handling";
- Console.WriteLine(message);
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- _DeviceHealthy = false; // ERROR: Did failing updating value, then just put it as not Healthy
- _DeviceHealthyMsgList = new List()
- {
- "Unknown failing for updating device healthy"
- };
- }
- }
-
- private void UpdateDeviceHealthy()
- {
- try
- {
- var newHealthy = true;
- var newMsgList = new List();
- { // Check Errors
- if (_Met_U32Errors != 0)
- {
- newHealthy = false;
- if (_Met_U32Errors == UInt32.MaxValue)
- {
- newMsgList.Add("System error has unknown error");
- }
- else
- {
- newMsgList.Add($"System error 0x{_Met_U32Errors:X}");
- }
- }
- }
- { // Check empty pipe
- // https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6659966841/Empty+Pipe+Detection+EPD#Empty-pipe-status
- if ((_Met_U16EmptyPipeStatus&1) != 0) // If empty pipe active
- {
- newHealthy = false;
- // Bit for empty pipe used for show pipe level.
- switch ((_Met_U16EmptyPipeStatus >> 1) & 7)
- {
- case 0x01: // Below empty
- newMsgList.Add("Pipe Empty");
- break;
- case 0x02: // Between empty & full
- newMsgList.Add("Pipe Below Half");
- break;
- case 0x04: // Above full
- newMsgList.Add("Pipe Above full");
- break;
- default:
- if (_Met_U16EmptyPipeStatus == UInt16.MaxValue)
- {
- newMsgList.Add("Pipe Empty has unknown error");
- }
- break;
- }
- }
- }
- { // Check Calibration status
- var calstatus = GetCalErrStatus(_Met_U16Flow_CalibStatus);
- if (calstatus != CalibrationErrorStatus.AllOK)
- {
- newHealthy = false;
- newMsgList.Add(GetCalErrText(calstatus));
- }
- }
- // Update to the new status
- _DeviceHealthy = newHealthy;
- _DeviceHealthyMsgList = newMsgList;
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail updating device healthy", ex);
- _DeviceHealthy = false; // ERROR: indicate error
- }
- }
- #endregion // Background service
-
- class CalPointsRegInfo
- {
- internal Device_value Reference { get; }
- internal Device_value Reported { get; }
-
- public CalPointsRegInfo(Device_value reference, Device_value reported)
- {
- Reference = reference;
- Reported = reported;
- }
-
- public override string ToString()
- {
- return $"Cal point ref={Reference.Name} rep={Reported.Name}";
- }
-
- }
-
- List NewCalRegInfoList = new List {
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt0_lps, reg_list.Met_F32Flow_NewReportedPt0_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt1_lps, reg_list.Met_F32Flow_NewReportedPt1_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt2_lps, reg_list.Met_F32Flow_NewReportedPt2_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt3_lps, reg_list.Met_F32Flow_NewReportedPt3_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt4_lps, reg_list.Met_F32Flow_NewReportedPt4_lps),
- new CalPointsRegInfo(reg_list.Met_F32Flow_NewReferencePt5_lps, reg_list.Met_F32Flow_NewReportedPt5_lps),
- };
-
- ///
- /// Present accepted Calibration (Note is read only)
- ///
- List PresentCalRegInfoList = new List {
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint0_reference_lps, reg_list.Met_F32FlowPresentPoint0_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint1_reference_lps, reg_list.Met_F32FlowPresentPoint1_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint2_reference_lps, reg_list.Met_F32FlowPresentPoint2_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint3_reference_lps, reg_list.Met_F32FlowPresentPoint3_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint4_reference_lps, reg_list.Met_F32FlowPresentPoint4_reported_lps),
- new CalPointsRegInfo(reg_list.Met_F32FlowPresentPoint5_reference_lps, reg_list.Met_F32FlowPresentPoint5_reported_lps),
- };
-
- public int CalibrationPointsMax { get { return NewCalRegInfoList.Count; } }
-
-
- #region Calibration Error flags
- ///
- /// Calibration Error flags
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- [Flags]
- enum CalibrationErrorStatus
- {
- ///
- /// Bits 0000: All OK
- ///
- AllOK = 0,
-
- ///
- /// Bits 0001: Bad point
- ///
- ErrorInPoint = 0b0001,
-
- ///
- /// Bits 0010: Bad gradient
- ///
- ErrorInGradient = 0b0010,
-
- ///
- /// Bits 1111: Bad other
- ///
- GeneralError = 0b1111,
-
- ///
- /// Haven't any knowledge on it you
- ///
- UnkownError = 0xFFFF,
- }
-
- ///
- /// Get the cal error status from Calibration status register
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- /// Read from "Met_U16Flow_CalibCtrl"
- ///
- CalibrationErrorStatus GetCalErrStatus(UInt16 CalibStatus)
- {
- var status = (CalibStatus&0xF00)>>8;
- try
- {
- return (CalibrationErrorStatus)status;
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to convert {status} to {typeof(CalibrationErrorStatus)}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- return CalibrationErrorStatus.UnkownError;
- }
-
- }
-
- static string AppendErrorTxt(ref string to, string append)
- {
- to = $"{to}[{append}]";
- return to;
- }
-
- ///
- /// Convert the calibration error to a string
- ///
- ///
- ///
- string GetCalErrText(CalibrationErrorStatus status)
- {
- var ret = "";
- switch (status)
- {
- case CalibrationErrorStatus.AllOK:
- AppendErrorTxt(ref ret, "All Cal OK");
- break;
- case CalibrationErrorStatus.ErrorInPoint:
- AppendErrorTxt(ref ret, "Error in point");
- break;
- case CalibrationErrorStatus.ErrorInGradient:
- AppendErrorTxt(ref ret, "Error in gradient");
- break;
- case CalibrationErrorStatus.UnkownError:
- AppendErrorTxt(ref ret, "Unknown error");
- break;
- default:
- AppendErrorTxt(ref ret, $"Unknown error 0x{status:X}");
- break;
- }
- return ret;
- }
- #endregion //#region Calibration Error flags
-
- ///
- /// Calibration state
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- enum CalibrationState
- {
- Normal = 0,
- CalibrationMode = 1,
- UnkownError,
- }
-
- ///
- /// Convert the Calibration State to a string
- ///
- ///
- ///
- string GetCalStateText(CalibrationState state)
- {
- var ret = "";
- switch (state)
- {
- case CalibrationState.Normal:
- AppendErrorTxt(ref ret, "Normal");
- break;
- case CalibrationState.CalibrationMode:
- AppendErrorTxt(ref ret, "Calibration Mode");
- break;
- case CalibrationState.UnkownError:
- AppendErrorTxt(ref ret, "Unknown error");
- break;
- default:
- AppendErrorTxt(ref ret, $"Unknown state 0x{state:X}");
- break;
- }
- return ret;
- }
-
- ///
- /// Get current calibration state from Calibration status register
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- /// Read from "Met_U16Flow_CalibCtrl"
- ///
- CalibrationState GetCurrentCalState(UInt16 CalibStatus)
- {
- var status = (CalibStatus&0x1);
- try
- {
- return (CalibrationState)status;
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to convert {status} to {typeof(CalibrationState)}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- return CalibrationState.UnkownError;
- }
- }
-
- ///
- /// Get current calibration state from Calibration status register
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- /// Read from "Met_U16Flow_CalibCtrl"
- ///
- CalibrationState GetPreviousCalState(UInt16 CalibStatus)
- {
- var status = ((CalibStatus&0xC)>>2);
- try
- {
- return (CalibrationState)status;
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to convert {status} to {typeof(CalibrationState)}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- return CalibrationState.UnkownError;
- }
- }
-
- enum CalibrationCommand
-
- {
- ///
- /// 00: Unused
- ///
- Unused = 0b00,
-
- ///
- /// 01: Enter
- ///
- Enter = 0b01,
-
- ///
- /// 10: Confirm
- ///
- Confirm = 0b10,
-
- ///
- /// 11: Abort
- ///
- Abort = 0b11,
-
- ///
- /// Unknown error
- ///
- UnkownError = 0xFFFF
- }
-
- ///
- /// Get current calibration state from Calibration status register
- /// https://xyleminc.atlassian.net/wiki/spaces/MJKMF/pages/6661802342/Calibration+guide#Calibration-Status-Register
- ///
- /// Read from "Met_U16Flow_CalibCtrl"
- ///
- CalibrationCommand GetPreviousCalCommand(UInt16 CalibStatus)
- {
- var status = ((CalibStatus&0x20)>>5);
- try
- {
- return (CalibrationCommand)status;
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to convert {status} to {typeof(CalibrationCommand)}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- return CalibrationCommand.UnkownError;
- }
- }
-
- ///
- /// Set a calibration command in device
- ///
- ///
- ///
- bool SetCalCommand(CalibrationCommand command)
- {
- var isOkay = false;
- try
- {
- isOkay = write_U16(reg_list.Met_U16Flow_CalibCtrl, (UInt16)command);
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to write {command}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- }
- return isOkay;
- }
-
- public Boolean GetDeviceErrorMessages(out List status_list_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- status_list_out = new List(); // is okay
- return true; // is okay
- }
- {// Normal
- //TODO: There is not errors to convert yet throw new System.NotImplementedException();
- status_list_out = _DeviceHealthyMsgList; // is okay
- return true; // is okay
- }
- }
-
- public Boolean GetDeviceHealthy()
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- var wait_max_s = 5;
- var wait_pull_ms = 10;
- var start_wait_count = wait_max_s*(1000.0/wait_pull_ms);
- while (_DeviceHealthy == null)
- {
- Thread.Sleep(wait_pull_ms);
- if (start_wait_count-- <=0)
- {
- throw new Exception("Fail getting a updated DeviceHealthy");
- }
- }
- return _DeviceHealthy.Value;
- }
-
- public Boolean GetDn_mm(out Int32 dn_mm_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- dn_mm_out = 50; // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U16PipeDiameterConfig_mm;
- try
- {
- var value = read_U16(valueInfo);
- // Is okay
- if (value != null)
- {
- dn_mm_out = (int)value.Value;
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- dn_mm_out = -1; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
- public bool SetDn_mm(UInt16 new_dn_mm)
- {
- var isOkay = false;
- try
- {
- isOkay = GetDn_mm(out var current);
- // Only write DN if different
- if(current != new_dn_mm)
- {
- isOkay &= write_U16(reg_list.Met_U16PipeDiameterConfig_mm, (UInt16)new_dn_mm);
- }
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to write DN {new_dn_mm}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- }
- return isOkay;
- }
-
- public Boolean GetFirmwareVersion(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out="1.2.3"; // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32FirmwareVersion;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- var GIT_VERSION_MAJOR = value>>24;
- var GIT_VERSION_MINOR = (value>>16) & ((1<<16)-1);
- var GIT_VERSION_REVISION = (value & ((1<<16)-1));
- value_out = $"{GIT_VERSION_MAJOR}.{GIT_VERSION_MINOR}.{GIT_VERSION_REVISION}";
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
- public Boolean GetFlowRate_lps(out Single value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = 1.2345F; // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_F32FlowRate_lps;
- try
- {
- var value = read_F32(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = value.Value;
- return true; // is okay
- }
- throw new Exception("value returned was null");
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = 0; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
- public Boolean GetFwBuildDate(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = TimeConvertClass.ToLocalDateTimeString(DateTime.Now); // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32FmwrBuildDate;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- int year = (int)(value.Value/1000000);
- int Month = (int)((value.Value%1000000)/10000);
- int day = (int)((value.Value%10000)/100);
- int hour = (int)(value.Value%100);
- DateTime time = new DateTime(year, Month, day, hour, 0, 0);
- value_out = TimeConvertClass.ToLocalDateTimeString(time);
- return true; // is okay
- }
- throw new Exception("value returned was null");
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
-
- public Boolean Get_MdbsRegsVer(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = (6200000 + reg_list.Met_U16DeviceType.Version).ToString(); // is okay
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32MdbsRegsVer;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = value.ToString();
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
-
- public Boolean GetFwGitHash(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = "0xF3573B9";
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32FmwrGITHash;
- try
- {
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = $"0x{value:X}";
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
-
- public Boolean GetSensorSerialNo(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = "0";
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U32SensorSerialNo;
- try
- {
- // TODO: is this to be converted to new format maybe like yyyy/mm/day
- var value = read_U32(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = $"{value}";
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
-
- public bool SetSensorSerialNo(UInt32 new_serial_number)
- {
- var isOkay = false;
- try
- {
- isOkay = write_U32(reg_list.Met_U32SensorSerialNo, new_serial_number);
- }
- catch (Exception ex)
- {
-#if (DEBUG)
- var message = $"Fail to write Sensor SN {new_serial_number}";
- AppConst.Logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), message, ex);
-#endif // #if (DEBUG)
- }
- return isOkay;
- }
-
-
-
- public Boolean GetUniqueId(out string value_out)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- value_out = "0";
- return true; // is okay
- }
- {// Normal
- var valueInfo = reg_list.Met_U128_CPU_ID;
- try
- {
- var value = read_U128(valueInfo);
- // Is okay
- if (value != null)
- {
- value_out = $"0x{value:x}";
- return true; // is okay
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(valueInfo.Name), "Fail to read value", ex);
- }
- value_out = "?"; // ERROR: Did not receive a value
- return false; // failed
- }
- }
-
- #region Calibration points handling
- public Boolean GetCalibrationPoints(out CalibrationPoints values_read)
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- values_read = new CalibrationPoints(
- new List {
- new CalibrationPoint(0,0), // 0
- new CalibrationPoint(1,1), // 1
- new CalibrationPoint(5,5), // 2
- },
- CalibrationPointsMax
- );
- return true; // is okay
- }
- {// Normal
- try
- {
- var cals = new List();
- var calP_dvis = PresentCalRegInfoList;
- // ---------- Do read ----------
- var dvList = new List();
- // Add status
- var u16CalStatusReg = reg_list.Met_U16Flow_CalibStatus;
- dvList.Add(u16CalStatusReg);
- // Add cal points
- foreach (var point in calP_dvis)
- {
- dvList.Add(point.Reference);
- dvList.Add(point.Reported);
- }
- var reads = read(dvList);
- if ((reads == null) || (reads.Count == 0))
- {
- throw new Exception("No read data returned");
- }
- // ---------- Handle read respond ----------
- // Check that calibration needs to be in normal mode and accepted before getting the calibration.
- var u16CalStatusValue = reads.Find(data => data.Info == u16CalStatusReg);
- if ((u16CalStatusValue != null) && (u16CalStatusValue != null))
- {
- var calstatus = GetCalErrStatus((UInt16)u16CalStatusValue.Data);
- if (calstatus != CalibrationErrorStatus.AllOK)
- {
- throw new Exception($"Calibration status must be {GetCalErrText(CalibrationErrorStatus.AllOK)} and not {GetCalErrText(calstatus)}");
- }
- var calState = GetCurrentCalState((UInt16)u16CalStatusValue.Data);
- if (calState != CalibrationState.Normal)
- {
- throw new Exception($"Calibration state must be {GetCalStateText(CalibrationState.Normal)} and not {GetCalStateText(calState)}");
- }
- }
-
- // Get calibrations
- foreach (var point in PresentCalRegInfoList)
- {
- try
- {
- var ref_value_lps = reads.Find(data => data.Info == point.Reference);
- var rep_value_lps = reads.Find(data => data.Info == point.Reported);
- // Is okay
- if ((ref_value_lps != null) && (rep_value_lps != null))
- {
- cals.Add(new CalibrationPoint(Convert.ToSingle(ref_value_lps.Data), Convert.ToSingle(rep_value_lps.Data)));
- }
- else
- {
- throw new Exception("value returned was null");
- }
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(point.ToString()), "Fail to read values", ex);
- throw new Exception($"Faild cal point read of {point} ");
- }
- }
- values_read = new CalibrationPoints(cals, CalibrationPointsMax);
- return true; // is okay
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail to read value", ex);
- }
- values_read = null;
- return false; // failed
- }
- }
-
- public Boolean AbortDeviceForCalibration()
- {
-
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- {// Normal
- try
- {
- // Abort any calibration that have been started and possible failed.
- if (!SetCalCommand(CalibrationCommand.Abort))
- {
- throw new Exception("Was not able to abort calibration");
- }
- return true; // is okay
- }
- catch (Exception ex)
- {
- _logger.AddFuncLog(true, this.ToString(), _logger.GetCurrentMethod(), "Fail preparing for calibrations", ex);
- }
- return false; // failed
- }
- }
-
-
- public Boolean PrepareDeviceForCalibration()
- {
- // Is just running as a Mock
- if (_runAs == RUN_TYPE.Mock)
- {
- return true; // is okay
- }
- {// Normal
- try
- {
- // Generate default calibrations points to use for calibration
- var cals = new List