This commit is contained in:
Roland Drabesch
2024-05-06 15:46:18 +02:00
200 changed files with 7045 additions and 11366 deletions
+1 -1
View File
@@ -155,7 +155,7 @@
</site> </site>
<site name="MeterProcessState" id="2"> <site name="MeterProcessState" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool"> <application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\Users\drabesch_ro\Repo\lab\la_operations\laa_production\Common\Service\MeterProcessState" /> <virtualDirectory path="/" physicalPath="C:\Users\SZLATEV\source\repos\laa_production\Common\Service\MeterProcessState" />
</application> </application>
<bindings> <bindings>
<binding protocol="http" bindingInformation="*:56011:localhost" /> <binding protocol="http" bindingInformation="*:56011:localhost" />
+1
View File
@@ -30,6 +30,7 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=Consts/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Consts/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Cordonel/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Cordonel/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Cordonels/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Cordonels/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=CUST/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=dispached/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=dispached/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=DNMAX/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=DNMAX/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Drabesch/@EntryIndexedValue">True</s:Boolean> <s:Boolean x:Key="/Default/UserDictionary/Words/=Drabesch/@EntryIndexedValue">True</s:Boolean>
+2 -1
View File
@@ -8,7 +8,7 @@
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<RootNamespace>CommonConsole</RootNamespace> <RootNamespace>CommonConsole</RootNamespace>
<AssemblyName>CommonConsole</AssemblyName> <AssemblyName>CommonConsole</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion> <TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
@@ -85,5 +85,6 @@
<ItemGroup> <ItemGroup>
<None Include="app.config" /> <None Include="app.config" />
</ItemGroup> </ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<runtime> <runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" /> <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0"/>
</dependentAssembly> </dependentAssembly>
</assemblyBinding> </assemblyBinding>
</runtime> </runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8.1"/></startup></configuration>
@@ -63,6 +63,14 @@
/// </summary> /// </summary>
Unknown, Unknown,
/// <summary> /// <summary>
/// Meter application detected but not checked
/// </summary>
MeterAppInstalledUnchecked,
/// <summary>
/// Meter application is not required
/// </summary>
MeterAppNotRequired,
/// <summary>
/// Delimiter for list /// Delimiter for list
/// </summary> /// </summary>
MeterAppStateListDelimiter MeterAppStateListDelimiter
@@ -20,47 +20,54 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Const
public MeterAppStateInfo() public MeterAppStateInfo()
{ {
_stateInfos = new MeterAppStateText[(Int32)MeterAppState.MeterAppStateListDelimiter]; _stateInfos = new MeterAppStateText[(Int32)MeterAppState.MeterAppStateListDelimiter];
_stateInfos[0].State = MeterAppState.MeterAppNotInstalled;
_stateInfos[0].Message = Resources.StrMeterAppNotInstalled; _stateInfos[(Int32)MeterAppState.MeterAppNotInstalled].State = MeterAppState.MeterAppNotInstalled;
_stateInfos[(Int32)MeterAppState.MeterAppNotInstalled].Message = Resources.StrMeterAppNotInstalled;
_stateInfos[1].State = MeterAppState.MeterAppUpToDate; _stateInfos[(Int32)MeterAppState.MeterAppNotRequired].State = MeterAppState.MeterAppNotRequired;
_stateInfos[1].Message = Resources.StrMeterAppUpToDate; _stateInfos[(Int32)MeterAppState.MeterAppNotRequired].Message = Resources.StrMeterAppNotRequired;
_stateInfos[2].State = MeterAppState.MeterAppInstallationRequired; _stateInfos[(Int32)MeterAppState.MeterAppUpToDate].State = MeterAppState.MeterAppUpToDate;
_stateInfos[2].Message = Resources.StrMeterAppInstallationRequired; _stateInfos[(Int32)MeterAppState.MeterAppUpToDate].Message = Resources.StrMeterAppUpToDate;
_stateInfos[3].State = MeterAppState.MeterAppVersionOutdated; _stateInfos[(Int32)MeterAppState.MeterAppInstallationRequired].State = MeterAppState.MeterAppInstallationRequired;
_stateInfos[3].Message = Resources.StrMeterAppVersionOutdated; _stateInfos[(Int32)MeterAppState.MeterAppInstallationRequired].Message = Resources.StrMeterAppInstallationRequired;
_stateInfos[4].State = MeterAppState.InvalidCrc; _stateInfos[(Int32)MeterAppState.MeterAppVersionOutdated].State = MeterAppState.MeterAppVersionOutdated;
_stateInfos[4].Message = Resources.StrInvalidCrc; _stateInfos[(Int32)MeterAppState.MeterAppVersionOutdated].Message = Resources.StrMeterAppVersionOutdated;
_stateInfos[5].State = MeterAppState.MeterAppErasureRequired; _stateInfos[(Int32)MeterAppState.InvalidCrc].State = MeterAppState.InvalidCrc;
_stateInfos[5].Message = Resources.StrMeterAppErasureRequired; _stateInfos[(Int32)MeterAppState.InvalidCrc].Message = Resources.StrInvalidCrc;
_stateInfos[6].State = MeterAppState.MeterAppDownloadSucceeded; _stateInfos[(Int32)MeterAppState.MeterAppErasureRequired].State = MeterAppState.MeterAppErasureRequired;
_stateInfos[6].Message = Resources.StrMeterAppDownloadSucceeded; _stateInfos[(Int32)MeterAppState.MeterAppErasureRequired].Message = Resources.StrMeterAppErasureRequired;
_stateInfos[7].State = MeterAppState.MeterAppDownloadSuspicious; _stateInfos[(Int32)MeterAppState.MeterAppDownloadSucceeded].State = MeterAppState.MeterAppDownloadSucceeded;
_stateInfos[7].Message = Resources.StrMeterAppDownloadSuspicious; _stateInfos[(Int32)MeterAppState.MeterAppDownloadSucceeded].Message = Resources.StrMeterAppDownloadSucceeded;
_stateInfos[8].State = MeterAppState.MeterAppSuccessfulErased; _stateInfos[(Int32)MeterAppState.MeterAppDownloadSuspicious].State = MeterAppState.MeterAppDownloadSuspicious;
_stateInfos[8].Message = Resources.StrMeterAppSuccessfulErased; _stateInfos[(Int32)MeterAppState.MeterAppDownloadSuspicious].Message = Resources.StrMeterAppDownloadSuspicious;
_stateInfos[9].State = MeterAppState.MeterAppSuccessfulUpdated; _stateInfos[(Int32)MeterAppState.MeterAppSuccessfulErased].State = MeterAppState.MeterAppSuccessfulErased;
_stateInfos[9].Message = Resources.StrMeterAppSuccessfulUpdated; _stateInfos[(Int32)MeterAppState.MeterAppSuccessfulErased].Message = Resources.StrMeterAppSuccessfulErased;
_stateInfos[10].State = MeterAppState.MeterAppDownloadFailed; _stateInfos[(Int32)MeterAppState.MeterAppSuccessfulUpdated].State = MeterAppState.MeterAppSuccessfulUpdated;
_stateInfos[10].Message = Resources.StrMeterAppDownloadFailed; _stateInfos[(Int32)MeterAppState.MeterAppSuccessfulUpdated].Message = Resources.StrMeterAppSuccessfulUpdated;
_stateInfos[11].State = MeterAppState.MeterAppDownloadActive; _stateInfos[(Int32)MeterAppState.MeterAppDownloadFailed].State = MeterAppState.MeterAppDownloadFailed;
_stateInfos[11].Message = Resources.StrMeterAppDownloadActive; _stateInfos[(Int32)MeterAppState.MeterAppDownloadFailed].Message = Resources.StrMeterAppDownloadFailed;
_stateInfos[12].State = MeterAppState.FileAppInvalid; _stateInfos[(Int32)MeterAppState.MeterAppDownloadActive].State = MeterAppState.MeterAppDownloadActive;
_stateInfos[12].Message = Resources.StrFileAppInvalid; _stateInfos[(Int32)MeterAppState.MeterAppDownloadActive].Message = Resources.StrMeterAppDownloadActive;
_stateInfos[13].State = MeterAppState.Unknown; _stateInfos[(Int32)MeterAppState.FileAppInvalid].State = MeterAppState.FileAppInvalid;
_stateInfos[13].Message = ""; _stateInfos[(Int32)MeterAppState.FileAppInvalid].Message = Resources.StrFileAppInvalid;
_stateInfos[(Int32)MeterAppState.Unknown].State = MeterAppState.Unknown;
_stateInfos[(Int32)MeterAppState.Unknown].Message = Resources.StrMeterAppStateUnknown;
_stateInfos[(Int32)MeterAppState.MeterAppInstalledUnchecked].State = MeterAppState.MeterAppInstalledUnchecked;
_stateInfos[(Int32)MeterAppState.MeterAppInstalledUnchecked].Message = Resources.StrMeterAppDetected;
} }
/// <summary> /// <summary>
@@ -78,6 +78,15 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Properties {
} }
} }
/// <summary>
/// Looks up a localized string similar to Installed.
/// </summary>
public static string StrMeterAppDetected {
get {
return ResourceManager.GetString("StrMeterAppDetected", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to DOWNLOAD.... /// Looks up a localized string similar to DOWNLOAD....
/// </summary> /// </summary>
@@ -133,7 +142,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Properties {
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Application not required. /// Looks up a localized string similar to Not installed.
/// </summary> /// </summary>
public static string StrMeterAppNotInstalled { public static string StrMeterAppNotInstalled {
get { get {
@@ -141,6 +150,24 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Properties {
} }
} }
/// <summary>
/// Looks up a localized string similar to Not required.
/// </summary>
public static string StrMeterAppNotRequired {
get {
return ResourceManager.GetString("StrMeterAppNotRequired", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installation state unknown.
/// </summary>
public static string StrMeterAppStateUnknown {
get {
return ResourceManager.GetString("StrMeterAppStateUnknown", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Erasure succeeded. /// Looks up a localized string similar to Erasure succeeded.
/// </summary> /// </summary>
@@ -160,7 +187,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Properties {
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Up To Date. /// Looks up a localized string similar to Okay.
/// </summary> /// </summary>
public static string StrMeterAppUpToDate { public static string StrMeterAppUpToDate {
get { get {
@@ -118,16 +118,16 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<data name="StrMeterAppNotInstalled" xml:space="preserve"> <data name="StrMeterAppNotInstalled" xml:space="preserve">
<value>Anwendung nicht erforderlich</value> <value>Nicht installiert</value>
</data> </data>
<data name="StrMeterAppUpToDate" xml:space="preserve"> <data name="StrMeterAppUpToDate" xml:space="preserve">
<value>Version ist aktuell</value> <value>Okay</value>
</data> </data>
<data name="StrMeterAppInstallationRequired" xml:space="preserve"> <data name="StrMeterAppInstallationRequired" xml:space="preserve">
<value>Installation notwendig</value> <value>Installation notwendig</value>
</data> </data>
<data name="StrMeterAppVersionOutdated" xml:space="preserve"> <data name="StrMeterAppVersionOutdated" xml:space="preserve">
<value>Version ist unterschiedlich</value> <value>Update erforderlich</value>
</data> </data>
<data name="StrInvalidCrc" xml:space="preserve"> <data name="StrInvalidCrc" xml:space="preserve">
<value>Prüfsummenfehler (CRC)</value> <value>Prüfsummenfehler (CRC)</value>
@@ -156,4 +156,13 @@
<data name="StrFileAppInvalid" xml:space="preserve"> <data name="StrFileAppInvalid" xml:space="preserve">
<value>Ungültige Aktualisierungsdatei</value> <value>Ungültige Aktualisierungsdatei</value>
</data> </data>
<data name="StrMeterAppDetected" xml:space="preserve">
<value>Installiert</value>
</data>
<data name="StrMeterAppStateUnknown" xml:space="preserve">
<value>Installationszustand unbekannt</value>
</data>
<data name="StrMeterAppNotRequired" xml:space="preserve">
<value>Nicht eforderlich</value>
</data>
</root> </root>
@@ -118,10 +118,10 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<data name="StrMeterAppNotInstalled" xml:space="preserve"> <data name="StrMeterAppNotInstalled" xml:space="preserve">
<value>Application not required</value> <value>Not installed</value>
</data> </data>
<data name="StrMeterAppUpToDate" xml:space="preserve"> <data name="StrMeterAppUpToDate" xml:space="preserve">
<value>Up To Date</value> <value>Okay</value>
</data> </data>
<data name="StrMeterAppInstallationRequired" xml:space="preserve"> <data name="StrMeterAppInstallationRequired" xml:space="preserve">
<value>Installation required</value> <value>Installation required</value>
@@ -156,4 +156,13 @@
<data name="StrFileAppInvalid" xml:space="preserve"> <data name="StrFileAppInvalid" xml:space="preserve">
<value>INVALID UPDATE FILE</value> <value>INVALID UPDATE FILE</value>
</data> </data>
<data name="StrMeterAppDetected" xml:space="preserve">
<value>Installed</value>
</data>
<data name="StrMeterAppStateUnknown" xml:space="preserve">
<value>Installation state unknown</value>
</data>
<data name="StrMeterAppNotRequired" xml:space="preserve">
<value>Not required</value>
</data>
</root> </root>
@@ -219,6 +219,7 @@
<Compile Include="..\..\..\..\.shared\SharedAssemblyInfo.cs"> <Compile Include="..\..\..\..\.shared\SharedAssemblyInfo.cs">
<Link>Properties\SharedAssemblyInfo.cs</Link> <Link>Properties\SharedAssemblyInfo.cs</Link>
</Compile> </Compile>
<Compile Include="PowerCorrection.cs" />
<Compile Include="Consts\ErrorState.cs" /> <Compile Include="Consts\ErrorState.cs" />
<Compile Include="Consts\LedMode.cs" /> <Compile Include="Consts\LedMode.cs" />
<Compile Include="GenesisMeter.cs" /> <Compile Include="GenesisMeter.cs" />
@@ -3,6 +3,7 @@ using Newtonsoft.Json;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
@@ -10,6 +11,7 @@ using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Authentication; using System.Security.Authentication;
using System.Text; using System.Text;
using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using System.Timers; using System.Timers;
using NLog; using NLog;
@@ -176,6 +178,11 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
/// </summary> /// </summary>
private String _password; private String _password;
/// <summary>
/// reminder for last communication acknowledge code to detect communication errors
/// </summary>
private RequestAcknowledgeState _acknowledgeCode;
/// <summary> /// <summary>
/// default false only enabled by <see cref="EnableAutoLogon"/> /// default false only enabled by <see cref="EnableAutoLogon"/>
/// when it is true, the meter will enforce the login when session is gone or access is denied /// when it is true, the meter will enforce the login when session is gone or access is denied
@@ -1174,32 +1181,98 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
/// <summary> /// <summary>
/// Building the FW Version string out of 2 bytes of data. /// Building the FW Version string out of 2 bytes of data.
/// REASON: FLEXNETVERSION is one application which does not follow the same rule of /// REASON: FLEXNETVERSION is one application which does not follow the same rule of
/// decimal numbers. Instead it uses hexadecimal digits. After the conversion of this /// decimal numbers. Instead it uses hexadecimal digits.
/// number to a pure Uint32, needed for comparison of file versions in configuration.json,
/// the hexadecimal outline will be lost and the comparison with the rowproduct.txt fails.
/// FW-update needs this information to validate a tested package!
/// </summary> /// </summary>
/// <param name="fwVersion">version as hexadecimal result of version e.g. 0x1107 or 0x130B</param>
/// <param name="strVersion">any string to evaluate like "11.07" or "R1.1.07" or "1.3.0B"</param>
/// <param name="msb">most significant byte representing the major and minor version</param>
/// <param name="lsb">last significant byte representing the built version</param>
/// <returns>FLEXNET version string e.g. "R1.2.47" or "B1.2.0C" </returns>
public static String BuildFlexnetFwVersion(out UInt32 fwVersion, String strVersion, Byte? msb = null,
Byte? lsb = null)
{
var major = 0;
var minor = 0;
var builtMajor = 0;
var builtMinor = 0;
// preset version with 0 as undetected
fwVersion = 0;
if (msb != null && lsb != null)
{
major = (Int32)((msb & 0xF0) >> 4);
minor = (Int32)(msb & 0x0F);
builtMajor = (Int32)((lsb & 0xF0) >> 4);
builtMinor = (Int32)(lsb & 0x0F);
fwVersion = (UInt32)((msb << 8) + lsb);
}
else if (!string.IsNullOrEmpty(strVersion))
{
// this is always a string like 1.0.2D or 9.0.2D,
// a msb higher as 8 is indicating "B" version
var strResult = Regex.Replace(strVersion, "[^0-9,A-F,a-f]", "");
var strMajor = strResult.Substring(0, 1);
var strMinor = strResult.Substring(1, 1);
var strBuiltMajor = strResult.Substring(2, 1);
var strBuiltMinor = strResult.Substring(3, 1);
if (!UInt32.TryParse(strResult, NumberStyles.HexNumber, new CultureInfo("en"), out fwVersion)
|| !Int32.TryParse(strMajor, NumberStyles.HexNumber, new CultureInfo("en"), out major)
|| !Int32.TryParse(strMinor, NumberStyles.HexNumber, new CultureInfo("en"), out minor)
|| !Int32.TryParse(strBuiltMajor, NumberStyles.HexNumber, new CultureInfo("en"), out builtMajor)
|| !Int32.TryParse(strBuiltMinor, NumberStyles.HexNumber, new CultureInfo("en"), out builtMinor))
{
return "R" + strVersion;
}
}
// release version marked with "R"
if (major <= 8)
return $"R{major:X0}.{minor:X0}.{builtMajor:X0}{builtMinor:X0}";
// debug version marked with "B"
major -= 8;
return $"B{major:X0}.{minor:X0}.{builtMajor:X0}{builtMinor:X0}";
}
/// <summary>
/// Building the FW Version string out of 2 bytes of data.
/// </summary>
/// <param name="fwVersion">firmware version as hex</param>
/// <param name="msb">most significant byte</param> /// <param name="msb">most significant byte</param>
/// <param name="lsb">last significant byte</param> /// <param name="lsb">last significant byte</param>
/// <returns>converted "msb.lsb" as string e.g. "12.34" or "2.0C" </returns> /// <returns>converted "msb.lsb" as string e.g. "2.34" or "2.0C" </returns>
public static String BuildFwVersionString(Byte msb, Byte lsb) public static String BuildFwVersion(out UInt32 fwVersion, Byte msb, Byte lsb)
{ {
fwVersion = (UInt32)((msb << 8) + lsb);
//skip leading 0 //skip leading 0
var msbPartString = (msb & 0xF0) > 0 ? $"{(msb & 0xF0) >> 4:X0}" : ""; var msbPartString = (msb & 0xF0) > 0 ? $"{(msb & 0xF0) >> 4:X0}." : "";
return msbPartString + $"{msb & 0x0F:X0}" + "." + $"{(lsb & 0xF0) >> 4:X1}" + $"{lsb & 0x0F:X1}"; return msbPartString + $"{msb & 0x0F:X0}" + "." + $"{(lsb & 0xF0) >> 4:X1}" + $"{lsb & 0x0F:X1}";
} }
/// <summary> /// <summary>
/// Building a version string with 2 decimals e.g. " 12.34" /// Building the FW Version string out of UInt32 as hexadecimal input.
/// </summary> /// </summary>
/// <remarks date="2022-Dec-02" author="Thomas Wiedebusch"> /// <param name="fwVersion">firmware version as hex</param>
/// - Initial. /// <returns>converted "to "2.34" or "2.0C" </returns>
/// </remarks> public static String BuildFwVersionStringFromHex(UInt32 fwVersion)
/// <param name="version">the version</param>
/// <returns>converted version to string </returns>
public static String BuildFwVersionString(Int32? version)
{ {
return version == null ? "0.00" : $@"{version / 100}.{version % 100:D2}"; //skip leading 0
var msbPartString = (fwVersion & 0xF000) > 0 ? $"{(fwVersion & 0xF000) >> 12:X0}." : "";
return msbPartString + $"{(fwVersion & 0xF00) >> 8:X0}.{(fwVersion & 0x0F0) >> 4:X0}{fwVersion & 0x00F:X0}";
}
/// <summary>
/// Building the FW Version string out of Int32 as decimal input.
/// </summary>
/// <param name="fwVersion">firmware version as hex</param>
/// <returns>converted to "2.34" or "2.01" </returns>
public static String BuildFwVersionStringFromDec(Int32? fwVersion)
{
if (fwVersion == 0)
return "0.00";
return $"{fwVersion / 100}.{fwVersion % 100:D2}";
} }
/// <summary> /// <summary>
@@ -1208,10 +1281,15 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
public List<MeterApplications> MeterAppListVersion = new List<MeterApplications>(); public List<MeterApplications> MeterAppListVersion = new List<MeterApplications>();
/// <summary> /// <summary>
/// Core revision of boot code. /// Core revision of boot code as hex number.
/// </summary>
public UInt32 CoreRevision;
/// <summary>
/// Core revision of boot code as string.
/// </summary> /// </summary>
//public String CoreRevision; //public String CoreRevision;
public Int32? CoreRevision; public String StrCoreRevision;
/// <summary> /// <summary>
/// This is the FLEXNETVERSION version which describes the entire packet. /// This is the FLEXNETVERSION version which describes the entire packet.
@@ -1221,7 +1299,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
/// <summary> /// <summary>
/// This is the FLEXNETVERSION version which describes the entire packet. /// This is the FLEXNETVERSION version which describes the entire packet.
/// </summary> /// </summary>
public UInt32 InstalledFwVersion; public UInt32? InstalledFwVersion;
/// <summary> /// <summary>
/// This is the Metrology Lookup Table CRC. /// This is the Metrology Lookup Table CRC.
@@ -1331,7 +1409,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
{ {
foreach (var registerToCheck in tempConfigRegisters) foreach (var registerToCheck in tempConfigRegisters)
{ {
if (registerToCheck.Key?.RegisterDetail?.Version == null || if (registerToCheck.Key?.RegisterDetail?.Version == null ||
MeterAppListVersion.All(f => f.AppId != registerToCheck.Key.AppAddress)) MeterAppListVersion.All(f => f.AppId != registerToCheck.Key.AppAddress))
continue; continue;
@@ -1413,10 +1491,19 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
/// <remarks date="2024-Feb-22" author="Thomas Wiedebusch"> /// <remarks date="2024-Feb-22" author="Thomas Wiedebusch">
/// - Build dictionary for debug to observe if configuration.json contains overlapping versions. /// - Build dictionary for debug to observe if configuration.json contains overlapping versions.
/// </remarks> /// </remarks>
/// <remarks date="2024-Apr-23" author="Thomas Wiedebusch">
/// - On missing answer mark as communication error being able to compare against not-installed. This issue
/// was responsible to start a FW update process in the CUST as it assumes the installation was incomplete
/// but it couldn't detect those applications due to communication issues.
/// </remarks>
/// <remarks date="2024-May-06" author="Thomas Wiedebusch">
/// - BuildFlexnetFwVersion,
/// - Calculate core revision.
/// </remarks>
private void ReadMeterFirmwareAndAssignRegisters() private void ReadMeterFirmwareAndAssignRegisters()
{ {
// Avoid overwriting of list if this already exits // Avoid overwriting of list if this already exits
if (MeterAppListVersion.Any()) if (MeterAppListVersion.Any() && MeterAppListVersion.All(f => f.Status != MeterAppState.Unknown))
{ {
_logger.Warn($"Slot:{Slot} - Trying to override meter dictionary. Skip read out FW"); _logger.Warn($"Slot:{Slot} - Trying to override meter dictionary. Skip read out FW");
return; return;
@@ -1424,15 +1511,17 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
// On new readout reset the installed version // On new readout reset the installed version
InstalledFwVersion = 0; InstalledFwVersion = 0;
MeterAppListVersion.Clear();
//Get all existing applications from meter register dictionary //Get all existing applications from meter register dictionary
foreach (var appVersionToRead in _configApplications.OrderBy(o => o.AppId)) foreach (var meterApp in _configApplications.OrderBy(o => o.AppId))
{ {
UInt32 readFwVersion = 0; UInt32 readFwVersion = 0;
UInt16 readFwCrc = 0; UInt16 readFwCrc = 0;
var isInstalled = false; var isInstalled = false;
var installationStatus = MeterAppState.MeterAppNotInstalled;
var versionString = ""; var versionString = "";
if (WriteRegister(Register.System.CheckFwPresence, appVersionToRead.AppId)) if (WriteRegister(Register.System.CheckFwPresence, meterApp.AppId))
{ {
//read version, skip retries on SYSTEM 0x04-> FW nor present is a valid feedback //read version, skip retries on SYSTEM 0x04-> FW nor present is a valid feedback
var readFwVersionBytes = ReadRegister(Register.System.CheckFwPresence, 4); var readFwVersionBytes = ReadRegister(Register.System.CheckFwPresence, 4);
@@ -1440,40 +1529,53 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
//the FW version as UInt32 will be used for comparison with the configuration.json //the FW version as UInt32 will be used for comparison with the configuration.json
if (readFwVersionBytes != null && readFwVersionBytes.Length > 0) if (readFwVersionBytes != null && readFwVersionBytes.Length > 0)
{ {
readFwVersion = (UInt32)(((readFwVersionBytes[1] & 0xF0) >> 4) * 10 +
(readFwVersionBytes[1] & 0x0F)) * 100;
readFwVersion += (UInt32)(((readFwVersionBytes[0] & 0xF0) >> 4) * 10 +
(readFwVersionBytes[0] & 0x0F));
//build the version string, because e.g. FLEXNETVERSION is one application which does not //build the version string, because e.g. FLEXNETVERSION is one application which does not
//follow the same rule. After the upper conversion, the hexadecimal outline will be lost //follow the same rule. After the upper conversion, the hexadecimal outline will be lost
versionString = BuildFwVersionString(readFwVersionBytes[1], readFwVersionBytes[0]); if (meterApp.AppName == "FLEXNETVERSION")
if (appVersionToRead.AppName == "FLEXNETVERSION")
{ {
FwVersion = versionString; // msb and lsb are swapped during communication
FwVersion = BuildFlexnetFwVersion(out readFwVersion, null, readFwVersionBytes[1], readFwVersionBytes[0]);
versionString = FwVersion;
InstalledFwVersion = readFwVersion; InstalledFwVersion = readFwVersion;
} }
else
{
// msb and lsb are swapped during communication
versionString = BuildFwVersion(out readFwVersion, readFwVersionBytes[1], readFwVersionBytes[0]);
}
if (readFwVersion != 0) if (readFwVersion != 0)
{ {
isInstalled = true; isInstalled = true;
installationStatus = MeterAppState.MeterAppInstalledUnchecked;
//write application Id to CRC register //write application Id to CRC register
if (WriteRegister(Register.System.CheckFwCrc, appVersionToRead.AppId)) if (WriteRegister(Register.System.CheckFwCrc, meterApp.AppId))
{ {
readFwCrc = RegisterConverter.ByteArrayToValue<UInt16>(ReadRegister(Register.System.CheckFwCrc)); readFwCrc = RegisterConverter.ByteArrayToValue<UInt16>(ReadRegister(Register.System.CheckFwCrc));
} }
} }
} }
// missing answer
else if (RequestAcknowledgeState.NoResponse == _acknowledgeCode)
{
installationStatus = MeterAppState.Unknown;
}
}
// missing answer
else if (RequestAcknowledgeState.NoResponse == _acknowledgeCode)
{
installationStatus = MeterAppState.Unknown;
} }
//add application always, even if this is not installed. This will be used for FW updates //add application always, even if this is not installed. This will be used for FW updates
MeterAppListVersion.Add(new MeterApplications MeterAppListVersion.Add(new MeterApplications
{ {
AppId = appVersionToRead.AppId, AppId = meterApp.AppId,
Version = readFwVersion, Version = readFwVersion,
StrVersion = versionString, StrVersion = versionString,
AppName = appVersionToRead.AppName, AppName = meterApp.AppName,
Crc = readFwCrc, Crc = readFwCrc,
Status = isInstalled ? MeterAppState.Unknown : MeterAppState.MeterAppNotInstalled, Status = installationStatus,
IsInstalled = isInstalled, IsInstalled = isInstalled,
}); });
} }
@@ -1486,28 +1588,27 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
//read core revision //read core revision
var coreRegisterRead = RegisterConverter.ByteArrayToValue<String>(ReadRegister(Register.System.CoreRevision, 16)); var coreRegisterRead = RegisterConverter.ByteArrayToValue<String>(ReadRegister(Register.System.CoreRevision, 16));
CoreRevision = null; CoreRevision = 0;
StrCoreRevision = "";
if (!string.IsNullOrEmpty(coreRegisterRead)) if (!string.IsNullOrEmpty(coreRegisterRead))
{ {
var coreRevisionStrings = coreRegisterRead.Split('\0'); var coreRevisionStrings = coreRegisterRead.Split('\0');
//remove Cordonel sub-string and the blanks // remove Cordonel sub-string and the blanks
var coreRevisionSubString = $"{coreRevisionStrings[0].ToLower().Replace("cordonel ", "")}"; var coreRevisionSubString = $"{coreRevisionStrings[0].ToLower().Replace("cordonel ", "")}";
var coreRevisionSubStrings = coreRevisionSubString.Split('.'); var strResult = Regex.Replace(coreRevisionSubString, "[^0-9,A-F,a-f]", "");
if (int.TryParse(coreRevisionSubStrings[0], out var coreRevisionMsb)) if (UInt32.TryParse(strResult, NumberStyles.HexNumber, new CultureInfo("en"), out CoreRevision))
{ {
if (int.TryParse(coreRevisionSubStrings[1], out var coreRevisionLsb)) StrCoreRevision = BuildFwVersionStringFromHex(CoreRevision);
{
CoreRevision = coreRevisionMsb * 100 + coreRevisionLsb;
}
} }
} }
//log application information to file // log application information to file
_logger.Info($"Slot:{Slot} - PCB ID: {PcbId}"); _logger.Info($"Slot:{Slot} - PCB ID: {PcbId}");
_logger.Info($"Slot:{Slot} - Date time (UTC): {DateTimeOffset.UtcNow}"); _logger.Info($"Slot:{Slot} - Date time (UTC): {DateTimeOffset.UtcNow}");
if (CoreRevision != null) if (CoreRevision != 0)
{ {
_logger.Info($"Slot:{Slot} - System Core Revision: {BuildFwVersionString(CoreRevision)}"); _logger.Info($"Slot:{Slot} - System Core Revision: {StrCoreRevision}");
} }
_logger.Info($"Slot:{Slot} - Region: {Region}"); _logger.Info($"Slot:{Slot} - Region: {Region}");
@@ -1521,6 +1622,9 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
{ {
var versionString = fm.IsInstalled var versionString = fm.IsInstalled
? $"V: {fm.StrVersion} - CRC: 0x{fm.Crc:X4}" : "Not installed"; ? $"V: {fm.StrVersion} - CRC: 0x{fm.Crc:X4}" : "Not installed";
if (fm.Status == MeterAppState.Unknown)
versionString = "Communication error";
_logger.Info($"Slot:{Slot} - AppId: 0x{fm.AppId:X2} - {versionString} - AppName: {fm.AppName}"); _logger.Info($"Slot:{Slot} - AppId: 0x{fm.AppId:X2} - {versionString} - AppName: {fm.AppName}");
} }
@@ -2020,13 +2124,20 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
return null; return null;
} }
/// <summary>
/// Execute request protocol and acts on response code.
/// </summary>
/// <remarks date="2020-Dec-19" author="Thomas Wiedebusch"> /// <remarks date="2020-Dec-19" author="Thomas Wiedebusch">
/// - Removed throw because the throw always kicks in to /// - Removed throw because the throw always kicks in to
/// the FW-Update process causing an unpredictable stop! /// the FW-Update process causing an unpredictable stop!
/// </remarks> /// </remarks>
/// <remarks date="2024-Apr-22" author="Thomas Wiedebusch">
/// - Remind last communication acknowledge code.
/// </remarks>
private void RequestProtocolProcess() private void RequestProtocolProcess()
{ {
switch (RequestProtocol.ProcessRecordList()) _acknowledgeCode = RequestProtocol.ProcessRecordList();
switch (_acknowledgeCode)
{ {
case RequestAcknowledgeState.AuthorizationRequired: case RequestAcknowledgeState.AuthorizationRequired:
@@ -2359,7 +2470,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
apps.Add(new CordonelAppVersion(item.AppId, item.StrVersion, item.AppId != 15)); apps.Add(new CordonelAppVersion(item.AppId, item.StrVersion, item.AppId != 15));
} }
apps.Add(new CordonelAppVersion(-1, BuildFwVersionString(CoreRevision), false)); apps.Add(new CordonelAppVersion(-1, StrCoreRevision, false));
var url = $"{ServiceUrls.MeterProcessStateUrl()}SetCordonelProgress?PcbId={PcbId}" + var url = $"{ServiceUrls.MeterProcessStateUrl()}SetCordonelProgress?PcbId={PcbId}" +
$"&ProgressName={progressName}&version={version}"; $"&ProgressName={progressName}&version={version}";
@@ -2423,14 +2534,14 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
{ {
try try
{ {
var valuestring = "NULL"; var valueString = "NULL";
if (value != null) if (value != null)
{ {
valuestring = BitConverter.ToString(value); valueString = BitConverter.ToString(value);
} }
var url = $"{Configuration.RegisterWatchServiceUrl}RegisterWrite?PcbID={PcbId}&Address={BitConverter.ToString(reg.RegisterAddress)}&value={valuestring}"; var url = $"{Configuration.RegisterWatchServiceUrl}RegisterWrite?PcbID={PcbId}&Address={BitConverter.ToString(reg.RegisterAddress)}&value={valueString}";
var result = LocalWebRequest.PostRequestAsync(url, 1500, string.Empty); var result = LocalWebRequest.PostRequestAsync(url, 1500, string.Empty);
@@ -0,0 +1,153 @@
using System;
namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore
{
/// <summary>
/// Power correction parameters used for overestimated power consumption on
/// Cordonel FW update from:
/// EMEA below R1.3.x
/// NA below R2.0.07
/// </summary>
public class PowerCorrection
{
#region Data Base at EOL - Production
/// <summary>
/// Unique identification of PCB
/// </summary>
public String PcbId { get; set; }
/// <summary>
/// Date time UTC at EOL - Production
/// </summary>
public DateTime? ProductionDateTimeUtc { get; set; }
/// <summary>
/// Total used seconds at EOL - Production
/// </summary>
public UInt32 ProductionTotalUsedSeconds_s { get; set; }
/// <summary>
/// Total used charge of batteries at EOL - Production
/// </summary>
public UInt64 ProductionTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Radio system state at EOL - Production
/// </summary>
public Byte? ProductionRadioSystemState { get; set; }
/// <summary>
/// Pulse adapter was installed during at EOL - Production
/// </summary>
public Boolean ProductionPulseAdapterIsInstalled { get; set; }
/// <summary>
/// Pulse mode during at EOL - Production
/// </summary>
public Byte ProductionPulseMode { get; set; }
/// <summary>
/// Pulse sequence counter during at EOL - Production
/// </summary>
public Byte ProductionPulseSequenceCounter { get; set; }
/// <summary>
/// Pulse distribution at EOL - Production
/// </summary>
public Boolean ProductionPulseEvenDistribution { get; set; }
/// <summary>
/// Detected region at EOL - Production
/// </summary>
public String ProductionRegion { get; set; }
#endregion
#region Maintenance readout
/// <summary>
/// Detected FW version before maintenance
/// </summary>
public UInt32 ActualFwVersion { get; set; }
/// <summary>
/// Date time UTC at time of maintenance
/// </summary>
public DateTime? ActualDateTimeUtc { get; set; }
/// <summary>
/// Total used seconds before maintenance
/// </summary>
public UInt32 ActualTotalUsedSeconds_s { get; set; }
/// <summary>
/// Total used charge of batteries before maintenance
/// </summary>
public UInt64 ActualTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Actual detected radio system state at maintenance
/// </summary>
public Byte? ActualRadioSystemState { get; set; }
/// <summary>
/// Detection of pulse adapter installation
/// </summary>
public Boolean ActualPulseAdapterIsInstalled { get; set; }
/// <summary>
/// Pulse mode during maintenance
/// </summary>
public Byte ActualPulseMode { get; set; }
/// <summary>
/// Pulse distribution during maintenance
/// </summary>
public Boolean ActualPulseEvenDistribution { get; set; }
#endregion
#region Maintenance calculation
/// <summary>
/// FW version for the update
/// </summary>
public UInt32 RequiredFwVersion { get; set; }
/// <summary>
/// Calculated pulse report length
/// </summary>
public UInt32 PulseReportLength { get; set; }
/// <summary>
/// Total used seconds after EOL and before maintenance
/// </summary>
public UInt32 AfterProductionTotalUsedSeconds_s { get; set; }
/// <summary>
/// Overestimated total used charge before maintenance
/// </summary>
public UInt64 OverestimatedTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Lowest threshold for total used charge calculated during maintenance
/// </summary>
public UInt64 MinimumTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Corrected total used charge during maintenance
/// </summary>
public UInt64 CorrectedTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Size of power correction file
/// </summary>
public UInt32 MeterPowerCorrectionFileSize { get; set; }
/// <summary>
/// CRC of power correction file
/// </summary>
public UInt32 MeterPowerCorrectionCRC { get; set; }
#endregion
}
}
@@ -124,7 +124,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.Properties {
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Reading registers after update. /// Looks up a localized string similar to Reading registers after maintenance.
/// </summary> /// </summary>
internal static string StrReadRegistersAfterUpdate { internal static string StrReadRegistersAfterUpdate {
get { get {
@@ -133,7 +133,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore.Properties {
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Reading registers before update. /// Looks up a localized string similar to Reading registers before maintenance.
/// </summary> /// </summary>
internal static string StrReadRegistersBeforeUpdate { internal static string StrReadRegistersBeforeUpdate {
get { get {
@@ -148,10 +148,10 @@
<value>Schreibe Register</value> <value>Schreibe Register</value>
</data> </data>
<data name="StrReadRegistersBeforeUpdate" xml:space="preserve"> <data name="StrReadRegistersBeforeUpdate" xml:space="preserve">
<value>Lese Register vor dem Firmware Update</value> <value>Lese Register vor der Wartung</value>
</data> </data>
<data name="StrReadRegistersAfterUpdate" xml:space="preserve"> <data name="StrReadRegistersAfterUpdate" xml:space="preserve">
<value>Lese Register nach dem Firmware Update</value> <value>Lese Register nach der Wartung</value>
</data> </data>
<data name="StrRegisterRecoveryExec" xml:space="preserve"> <data name="StrRegisterRecoveryExec" xml:space="preserve">
<value>Ausführung Konfigurationswiederherstellungssequenz....</value> <value>Ausführung Konfigurationswiederherstellungssequenz....</value>
@@ -139,10 +139,10 @@
<value>Scan port</value> <value>Scan port</value>
</data> </data>
<data name="StrReadRegistersAfterUpdate" xml:space="preserve"> <data name="StrReadRegistersAfterUpdate" xml:space="preserve">
<value>Reading registers after update</value> <value>Reading registers after maintenance</value>
</data> </data>
<data name="StrReadRegistersBeforeUpdate" xml:space="preserve"> <data name="StrReadRegistersBeforeUpdate" xml:space="preserve">
<value>Reading registers before update</value> <value>Reading registers before maintenance</value>
</data> </data>
<data name="StrRegisterCompare" xml:space="preserve"> <data name="StrRegisterCompare" xml:space="preserve">
<value>Compare register</value> <value>Compare register</value>
@@ -116,6 +116,7 @@
<Compile Include="MeterLutUpdate.cs" /> <Compile Include="MeterLutUpdate.cs" />
<Compile Include="MeterFwUpdate.cs" /> <Compile Include="MeterFwUpdate.cs" />
<Compile Include="MeterFwUpdateCapability.cs" /> <Compile Include="MeterFwUpdateCapability.cs" />
<Compile Include="MeterPowerCorrectionFile.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="MeterFile.cs" /> <Compile Include="MeterFile.cs" />
<Compile Include="MeterPwdFile.cs" /> <Compile Include="MeterPwdFile.cs" />
@@ -330,9 +330,9 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
#region Compare #region Compare
/// <summary> /// <summary>
/// Compare file and meter applications /// Compare file and meter applications and update display code if required.
/// </summary> /// </summary>
/// <returns></returns> /// <param name="updateDisplayCode">true updates the display code</param>
/// <remarks date="2019-Jun-25" author="Thomas Wiedebusch"> /// <remarks date="2019-Jun-25" author="Thomas Wiedebusch">
/// - Initial /// - Initial
/// </remarks> /// </remarks>
@@ -345,7 +345,13 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
/// <remarks date="2019-Jul-02" author="Thomas Wiedebusch"> /// <remarks date="2019-Jul-02" author="Thomas Wiedebusch">
/// - Removed genesis meter has to be logged in /// - Removed genesis meter has to be logged in
/// </remarks> /// </remarks>
public void CompareAllMeterAndFileApps() /// <remarks date="2024-Apr-23" author="Thomas Wiedebusch">
/// - Removed MeterAppState.Unknown.
/// </remarks>
/// <remarks date="2024-Apr-25" author="Thomas Wiedebusch">
/// - Optional display code update.
/// </remarks>
public void CompareAllMeterAndFileApps(Boolean updateDisplayCode = false)
{ {
if (_genesisMeter == null || FileApps == null) if (_genesisMeter == null || FileApps == null)
{ {
@@ -356,34 +362,34 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
{ {
CompareMeterAppWithFileApp(meterApp); CompareMeterAppWithFileApp(meterApp);
} }
if (!_genesisMeter.IsLoggedOn)
if (updateDisplayCode)
{ {
//remind the login status to logout if not logged in here
var wasLoggedOn = _genesisMeter.IsLoggedOn;
_genesisMeter.ReLogin(); _genesisMeter.ReLogin();
var isUpToDate = _genesisMeter.MeterAppListVersion.All(
meterApp => meterApp.Status == MeterAppState.MeterAppUpToDate ||
meterApp.Status == MeterAppState.MeterAppNotRequired);
//set display code to up to date if not needed to be installed or up to date //set display code to up to date if not needed to be installed or up to date
_genesisMeter.SetProcessState(_genesisMeter.MeterAppListVersion.All( _genesisMeter.SetProcessState(isUpToDate ? DisplayCodes.FwUpToDate
f => f.Status == MeterAppState.MeterAppUpToDate || : DisplayCodes.FwUpdateFailed, false);
f.Status == MeterAppState.MeterAppNotInstalled || f.Status == MeterAppState.Unknown)
? DisplayCodes.FwUpToDate
: DisplayCodes.FwUpdateFailed, false);
_genesisMeter.Logout();
}
else
{
//set display code to up to date if not needed to be installed or up to date
_genesisMeter.SetProcessState(_genesisMeter.MeterAppListVersion.All(
f => f.Status == MeterAppState.MeterAppUpToDate ||
f.Status == MeterAppState.MeterAppNotInstalled || f.Status == MeterAppState.Unknown)
? DisplayCodes.FwUpToDate
: DisplayCodes.FwUpdateFailed, false);
}
if (!wasLoggedOn)
_genesisMeter.Logout();
}
} }
/// <summary> /// <summary>
/// Compare single meter application with file /// Check the meter app status and if this is not indicating the unknown status
/// compare the meter app with the file app to check for required action.
/// After comparison it marks the meter app status <see cref="MeterAppState"/> and
/// the "Update" or "Erase" request.
/// Preconditions:
/// - FileApps have to be preset.
/// </summary> /// </summary>
/// <returns></returns> /// <param name="meterApp">single application for check</param>
/// <remarks date="2019-Jun-29" author="Thomas Wiedebusch"> /// <remarks date="2019-Jun-29" author="Thomas Wiedebusch">
/// - Initial /// - Initial
/// </remarks> /// </remarks>
@@ -396,25 +402,35 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
/// <remarks date="2020-Dec-01" author="Thomas Wiedebusch"> /// <remarks date="2020-Dec-01" author="Thomas Wiedebusch">
/// - Meter state unknown if file apps not loaded /// - Meter state unknown if file apps not loaded
/// </remarks> /// </remarks>
/// <remarks date="2024-Apr-23" author="Thomas Wiedebusch">
/// - Return if communication error without change of meter app status
/// </remarks>
public void CompareMeterAppWithFileApp(MeterApplications meterApp) public void CompareMeterAppWithFileApp(MeterApplications meterApp)
{ {
meterApp.Update = false; meterApp.Update = false;
meterApp.Erase = false; meterApp.Erase = false;
//CASE -1: meter application is installed but files are not loaded //CASE -3: file apps not loaded, no comparison possible, leave everything as is
if (meterApp.IsInstalled && FileApps.Count == 0) if (FileApps.Count == 0)
{ {
meterApp.Status = MeterAppState.Unknown;
return; return;
} }
//CASE 0: meter application is not installed and update files are not loaded //CASE -2: meter application could not be read due to communication error
if (!meterApp.IsInstalled && FileApps.Count == 0) if (meterApp.Status == MeterAppState.Unknown)
{ {
meterApp.Status = MeterAppState.MeterAppNotInstalled; //CASE -2.1 Installation is required but installed app is not detected due to communication error
if (FileApps.Any(x => x.AppId == meterApp.AppId))
{
return;
}
//CASE -2.2 Installation not required as app is NOT in the fileApp list
meterApp.Status = MeterAppState.MeterAppNotRequired;
return; return;
} }
//compare file apps with meter apps and change meterApp.Status
foreach (var fileApp in FileApps) foreach (var fileApp in FileApps)
{ {
if (meterApp.AppId != fileApp.AppId) if (meterApp.AppId != fileApp.AppId)
@@ -495,7 +511,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
} }
//CASE 4.2: update file application not found and meter application is not installed //CASE 4.2: update file application not found and meter application is not installed
meterApp.Status = MeterAppState.Unknown; meterApp.Status = MeterAppState.MeterAppNotRequired;
} }
/// <summary> /// <summary>
@@ -713,7 +729,8 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
} }
_remainingFileAppsParts.Clear(); _remainingFileAppsParts.Clear();
_fwUpdateState = FwUpdateState.UpdateFailed; if (_stopUpdateProcess)
_fwUpdateState = FwUpdateState.UpdateFailed;
} }
} }
@@ -924,7 +941,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
_actualOperation = ""; _actualOperation = "";
//update file information //update file information
CompareAllMeterAndFileApps(); CompareAllMeterAndFileApps(true);
//logout/login/auto-login //logout/login/auto-login
ReestablishMeterFileSystem(); ReestablishMeterFileSystem();
@@ -989,12 +1006,16 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
/// <remarks date="2023-Jan-20" author="Thomas Wiedebusch"> /// <remarks date="2023-Jan-20" author="Thomas Wiedebusch">
/// - Set upgrade permission for metrology to 0xFF if required (will be done by GTB). /// - Set upgrade permission for metrology to 0xFF if required (will be done by GTB).
/// </remarks> /// </remarks>
/// <remarks date="2024-Apr-25" author="Thomas Wiedebusch">
/// - Reset retry counter.
/// </remarks>
public Boolean UpdatePreparation() public Boolean UpdatePreparation()
{ {
_actualOperation = Resources.StrFwUpdateStatePrepareUpdate; _actualOperation = Resources.StrFwUpdateStatePrepareUpdate;
_fwUpdateState = FwUpdateState.PrepareUpdate; _fwUpdateState = FwUpdateState.PrepareUpdate;
_processedBytesCtr = 0; _processedBytesCtr = 0;
_overallBytesCtr = 6; _overallBytesCtr = 6;
_updateProcedureRetryCtr = 0;
_meterFile = new MeterFile(_genesisMeter); _meterFile = new MeterFile(_genesisMeter);
if (_meterFile != null) if (_meterFile != null)
@@ -1411,12 +1432,8 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
/// </remarks> /// </remarks>
public static UInt32 GetFileAppVersion(Byte[] binData) public static UInt32 GetFileAppVersion(Byte[] binData)
{ {
return (UInt32)((binData[FileAppVersionIndex] & 0x0F) return (UInt32)(binData[FileAppVersionIndex] + (binData[FileAppVersionIndex + 1] << 8));
+ ((binData[FileAppVersionIndex] & 0xF0) >> 4) * 10
+ (binData[FileAppVersionIndex + 1] & 0x0F) * 100
+ ((binData[FileAppVersionIndex + 1] & 0xF0) >> 4) * 1000);
} }
/// <summary> /// <summary>
/// Check the content of the binaries: /// Check the content of the binaries:
/// - begins with "APP>", /// - begins with "APP>",
@@ -1432,15 +1449,29 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
/// <remarks date="2019-Jun-26" author="Thomas Wiedebusch"> /// <remarks date="2019-Jun-26" author="Thomas Wiedebusch">
/// - New file version string builder. /// - New file version string builder.
/// </remarks> /// </remarks>
/// <remarks date="2024-May-06" author="Thomas Wiedebusch">
/// - File version as hex number to handle .
/// </remarks>
private static Boolean CheckFileApp(FileApplications fileApp) private static Boolean CheckFileApp(FileApplications fileApp)
{ {
fileApp.AppId = GetFileAppAppId(fileApp.BinData.ToArray()); var binData = fileApp.BinData.ToArray();
fileApp.Crc = GetFileAppCrc(fileApp.BinData.ToArray()); fileApp.AppId = binData[FileAppAppIdIndex];
fileApp.Version = GetFileAppVersion(fileApp.BinData.ToArray()); fileApp.Crc = (UInt16)(binData[FileAppCrcIndex] + (binData[FileAppCrcIndex + 1] << 8));
fileApp.StrVersion = GenesisMeter.BuildFwVersionString(fileApp.BinData[FileAppVersionIndex + 1], if (fileApp.AppId == 0x18) //FLEXNETVERSION
fileApp.BinData[FileAppVersionIndex]); {
var fileAppStartId = Encoding.UTF8.GetString(fileApp.BinData.ToArray(), 0, 4); fileApp.StrVersion = GenesisMeter.BuildFlexnetFwVersion(out fileApp.Version, null,
binData[FileAppVersionIndex + 1],
binData[FileAppVersionIndex]);
}
else
{
fileApp.StrVersion = GenesisMeter.BuildFwVersion(out fileApp.Version,
binData[FileAppVersionIndex + 1],
binData[FileAppVersionIndex]);
}
var fileAppStartId = Encoding.UTF8.GetString(binData, 0, 4);
//check update file start identifier //check update file start identifier
if (fileAppStartId != StrFileAppStartId) if (fileAppStartId != StrFileAppStartId)
{ {
@@ -1712,7 +1743,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
_backupPcbId = _pcbId; _backupPcbId = _pcbId;
RemindDownloadedFileApps(); RemindDownloadedFileApps();
CompareAllMeterAndFileApps(); CompareAllMeterAndFileApps(true);
return returnValue; return returnValue;
} }
@@ -1825,7 +1856,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
private Boolean DownloadUpgradeCtrlFile() private Boolean DownloadUpgradeCtrlFile()
{ {
//initiate upgrade by writing the upgrade control file //initiate upgrade by writing the upgrade control file
if (_upgradeCtrlFile == "" || if (_upgradeCtrlFile == "" || _meterFile == null ||
!_meterFile.UnlockEraseWriteMeterFile(StrUpgradeCtrlFileName)) !_meterFile.UnlockEraseWriteMeterFile(StrUpgradeCtrlFileName))
{ {
return false; return false;
@@ -1948,7 +1979,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
} }
_updatedMeterApps.Clear(); _updatedMeterApps.Clear();
CompareAllMeterAndFileApps(); CompareAllMeterAndFileApps(true);
return true; return true;
} }
@@ -1967,16 +1998,6 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
return $"0x{appId:X2}"; return $"0x{appId:X2}";
} }
/// <summary>
/// Build a version string like 2.02
/// </summary>
/// <param name="version"></param>
/// <returns></returns>
public static String ConvertVersionToString(Int32? version)
{
return version == null ? "0.00" : $"{version / 100}.{version % 100:D2}";
}
/// <summary> /// <summary>
/// Build the hexadecimal CRC string /// Build the hexadecimal CRC string
/// </summary> /// </summary>
@@ -2046,6 +2067,9 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
/// new versions starting with 2022-11-04_NA_B122B contain a CRC16 and CRC32 identifier. /// new versions starting with 2022-11-04_NA_B122B contain a CRC16 and CRC32 identifier.
/// - File line check modified to be immune against multiple blanks behind the field identifier. /// - File line check modified to be immune against multiple blanks behind the field identifier.
/// </remarks> /// </remarks>
/// <remarks date="2024-May-06" author="Thomas Wiedebusch">
/// - Handle FLEXNETVERSION correctly.
/// </remarks>
public Boolean ValidateFileAppsWithPackageFile() public Boolean ValidateFileAppsWithPackageFile()
{ {
if (string.IsNullOrEmpty(_packageDescriptionFile) || FileApps.Count == 0 || if (string.IsNullOrEmpty(_packageDescriptionFile) || FileApps.Count == 0 ||
@@ -2058,7 +2082,11 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
var validAppsCtr = 0; var validAppsCtr = 0;
foreach (var fileApp in FileApps) foreach (var fileApp in FileApps)
{ {
//find a line which contains all required information // convert version from 0x1107 to "11.07"
var strVersion = fileApp.AppId == 0x18 ?
$"{(fileApp.Version & 0xFF00) >> 8:X2}.{fileApp.Version & 0x00FF:X2}"
: fileApp.StrVersion;
// find a line which contains all required information
validAppsCtr += packageFileLines.Count(line => validAppsCtr += packageFileLines.Count(line =>
line.Contains($"{StrPackageFileAppId}") && line.Contains($"{StrPackageFileAppId}") &&
line.Contains($"{ConvertAppIdToString(fileApp.AppId)}") && line.Contains($"{ConvertAppIdToString(fileApp.AppId)}") &&
@@ -2066,7 +2094,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
line.Contains($"{StrPackageFileAppCrc16}")) && line.Contains($"{StrPackageFileAppCrc16}")) &&
line.Contains($"{ConvertCrcToString(fileApp.Crc)}") && line.Contains($"{ConvertCrcToString(fileApp.Crc)}") &&
line.Contains($"{StrPackageFileAppVersion}") && line.Contains($"{StrPackageFileAppVersion}") &&
line.Contains($"{fileApp.StrVersion}")); line.Contains($"{strVersion}"));
} }
//extract the core revision fields //extract the core revision fields
@@ -2095,9 +2123,9 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
/// <remarks date="2022-Dec-05" author="Thomas Wiedebusch"> /// <remarks date="2022-Dec-05" author="Thomas Wiedebusch">
/// - Core revision data type changed from string ti int32?. /// - Core revision data type changed from string ti int32?.
/// </remarks> /// </remarks>
public Boolean CheckCoreRevision(Int32? coreRevision) public Boolean CheckCoreRevision(UInt32 coreRevision)
{ {
if (null == CoreRevisionMaximum || null == CoreRevisionMinimum || null == coreRevision || if (null == CoreRevisionMaximum || null == CoreRevisionMinimum ||
null == _packageDescriptionFile) null == _packageDescriptionFile)
{ {
return false; return false;
@@ -65,9 +65,9 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
/// <remarks date="2022-Dec-05" author="Thomas Wiedebusch"> /// <remarks date="2022-Dec-05" author="Thomas Wiedebusch">
/// - Core revision data type changed from string ti int32?. /// - Core revision data type changed from string ti int32?.
/// </remarks> /// </remarks>
public static Boolean CheckCoreRevision(MeterFwUpdate meterFwUpdate, Int32? coreRevision) public static Boolean CheckCoreRevision(MeterFwUpdate meterFwUpdate, UInt32 coreRevision)
{ {
if (meterFwUpdate == null || coreRevision == null) return false; if (meterFwUpdate == null ) return false;
return meterFwUpdate.CheckCoreRevision(coreRevision); return meterFwUpdate.CheckCoreRevision(coreRevision);
} }
} }
@@ -0,0 +1,101 @@
using System;
namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile
{
/// <summary>
/// Power correction file stored as reminder and log to meter
/// </summary>
public class MeterPowerCorrectionFile
{
/// <summary>
/// Drive and name for power correction file stored on meter
/// </summary>
public const String StrMeterPowerCorrectionFilePathName = "1\\powcorr";
private const Int32 MeterPwrCorrFileLengthIndex = 0;
private const Int32 MeterPwrCorrFileLengthSize = 2;
private const Int32 MeterPwrCorrFileCrcIndex = MeterPwrCorrFileLengthIndex + MeterPwrCorrFileLengthSize;
private const Int32 MeterPwrCorrFileCrcSize= 2;
private const Int32 MeterPwrCorrFileDataIndex = MeterPwrCorrFileCrcIndex + MeterPwrCorrFileCrcSize;
/// <summary>
/// Detected FW version before maintenance
/// </summary>
public UInt32 ActualFwVersion { get; set; }
/// <summary>
/// Date time UTC at time of maintenance
/// </summary>
public DateTime? ActualDateTimeUtc { get; set; }
/// <summary>
/// Total used seconds before maintenance
/// </summary>
public UInt32 ActualTotalUsedSeconds_s { get; set; }
/// <summary>
/// Total used charge of batteries before maintenance
/// </summary>
public UInt64 ActualTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Actual detected radio system state at maintenance
/// </summary>
public Byte? ActualRadioSystemState { get; set; }
/// <summary>
/// Detection of pulse adapter installation
/// </summary>
public Boolean ActualPulseAdapterIsInstalled { get; set; }
/// <summary>
/// Pulse mode during maintenance
/// </summary>
public Byte ActualPulseMode { get; set; }
/// <summary>
/// Pulse distribution during maintenance
/// </summary>
public Boolean ActualPulseEvenDistribution { get; set; }
/// <summary>
/// FW version for the update
/// </summary>
public UInt32 RequiredFwVersion { get; set; }
/// <summary>
/// Calculated pulse report length
/// </summary>
public UInt32 PulseReportLength { get; set; }
/// <summary>
/// Total used seconds after EOL and before maintenance
/// </summary>
public UInt32 AfterProductionTotalUsedSeconds_s { get; set; }
/// <summary>
/// Overestimated total used charge before maintenance
/// </summary>
public UInt64 OverestimatedTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Lowest threshold for total used charge calculated during maintenance
/// </summary>
public UInt64 MinimumTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Corrected total used charge during maintenance
/// </summary>
public UInt64 CorrectedTotalUsedCharge_uAs { get; set; }
/// <summary>
/// Size of power correction file
/// </summary>
public UInt32 MeterPowerCorrectionFileSize { get; set; }
/// <summary>
/// CRC of power correction file
/// </summary>
public UInt32 MeterPowerCorrectionCRC { get; set; }
}
}
@@ -18,111 +18,111 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus
/// <summary> /// <summary>
/// Data base primary key /// Data base primary key
/// </summary> /// </summary>
public Int32 Id; public Int32 Id { get; set; }
/// <summary> /// <summary>
/// Order number /// Order number
/// </summary> /// </summary>
public Int32? OrderNumber; public Int32? OrderNumber { get; set; }
/// <summary> /// <summary>
/// PcbId. /// PcbId.
/// </summary> /// </summary>
public String PcbId; public String PcbId { get; set; }
/// <summary> /// <summary>
/// Skip radio parameter check /// Skip radio parameter check
/// </summary> /// </summary>
public Boolean SkipRadioParametersCheck; public Boolean SkipRadioParametersCheck { get; set; }
/// <summary> /// <summary>
/// Override FW version. Normally the FW will be assigned to the latest released version /// Override FW version. Normally the FW will be assigned to the latest released version
/// and taken from the data base. Here special versions can be used for FW tests. /// and taken from the data base. Here special versions can be used for FW tests.
/// null means take the current released version /// null means take the current released version
/// </summary> /// </summary>
public Int32? OverrideFwCheck; public Int32? OverrideFwCheck { get; set; }
/// <summary> /// <summary>
/// override the Lut version to check the look-up-table installation as this device may be used for development. /// override the Lut version to check the look-up-table installation as this device may be used for development.
/// null means take the current released version /// null means take the current released version
/// </summary> /// </summary>
public Int32? OverrideLutCheck; public Int32? OverrideLutCheck { get; set; }
/// <summary> /// <summary>
/// Internally used to signal that production and shipping is proved and validated. /// Internally used to signal that production and shipping is proved and validated.
/// </summary> /// </summary>
public Boolean ProductionAccepted; public Boolean ProductionAccepted { get; set; }
/// <summary> /// <summary>
/// Date and time of production of electronics. /// Date and time of production of electronics.
/// </summary> /// </summary>
public DateTime KitronProductionDate; public DateTime KitronProductionDate { get; set; }
/// <summary> /// <summary>
/// Last date until production has to be finished, can be extended by special permission /// Last date until production has to be finished, can be extended by special permission
/// </summary> /// </summary>
public DateTime ProductionDueDate; public DateTime ProductionDueDate { get; set; }
/// <summary> /// <summary>
/// Remaining life time for Cordonel in years based on battery drainage. /// Remaining life time for Cordonel in years based on battery drainage.
/// </summary> /// </summary>
public Double RemainingLifeTimeYears; public Double RemainingLifeTimeYears { get; set; }
/// <summary> /// <summary>
/// Exceeded life time of all batteries in seconds. /// Exceeded life time of all batteries in seconds.
/// </summary> /// </summary>
public UInt64 ExceededLifeTime_s; public UInt64 ExceededLifeTime_s { get; set; }
/// <summary> /// <summary>
/// Required life time in years for assembly, is dependent on region and special permission. /// Required life time in years for assembly, is dependent on region and special permission.
/// </summary> /// </summary>
public Double RequiredLifeTimeYearsAssembly; public Double RequiredLifeTimeYearsAssembly { get; set; }
/// <summary> /// <summary>
/// Required life time in years for shipping, is dependent on region and special permission. /// Required life time in years for shipping, is dependent on region and special permission.
/// </summary> /// </summary>
public Double RequiredLifeTimeYearsShipping; public Double RequiredLifeTimeYearsShipping { get; set; }
/// <summary> /// <summary>
/// Battery drainage in percent. /// Battery drainage in percent.
/// </summary> /// </summary>
public Double DrainedBatteryLoadPercent; public Double DrainedBatteryLoadPercent { get; set; }
/// <summary> /// <summary>
/// Maximum drained Battery load in percent. /// Maximum drained Battery load in percent.
/// </summary> /// </summary>
public Double MaxDrainedBatteryLoadPercent; public Double MaxDrainedBatteryLoadPercent { get; set; }
/// <summary> /// <summary>
/// Number of batteries attached to Cordonel. /// Number of batteries attached to Cordonel.
/// </summary> /// </summary>
public Int32 BatteryQuantity; public Int32 BatteryQuantity { get; set; }
/// <summary> /// <summary>
/// Initial capacity of one battery in mAh. /// Initial capacity of one battery in mAh.
/// </summary> /// </summary>
public UInt64 InitialBatteryLoad_mAh; public UInt64 InitialBatteryLoad_mAh { get; set; }
/// <summary> /// <summary>
/// Drained capacity of all batteries in uAs. /// Drained capacity of all batteries in uAs.
/// </summary> /// </summary>
public UInt64 DrainedBatteryLoad_uAs; public UInt64 DrainedBatteryLoad_uAs { get; set; }
/// <summary> /// <summary>
/// Comment for approval and permissions reasons: /// Comment for approval and permissions reasons:
/// e.g. "On customer requirement for test purposes the life time isn't of importance". /// e.g. "On customer requirement for test purposes the life time isn't of importance".
/// </summary> /// </summary>
public String ApprovalComment; public String ApprovalComment { get; set; }
/// <summary> /// <summary>
/// Name of approver for special permissions. /// Name of approver for special permissions.
/// </summary> /// </summary>
public String ApproverName; public String ApproverName { get; set; }
/// <summary> /// <summary>
/// Date of approval. /// Date of approval.
/// </summary> /// </summary>
public DateTime ApprovalDate; public DateTime ApprovalDate { get; set; }
public Double UNTLimit { get; internal set; } = 0; public Double UNTLimit { get; internal set; } = 0;
public Boolean UNTStatus { get; internal set; } = false; public Boolean UNTStatus { get; internal set; } = false;
@@ -10,9 +10,9 @@
/// </summary> /// </summary>
CommandNotAssigned, CommandNotAssigned,
/// <summary> /// <summary>
/// Acknowledge code not set, will be used initially /// Will be used initially as the record is not sent
/// </summary> /// </summary>
NotDecoded, Unsent,
/// <summary> /// <summary>
/// Response missing /// Response missing
/// </summary> /// </summary>
@@ -173,6 +173,9 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Protocols.RequestProtocol
/// <remarks date="2022-Nov-07" author="T.Wiedebusch"> /// <remarks date="2022-Nov-07" author="T.Wiedebusch">
/// - Command not assigned response for recordInProcess == null. /// - Command not assigned response for recordInProcess == null.
/// </remarks> /// </remarks>
/// <remarks date="2024-Apr-22" author="T.Wiedebusch">
/// - Initial request acknowledge state changed from NotDecoded to NoResponse.
/// </remarks>
public RequestAcknowledgeState ProcessRecordList() public RequestAcknowledgeState ProcessRecordList()
{ {
_logger.Trace($"{_ident} Entry to ProcessRecordList, FIFO contains ({_recordsSendFifo.Count}) records"); _logger.Trace($"{_ident} Entry to ProcessRecordList, FIFO contains ({_recordsSendFifo.Count}) records");
@@ -195,10 +198,11 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Protocols.RequestProtocol
if (_recordInProcess == null) if (_recordInProcess == null)
return RequestAcknowledgeState.CommandNotAssigned; return RequestAcknowledgeState.CommandNotAssigned;
//mark record as answer outstanding
_recordInProcess.Acknowledge = RequestAcknowledgeState.NotDecoded;
do do
{ {
//mark record as answer outstanding
_recordInProcess.Acknowledge = RequestAcknowledgeState.NoResponse;
_logger.Trace($"{_ident} Record({loopCounter}) - Processing"); _logger.Trace($"{_ident} Record({loopCounter}) - Processing");
//log retries //log retries
if (_recordInProcess.RetryCtr > 0) if (_recordInProcess.RetryCtr > 0)
@@ -610,6 +614,10 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Protocols.RequestProtocol
/// <remarks date="2024-Apr-11 Version 2" author="T.Wiedebusch"> /// <remarks date="2024-Apr-11 Version 2" author="T.Wiedebusch">
/// - Rewound to version from 06.09.2023 14:44:33 before Commit 8c9d7704. /// - Rewound to version from 06.09.2023 14:44:33 before Commit 8c9d7704.
/// </remarks> /// </remarks>
/// <remarks date="2024-Apr-15" author="T.Wiedebusch">
/// - Removed useless too short comments as every string is going to be delimited by a 0 and usually won't match
/// to a 4 byte chunk.
/// </remarks>
public RequestRecord CommandToMeter(Byte command, RegisterDefinition meterRegister = null, public RequestRecord CommandToMeter(Byte command, RegisterDefinition meterRegister = null,
Byte[] payload = null, Int32? expectedLength = null, Boolean hideDataInLog = false, Byte[] payload = null, Int32? expectedLength = null, Boolean hideDataInLog = false,
UInt16 skipRetryErrorCode = CommunicationConfig.SkipRetryErrorCode) UInt16 skipRetryErrorCode = CommunicationConfig.SkipRetryErrorCode)
@@ -617,82 +625,27 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Protocols.RequestProtocol
if (command == Commands.MultipleReadData && meterRegister != null && meterRegister.DataType == typeof(String)) if (command == Commands.MultipleReadData && meterRegister != null && meterRegister.DataType == typeof(String))
{ {
var completeResponse = new List<Byte>(); var completeResponse = new List<Byte>();
//TODO THW check this including the recursive call CommandToMeter
while (true) while (true)
{ {
var cRecord = CommandToMeter(Commands.ReadData, meterRegister, payload, expectedLength, var cRecord = CommandToMeter(Commands.ReadData, meterRegister, payload, expectedLength,
hideDataInLog, skipRetryErrorCode); hideDataInLog, skipRetryErrorCode);
var rest = ProcessRecordList(); var rest = ProcessRecordList();
if (rest == RequestAcknowledgeState.Ok && cRecord != null && cRecord.ResponsePayload != null) if (rest == RequestAcknowledgeState.Ok && cRecord?.ResponsePayload != null)
{ {
completeResponse.AddRange(cRecord.ResponsePayload); completeResponse.AddRange(cRecord.ResponsePayload);
if (cRecord.ResponsePayload.Contains(0)) if (!cRecord.ResponsePayload.Contains(0)) continue;
{
cRecord.ResponsePayload = completeResponse;
OnMeterRegisterUpdated?.Invoke(this,
new RegisterUpdatedEventArgs(meterRegister, completeResponse.ToArray()));
if (expectedLength.HasValue && completeResponse.Count < expectedLength.Value)
{
_logger.Debug("Too Short. Payload contains zero");
}
return cRecord; cRecord.ResponsePayload = completeResponse;
} OnMeterRegisterUpdated?.Invoke(this,
} new RegisterUpdatedEventArgs(meterRegister, completeResponse.ToArray()));
else
{
if (expectedLength.HasValue && completeResponse.Any() &&
completeResponse.Count < expectedLength.Value)
{
if (rest != RequestAcknowledgeState.Ok)
{
_logger.Debug($"Too Short.Request Acknowledge State is {rest}");
}
else if (cRecord == null)
{
_logger.Debug("Too Short.Record is empty or null");
}
else if (cRecord.ResponsePayload == null)
{
_logger.Debug("Too Short.ResponsePayload is empty or null");
}
else
{
_logger.Debug("Too Short.Unkown reason");
}
}
return cRecord; return cRecord;
} }
return cRecord;
} }
} }
//if (command == Commands.MultipleReadData && meterRegister != null && meterRegister.DataType == typeof(String))
//{
// var completeResponse = new List<Byte>();
// while (!completeResponse.Contains(0) && _recordInProcess.RetryCtr <= CommunicationConfig.MaxRequestRetries)
// {
// var cRecord = CommandToMeter(Commands.ReadData, meterRegister, payload, 4, hideDataInLog,
// skipRetryErrorCode);
// var rest = ProcessRecordList();
// if (rest == RequestAcknowledgeState.Ok && cRecord?.ResponsePayload != null)
// {
// completeResponse.AddRange(cRecord.ResponsePayload);
// if (cRecord.ResponsePayload.Contains(0))
// {
// cRecord.ResponsePayload = completeResponse;
// OnMeterRegisterUpdated?.Invoke(this,
// new RegisterUpdatedEventArgs(meterRegister, completeResponse.ToArray()));
// return cRecord;
// }
// }
// if (cRecord?.ResponsePayload == null)
// {
// return null;
// }
// }
//}
//the minimum payload is one 4 byte chunk //the minimum payload is one 4 byte chunk
var chunkSize = RegisterDefinition.ChunkSize; var chunkSize = RegisterDefinition.ChunkSize;
if (payload == null) if (payload == null)
@@ -25,7 +25,7 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Protocols.RequestProtocol
/// <summary> /// <summary>
/// Command acknowledged /// Command acknowledged
/// </summary> /// </summary>
public RequestAcknowledgeState Acknowledge = RequestAcknowledgeState.NoResponse; public RequestAcknowledgeState Acknowledge = RequestAcknowledgeState.Unsent;
/// <summary> /// <summary>
/// Retry counter /// Retry counter
@@ -9,8 +9,19 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Registers.DataTypes
public class TimeT public class TimeT
{ {
/// <summary> /// <summary>
/// Seconds since 01. Jan 2000 /// 1. Get seconds since 01. Jan 2000 00:00:00 UTC previously set by any call by
/// <see cref="UtcNowToSecondsSince2000"/> or <see cref="UtcAnyToSecondsSince2000"/>
/// or directly by this routine delivering the seconds e.g. read from meter,
/// 2. Set UTC seconds to analyze the corresponding time in UTC and use the ToString to
/// read the converted result.
/// </summary> /// </summary>
/// <remarks date="2023-Jul-19" author="Thomas Wiedebusch">
/// - Used <see cref="TimeT"/> to calculate time in UTC based on 01. Jan 2000.
/// </remarks>
/// <remarks date="2024-May-02" author="Thomas Wiedebusch">
/// - Setting of seconds and conversion to corresponding UTC sine 2000 or return seconds
/// from set DataTimeUtc.
/// </remarks>
public Int32 SecondsSince2000 public Int32 SecondsSince2000
{ {
set set
@@ -18,25 +29,74 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.Registers.DataTypes
var secondsToTimeSpan = TimeSpan.FromSeconds(value); var secondsToTimeSpan = TimeSpan.FromSeconds(value);
DateTimeUtc = _fixedDateTime2000.Add(secondsToTimeSpan); DateTimeUtc = _fixedDateTime2000.Add(secondsToTimeSpan);
} }
// DateTimeUtc has to be set in advance with seconds or by the call
// of UtcNowToSecondsSince2000 or UtcAnyToSecondsSince2000
get => UtcToSecondsSince2000();
}
/// <summary>
/// Get actual seconds (UTC now) since 01. Jan 2000 00:00:00 UTC.
/// </summary>
/// <remarks date="2024-May-02" author="Thomas Wiedebusch">
/// - Initial.
/// </remarks>
public Int32 UtcNowToSecondsSince2000
{
get get
{ {
DateTimeUtc = DateTime.UtcNow; DateTimeUtc = DateTime.UtcNow;
var timeSince2000Utc = DateTimeUtc - _fixedDateTime2000; return UtcToSecondsSince2000();
var secondsSince2000 = Convert.ToInt32(timeSince2000Utc.TotalSeconds);
return secondsSince2000;
} }
} }
/// <summary> /// <summary>
/// The date and time of 01.Jan 2000 00:00:00 /// Common routine to convert given UTC timestamp to seconds since 01. Jan 2000 00:00:00 UTC.
/// </summary> /// </summary>
private readonly DateTime _fixedDateTime2000 = new DateTime(2000, 1, 1, 0, 0, 0); /// <remarks date="2024-May-02" author="Thomas Wiedebusch">
/// - Initial.
/// </remarks>
private Int32 UtcToSecondsSince2000()
{
var timeSince2000Utc = DateTimeUtc - _fixedDateTime2000;
var secondsSince2000 = Convert.ToInt32(timeSince2000Utc.TotalSeconds);
return secondsSince2000;
}
/// <summary>
/// Builds the seconds for a given timestamp based on 01.Jan.2000 00:00:00 UTC
/// </summary>
/// <param name="dateTimeUtc">time stamp dateTime for conversion</param>
/// <remarks date="2023-Jul-19" author="Thomas Wiedebusch">
/// - Optional input of dateTime to convert this to the time in UTC based on 01. Jan 2000.
/// </remarks>
public Int32 UtcAnyToSecondsSince2000(DateTime dateTimeUtc)
{
try
{
// limit dateTime to 01. Jan 2000 00:00:00 UTC
DateTimeUtc = dateTimeUtc < _fixedDateTime2000 ? _fixedDateTime2000 : dateTimeUtc;
return UtcToSecondsSince2000();
}
catch (Exception)
{
return 0;
}
}
/// <summary>
/// The date and time of 01.Jan 2000 00:00:00 UTC
/// </summary>
private static readonly DateTime _fixedDateTime2000 = new DateTime(2000, 1, 1, 0, 0, 0);
/// <summary> /// <summary>
/// Converted date and time to UTC using the FixedDateTime2000 /// Converted date and time to UTC using the FixedDateTime2000
/// and the SecondsSince2000 /// and the SecondsSince2000
/// </summary> /// </summary>
public DateTime DateTimeUtc; public DateTime DateTimeUtc
{
private set;
get;
} = _fixedDateTime2000;
/// <summary> /// <summary>
/// Get string of UTC date and time universal language with 24 hours format /// Get string of UTC date and time universal language with 24 hours format
@@ -36,6 +36,6 @@ namespace Xylem.Common.Logic.ProductionOrderCore.OrderData
/// <summary> /// <summary>
/// Cordonel length /// Cordonel length
/// </summary> /// </summary>
public Int64 Length { get; set; } public Int64? Length { get; set; }
} }
} }
@@ -52,6 +52,11 @@ namespace Xylem.Common.Logic.ProductionOrderCore.OrderData
/// </summary> /// </summary>
public String InstalledReleaseNameVersion; public String InstalledReleaseNameVersion;
/// <summary>
/// Installed firmware version
/// </summary>
public Int32? InstalledFwVersion;
/// <summary> /// <summary>
/// Device core revision /// Device core revision
/// </summary> /// </summary>
@@ -1,15 +0,0 @@
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Omni.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Omni.Data")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("c0d3bdde-324a-487d-b3b1-1af6904f8ba1")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+3 -5
View File
@@ -55,7 +55,7 @@
{ {
try try
{ {
return this.connection.State == ConnectionState.Connected; return this.connection?.State == ConnectionState.Connected;
} }
catch (Exception e) catch (Exception e)
{ {
@@ -116,10 +116,8 @@
}); });
} }
public void Send(DataDictionary dictionary) public void Send(DataDictionary dictionary)
{ => this.proxy.Invoke(nameof(this.Send), dictionary.Generic());
this.proxy.Invoke(nameof(this.Send), dictionary.Generic());
}
private void Connection_Closed() private void Connection_Closed()
{ {
+4 -4
View File
@@ -4,11 +4,11 @@
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup> </startup>
<appSettings> <appSettings>
<add key="PSNR" value="1000"/> <add key="PSNR" value="0000"/>
<add key="HubURL" value="http://sla12iis01.emea.sensus.net/LaaProductionWeb" /> <add key="HubURL" value="http://localhost:52822/LaaProductionWeb" />
<!--<add key="OmniDB" value="Server=SLASQL01.emea.sensus.net; Database=AuftragKopie; User ID=sa; Password=sqlserver;" />--> <!--<add key="HubURL" value="http://sla12iis01.emea.sensus.net/LaaProductionWeb" />-->
<add key="OmniDB" value="Server=SLASQL01.emea.sensus.net; Database=Auftrag; User ID=sa; Password=sqlserver;"/> <add key="OmniDB" value="Server=SLASQL01.emea.sensus.net; Database=Auftrag; User ID=sa; Password=sqlserver;"/>
<!--<add key="COMPorts" value="COM1, COM3, COM5, COM7, COM5, COM9, COM11, COM13, COM15, COM17"/>-->
<add key="COMPorts" value="COM36"/> <add key="COMPorts" value="COM36"/>
<add key="FlushMinutes" value=""/>
</appSettings> </appSettings>
</configuration> </configuration>
+2 -4
View File
@@ -10,9 +10,7 @@
internal static event Action Exiting; internal static event Action Exiting;
protected override void OnExit(ExitEventArgs e) protected override void OnExit(ExitEventArgs e)
{ => Exiting?.Invoke();
Exiting?.Invoke();
}
} }
} }
@@ -61,11 +61,9 @@
</Compile> </Compile>
<Compile Include="Models\Appsettings.cs" /> <Compile Include="Models\Appsettings.cs" />
<Compile Include="Models\CompilerServices.cs" /> <Compile Include="Models\CompilerServices.cs" />
<Compile Include="ViewModels\DisplayHeadersRowVM.cs" />
<Compile Include="ViewModels\DisplayReaderVM.cs" />
<Compile Include="ViewModels\PluginsVM.cs" /> <Compile Include="ViewModels\PluginsVM.cs" />
<Compile Include="ViewModels\DefaultsHeaderRow.cs" />
<Compile Include="ViewModels\DefaultsRowVM.cs" />
<Compile Include="ViewModels\HeadersRowVM.cs" />
<Compile Include="ViewModels\ItemsGridActionsVM.cs" />
<Compile Include="ViewModels\ItemsGridHeaderVM.cs" /> <Compile Include="ViewModels\ItemsGridHeaderVM.cs" />
<Compile Include="ViewModels\ItemsGridRowVM.cs" /> <Compile Include="ViewModels\ItemsGridRowVM.cs" />
<Compile Include="ViewModels\ItemsGridVM.cs" /> <Compile Include="ViewModels\ItemsGridVM.cs" />
@@ -74,6 +72,7 @@
<Compile Include="ViewModels\MeterVM.cs" /> <Compile Include="ViewModels\MeterVM.cs" />
<Compile Include="ViewModels\ItemsGridCellVM.cs" /> <Compile Include="ViewModels\ItemsGridCellVM.cs" />
<Compile Include="ViewModels\ReferenceMeterVM.cs" /> <Compile Include="ViewModels\ReferenceMeterVM.cs" />
<Compile Include="ViewModels\RotationsHeaderRow.cs" />
<Compile Include="ViewModels\VM.cs" /> <Compile Include="ViewModels\VM.cs" />
<Page Include="ItemsGrid.xaml"> <Page Include="ItemsGrid.xaml">
<SubType>Designer</SubType> <SubType>Designer</SubType>
@@ -125,9 +124,9 @@
</Content> </Content>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ExchangeHub\ExchangeHub.csproj"> <ProjectReference Include="..\Exchange\SignalR\SignalR.csproj">
<Project>{6033FF0C-CF32-4BC5-8EFE-4774CCDC663D}</Project> <Project>{ABF3EC64-1257-4CA2-AD62-8A27A5F1EDCC}</Project>
<Name>ExchangeHub</Name> <Name>SignalR</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="..\OmniPlus\OmniPlus.csproj"> <ProjectReference Include="..\OmniPlus\OmniPlus.csproj">
<Project>{F8D84B9A-0FCF-4083-B067-8C39B7314152}</Project> <Project>{F8D84B9A-0FCF-4083-B067-8C39B7314152}</Project>
@@ -33,48 +33,5 @@
VerticalAlignment="Stretch" VerticalAlignment="Stretch"
VerticalContentAlignment="Center" /> VerticalContentAlignment="Center" />
</DataTemplate> </DataTemplate>
<DataTemplate DataType="{x:Type VM:ItemsGridActionsVM}">
<Border BorderBrush="WhiteSmoke"
BorderThickness="0, 1, 1, 0" >
<StackPanel HorizontalAlignment="Center"
Orientation="Horizontal"
Margin="0"
VerticalAlignment="Stretch">
<Button Background="Transparent"
BorderBrush="Transparent"
Content="A"
Cursor="Hand"
FontFamily="Consolas"
FontSize="14"
HorizontalAlignment="Center"
HorizontalContentAlignment="Center"
Padding="5, 0"
VerticalAlignment="Center"
VerticalContentAlignment="Center"/>
<Button Background="Transparent"
BorderBrush="Transparent"
Content="B"
Cursor="Hand"
FontFamily="Consolas"
FontSize="14"
HorizontalAlignment="Center"
HorizontalContentAlignment="Center"
Padding="5, 0"
VerticalAlignment="Center"
VerticalContentAlignment="Center" />
<Button Background="Transparent"
BorderBrush="Transparent"
Content="C"
Cursor="Hand"
FontFamily="Consolas"
FontSize="14"
HorizontalAlignment="Center"
HorizontalContentAlignment="Center"
Padding="5, 0"
VerticalAlignment="Center"
VerticalContentAlignment="Center" />
</StackPanel>
</Border>
</DataTemplate>
</Grid.Resources> </Grid.Resources>
</Grid> </Grid>
+18 -6
View File
@@ -14,12 +14,14 @@
</Window.DataContext> </Window.DataContext>
<Grid> <Grid>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
<RowDefinition Height="*" /> <RowDefinition Height="*" />
<RowDefinition Height="Auto" /> <RowDefinition Height="Auto" />
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Border BorderBrush="LightGray" BorderThickness="0, 1" Grid.Row="0">
<Border BorderBrush="LightGray" BorderThickness="0, 1" Grid.Row="1">
<Grid> <Grid>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" />
@@ -96,11 +98,20 @@
<ComboBoxItem Content="IRDA" Padding="10, 5" IsSelected="True" /> <ComboBoxItem Content="IRDA" Padding="10, 5" IsSelected="True" />
<ComboBoxItem Content="UniPro" Padding="10, 5" /> <ComboBoxItem Content="UniPro" Padding="10, 5" />
</ComboBox> </ComboBox>
<Button Command="{Binding StartDisplayReading}"
Content="Anzeige lesen"
Cursor="Hand"
FontFamily="Consolas"
Grid.Column="7"
IsEnabled="{Binding IsStartInspectionEnabled}"
Margin="5"
Padding="10, 5"/>
<Button Command="{Binding StartInspection}" <Button Command="{Binding StartInspection}"
Content="Prüfung starten" Content="Prüfung starten"
Cursor="Hand" Cursor="Hand"
FontFamily="Consolas" FontFamily="Consolas"
Grid.Column="7" Grid.Column="8"
IsEnabled="{Binding IsStartInspectionEnabled}" IsEnabled="{Binding IsStartInspectionEnabled}"
Margin="5" Margin="5"
Padding="10, 5"/> Padding="10, 5"/>
@@ -108,14 +119,14 @@
Content="Abbrechen" Content="Abbrechen"
Cursor="Hand" Cursor="Hand"
FontFamily="Consolas" FontFamily="Consolas"
Grid.Column="8" Grid.Column="9"
IsEnabled="{Binding IsCancelInspectionEnabled}" IsEnabled="{Binding IsCancelInspectionEnabled}"
Margin="5" Margin="5"
Padding="10, 5" /> Padding="10, 5" />
</Grid> </Grid>
</Border> </Border>
<Border Grid.Row="1" Margin="10"> <Border Grid.Row="2">
<TextBlock FontFamily="Consolas" <TextBlock FontFamily="Consolas"
Padding="0" Padding="0"
Text="{Binding Errors}" Text="{Binding Errors}"
@@ -124,12 +135,13 @@
<!-- TODO: Order head --> <!-- TODO: Order head -->
<ScrollViewer Grid.Row="2" <ScrollViewer Grid.Row="3"
CanContentScroll="True" CanContentScroll="True"
IsDeferredScrollingEnabled="True" IsDeferredScrollingEnabled="True"
VerticalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"> HorizontalScrollBarVisibility="Auto">
<Local:ItemsGrid ItemsSource="{Binding MetersPool}" Margin="10, 0, 10, 10" /> <Local:ItemsGrid ItemsSource="{Binding MetersPool}" />
</ScrollViewer> </ScrollViewer>
</Grid> </Grid>
</Window> </Window>
@@ -45,13 +45,18 @@
get => GetSetting(nameof(PSNR)); get => GetSetting(nameof(PSNR));
} }
public static int FlushMinutes
{
get => int.TryParse(GetSetting(nameof(FlushMinutes)), out var flush) ? flush : 0;
}
private static string GetSetting(string setting) private static string GetSetting(string setting)
{ {
var appsettingsSection = ExeConfiguration.AppSettings.SectionInformation.Name; var appsettingsSection = ExeConfiguration.AppSettings.SectionInformation.Name;
ConfigurationManager.RefreshSection(appsettingsSection); ConfigurationManager.RefreshSection(appsettingsSection);
return Settings[setting].Value; return Settings[setting].Value ?? string.Empty;
} }
} }
} }
@@ -1,30 +0,0 @@
namespace InspectionUI.ViewModels
{
using OmniPlus;
public class DefaultsHeaderRow : ItemsGridRowVM
{
public DefaultsHeaderRow()
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
var pruefpunkte = OmniContext
.Current
.Auftrag
.Pruefpunkte
.Count;
for (int i = 0; i < pruefpunkte; i++)
{
this.Add(new ItemsGridHeaderVM { Value = $"r/s" });
this.Add(new ItemsGridHeaderVM { Value = $"m³/h" });
this.Add(new ItemsGridHeaderVM { Value = $"acc. %" });
}
this.Add(new ItemsGridHeaderVM());
}
}
}
@@ -1,29 +0,0 @@
namespace InspectionUI.ViewModels
{
using OmniPlus;
public class DefaultsRowVM : ItemsGridRowVM
{
public DefaultsRowVM()
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM { Value = "PP:" });
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM { Value = "0.0" });
var pruefpunkte = OmniContext
.Current
.Auftrag
.Pruefpunkte;
foreach (var pp in pruefpunkte)
{
this.Add(new ItemsGridHeaderVM { Value = $"{pp.Rotations}/{pp.Duration:0.0}" });
this.Add(new ItemsGridHeaderVM { Value = $"{pp.FlowM3H:0.000}" });
this.Add(new ItemsGridHeaderVM { Value = $"{pp.MinAccuracy}-{pp.MaxAccuracy}" });
}
this.Add(new ItemsGridHeaderVM { Value = "0.0" });
}
}
}
@@ -0,0 +1,14 @@
namespace InspectionUI.ViewModels
{
public class DisplayHeadersRowVM : ItemsGridRowVM
{
public DisplayHeadersRowVM() : base()
{
this.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
this.Add(new ItemsGridHeaderVM { Value = "MeterNr", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "Display Units", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "Start value", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "Current value", Width = ItemsGridHeaderVM.Star });
}
}
}
@@ -0,0 +1,110 @@
namespace InspectionUI.ViewModels
{
using InspectionUI.Models;
using OmniPlus;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
internal class DisplayReaderVM : VM
{
private readonly OmniContext omniContext;
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
private List<Task> readers;
public DisplayReaderVM()
{
this.Meters = new ObservableCollection<MeterDisplayVM>();
this.omniContext = OmniContext.Create(Appsettings.OmniDB, Appsettings.CurrentDirectory);
}
public ObservableCollection<MeterDisplayVM> Meters { get; }
private void StartReading()
{
try
{
this.cancellationTokenSource?.Cancel(true);
this.readers?.Clear();
this.Meters?.Clear();
}
catch (Exception e)
{
}
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
this.readers = new List<Task>();
this.omniContext.LoadMeters(Appsettings.COMPorts, Appsettings.PSNR);
foreach (var meter in this.omniContext.Meters)
{
var meterVM = new MeterDisplayVM(meter);
this.Meters.Add(meterVM);
this.readers.Add(meterVM.StartReadingAsync(this.cancellationToken));
}
}
}
internal class MeterDisplayVM : VM
{
private readonly OmniMeter meter;
public MeterDisplayVM(OmniMeter meter)
=> this.meter = meter;
private string meterId;
public string MeterNr
{
get => this.meterId;
set => this.Set(() => this.meterId = value);
}
private string displayValue;
public string DisplayValue
{
get => this.displayValue;
set => this.Set(() => this.displayValue = value);
}
public Task StartReadingAsync(CancellationToken cancellationToken)
{
cancellationToken.Register(this.meter.Dispose);
void StartReading(object state)
{
if (state is MeterDisplayVM vm)
{
var _meter = vm.meter;
_meter.Connect();
_meter.IdentifySelf();
if (!_meter.IsActive)
{
return;
}
vm.MeterNr = _meter.MeterNr;
while (_meter.IsActive)
{
vm.DisplayValue = _meter.ReadDisplay();
Thread.Sleep(1000);
}
}
}
return Task.Factory.StartNew(StartReading, this, cancellationToken);
}
}
}
@@ -1,35 +0,0 @@
namespace InspectionUI.ViewModels
{
using InspectionUI.Models;
using OmniPlus;
public class HeadersRowVM : ItemsGridRowVM
{
public HeadersRowVM() : base()
{
this.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
this.Add(new ItemsGridHeaderVM { Value = "MeterNr", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "SerialNr", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "Crr.F. %", Width = ItemsGridHeaderVM.Auto });
var pruefpunkte = OmniContext
.Current
.Auftrag
.Pruefpunkte;
foreach (var pp in pruefpunkte)
{
this.Add(new ItemsGridHeaderVM
{
Value = $"Q{pp.PPNR}",
Width = ItemsGridHeaderVM.Star,
ColSpan = 3
});
}
this.Add(new ItemsGridHeaderVM { Value = "Crr.F. %", Width = ItemsGridHeaderVM.Star });
}
}
}
@@ -1,12 +0,0 @@
namespace InspectionUI.ViewModels
{
internal class ItemsGridActionsVM : ItemsGridCellVM
{
private MeterVM meterVM;
public ItemsGridActionsVM(MeterVM meterVM) : base()
{
this.meterVM = meterVM;
}
}
}
@@ -65,20 +65,15 @@
protected void Set<T>(T value, string format, int index) protected void Set<T>(T value, string format, int index)
{ {
this.DispatcherInvoke(() => if (string.IsNullOrWhiteSpace(format))
{ {
if (string.IsNullOrWhiteSpace(format)) format = "{0}";
{ }
format = "{0}";
}
this[index].Value = string.Format(format, value); this[index].Value = string.Format(format, value);
});
} }
protected void Set(Action<ItemsGridCellVM> setter, int index) protected void Set(Action<ItemsGridCellVM> setter, int index)
{ => setter(this[index]);
this.DispatcherInvoke(() => setter(this[index]));
}
} }
} }
@@ -19,7 +19,7 @@
IEnumerator IEnumerable.GetEnumerator() IEnumerator IEnumerable.GetEnumerator()
{ {
return this.GetEnumerator(); return this.rows.GetEnumerator();
} }
protected void Add(ItemsGridRowVM item) protected void Add(ItemsGridRowVM item)
@@ -46,5 +46,10 @@
{ {
this.rows.Insert(index, item); this.rows.Insert(index, item);
} }
internal void Remove(ItemsGridRowVM row)
{
this.rows.Remove(row);
}
} }
} }
@@ -1,6 +1,5 @@
namespace InspectionUI.ViewModels namespace InspectionUI.ViewModels
{ {
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Windows.Input; using System.Windows.Input;
@@ -11,6 +10,7 @@
{ {
this.IsReloadEnabled = true; this.IsReloadEnabled = true;
this.Reload = new Command(this.ReloadCommand); this.Reload = new Command(this.ReloadCommand);
this.StartDisplayReading = new Command(this.StartDisplayReadingCommand);
this.StartInspection = new Command(this.StartInspectionCommand); this.StartInspection = new Command(this.StartInspectionCommand);
this.CancelInspection = new Command(this.CancelInspectionCommand); this.CancelInspection = new Command(this.CancelInspectionCommand);
this.MetersPool = new MetersPoolVM(this.ConnectionType); this.MetersPool = new MetersPoolVM(this.ConnectionType);
@@ -64,6 +64,8 @@
public ICommand Reload { get; } public ICommand Reload { get; }
public ICommand StartDisplayReading { get; }
private bool startInspectionEnabled; private bool startInspectionEnabled;
public bool IsStartInspectionEnabled public bool IsStartInspectionEnabled
{ {
@@ -147,26 +149,30 @@
} }
} }
private void StartDisplayReadingCommand()
{
this.StartNewTask(() =>
{
this.EnableButtons(false);
this.MetersPool.StartDisplayReading();
})
.ContinueWith(_ => this.EnableButtons(true));
}
private void StartInspectionCommand() private void StartInspectionCommand()
{ {
this.StartNewTask(() => this.StartNewTask(() =>
{ {
this.EnableButtons(false); this.EnableButtons(false);
this.MetersPool.RunInspection(this.KeepCorrection); this.MetersPool.RunInspection(this.KeepCorrection);
this.IsCancelInspectionEnabled = false; })
this.IsReloadEnabled = true; .ContinueWith(_ => this.EnableButtons(true));
});
} }
private void CancelInspectionCommand() private void CancelInspectionCommand()
{ {
this.StartNewTask(() => this.StartNewTask(this.MetersPool.CancelInspection)
{ .ContinueWith(_ => this.EnableButtons(true));
this.EnableButtons(false);
this.MetersPool.CancelInspection();
this.IsCancelInspectionEnabled = false;
this.IsReloadEnabled = true;
});
} }
private void EnableButtons(bool enabled) private void EnableButtons(bool enabled)
@@ -3,6 +3,7 @@
using OmniPlus; using OmniPlus;
using System; using System;
using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Timers; using System.Timers;
@@ -10,19 +11,21 @@
public class MeterVM : ItemsGridRowVM public class MeterVM : ItemsGridRowVM
{ {
const int OFFSET = 2;
private readonly OmniMeter meter; private readonly OmniMeter meter;
private int uinr; private int column;
private bool active; private bool active;
public MeterVM(OmniMeter meter) : base() public MeterVM(OmniMeter meter) : base()
{ {
this.meter = meter; this.meter = meter;
this.column = OFFSET;
this.Add(new ItemsGridHeaderVM { Value = $"{this.meter.SlotNr, 2}." }); this.Add(new ItemsGridHeaderVM { Value = $"{this.meter.SlotNr, 2}." });
this.Add(new ItemsGridCellVM()); this.Add(new ItemsGridCellVM());
this.Add(new ItemsGridCellVM()); this.Add(new ItemsGridCellVM());
this.Add(new ItemsGridCellVM());
var pruefpunkte = OmniContext var pruefpunkte = OmniContext
.Current .Current
@@ -33,16 +36,16 @@
for (int i = 0; i < pruefpunkte; i++) for (int i = 0; i < pruefpunkte; i++)
{ {
this.Add(new ItemsGridCellVM()); this.Add(new ItemsGridCellVM());
this.Add(new ItemsGridCellVM());
this.Add(new ItemsGridCellVM());
} }
this.Add(new ItemsGridCellVM()); this.Add(new ItemsGridCellVM());
this.MeterNr = this.meter.MeterNr; this.MeterNr = this.meter.MeterNr;
this.SerialNr = this.meter.SerialNr;
} }
protected int? SlotNr
=> this.meter?.SlotNr;
private string meterId; private string meterId;
protected string MeterNr protected string MeterNr
{ {
@@ -50,13 +53,17 @@
set => this.Set(() => this.meterId = value, value, "{0}", 1); set => this.Set(() => this.meterId = value, value, "{0}", 1);
} }
private int? serialNr; protected string DisplayValue => this.meter.ReadDisplay();
protected int? SerialNr
protected string MeterUnits => this.meter.MeterUnits;
protected string message;
public string Message
{ {
get => this.serialNr; get => this.message;
set => this.Set(() => this.serialNr = value, value, "{0}", 2); set => this.Set(() => this.message = value);
} }
internal Task ConnectAsync(int connectionType, CancellationToken cancellationToken) internal Task ConnectAsync(int connectionType, CancellationToken cancellationToken)
{ {
void Connect(object state) void Connect(object state)
@@ -124,12 +131,10 @@
{ {
if (state is MeterVM vm && vm.active) if (state is MeterVM vm && vm.active)
{ {
vm.uinr = 0;
var meter = vm.meter; var meter = vm.meter;
meter.InitializeForInspection(keepCorrection); meter.InitializeForInspection(keepCorrection);
vm.Set(meter.TestRun.CrrfBefore, "{0:0.0}", 3); vm.Set(meter.TestRun.CrrfBefore, "{0:0.0}", OFFSET);
} }
} }
@@ -142,13 +147,13 @@
{ {
if (state is MeterVM vm && vm.active) if (state is MeterVM vm && vm.active)
{ {
vm.uinr++; this.column++;
var _pp = pp; var _pp = pp;
var meter = vm.meter; var meter = vm.meter;
meter.StartCalibration((ushort)_pp.Rotations, (ushort)_pp.Duration); meter.StartCalibration((ushort)_pp.Rotations, (ushort)_pp.Duration);
vm.ShowRestTime(_pp.Duration, vm.uinr * 3 + 1); vm.ShowRestTime(_pp.Duration, this.column);
} }
} }
@@ -165,11 +170,8 @@
var meter = vm.meter; var meter = vm.meter;
var response = meter.StopCalibration(_pp, refm3s); var response = meter.StopCalibration(_pp, refm3s);
var index = vm.uinr * 3 + 1;
vm.Set(response.Item3, "{0:0.00}", this.column);
vm.Set(response.Item2, "{0}", index);
vm.Set(response.Item1, "{0:0.0000000}", index + 1);
vm.Set(response.Item3, "{0:0.00}", index + 2);
} }
} }
@@ -184,7 +186,16 @@
{ {
var meter = vm.meter; var meter = vm.meter;
void WaitUntil(object _)
{
vm.Set(x => x.Foreground = Brushes.LightGray, vm.LastIndex);
vm.Set("Wird programmiert...", null, vm.LastIndex);
}
var timer = new System.Threading.Timer(WaitUntil, null, 0, 1000);
meter.FinishInspection(); meter.FinishInspection();
timer.Dispose();
var crrf = meter.TestRun.CrrfAfter; var crrf = meter.TestRun.CrrfAfter;
var foreground = meter.TestRun.Succeeded == true var foreground = meter.TestRun.Succeeded == true
@@ -193,22 +204,20 @@
vm.Set(x => x.Foreground = foreground, vm.LastIndex); vm.Set(x => x.Foreground = foreground, vm.LastIndex);
vm.Set(crrf, "{0:0.0}", vm.LastIndex); vm.Set(crrf, "{0:0.0}", vm.LastIndex);
vm.uinr = 1;
var ppnr = OFFSET;
foreach (var testedPP in meter.TestRun.TestedPoints) foreach (var testedPP in meter.TestRun.TestedPoints)
{ {
var index = vm.uinr * 3 + 1 + 2; ppnr++;
vm.Set(testedPP.Acc, "{0:0.00}", ppnr);
vm.Set(testedPP.Acc, "{0:0.00}", index);
vm.Set(x => vm.Set(x =>
{ {
foreground = testedPP.Succeeded == true foreground = testedPP.Succeeded == true
? Brushes.Green ? Brushes.Green
: Brushes.Red; : Brushes.Red;
x.Foreground = foreground; x.Foreground = foreground;
}, index); }, ppnr);
vm.uinr++;
} }
} }
} }
@@ -216,6 +225,57 @@
return this.StartTask(FinishInspection, cancellationToken); return this.StartTask(FinishInspection, cancellationToken);
} }
private string waageFile;
internal void InitDisplayReading()
{
this.Clear();
var timestamp = DateTime.Now;
var displayValue = this.DisplayValue;
var currentValueCell = new ItemsGridCellVM
{
Value = $"{displayValue}"
};
var dir = Directory.CreateDirectory("./waage").FullName;
this.waageFile = $"{dir}/{this.MeterNr}.txt";
this.Add(new ItemsGridHeaderVM { Value = $"{this.SlotNr,2}." });
this.Add(new ItemsGridCellVM { Value = this.MeterNr });
this.Add(new ItemsGridCellVM { Value = this.MeterUnits });
this.Add(new ItemsGridCellVM { Value = displayValue });
this.Add(currentValueCell);
File.AppendAllText(this.waageFile, $"{timestamp:yyyy-MM-dd HH:mm:ss};{displayValue}{Environment.NewLine}");
this.NotifyPropertyChanged();
}
internal Task StartDisplayReadingAsync(CancellationToken cancellationToken)
{
void StartDisplayReading(object state)
{
if (state is MeterVM vm)
{
var awaiter = new ManualResetEventSlim();
while (!cancellationToken.IsCancellationRequested)
{
var displayValue = vm.DisplayValue;
var timestamp = DateTime.Now;
vm[4].Value = displayValue;
File.AppendAllText(this.waageFile, $"{timestamp:yyyy-MM-dd HH:mm:ss};{displayValue}{Environment.NewLine}");
awaiter.Reset();
awaiter.Wait(1000);
}
}
}
return Task.Factory.StartNew(StartDisplayReading, this, cancellationToken);
}
private void ShowRestTime(int duration, int index) private void ShowRestTime(int duration, int index)
{ {
var interval = 1000; var interval = 1000;
@@ -26,20 +26,16 @@
public Boolean HasPruefpunkte { get; private set; } public Boolean HasPruefpunkte { get; private set; }
internal IList<String> LoadTypes() internal IList<String> LoadTypes()
{ => this.omniContext.LoadTypes();
return this.omniContext.LoadTypes();
}
internal IList<String> LoadSizes() internal IList<String> LoadSizes()
{ => this.omniContext.LoadSizes();
return this.omniContext.LoadSizes();
}
public void CancelInspection() public void CancelInspection()
{ {
this.cancellationTokenSource?.Cancel(); this.cancellationTokenSource?.Cancel();
this.referenceMeter?.Stop(); this.referenceMeter?.Dispose();
this.Dispose(); this.Dispose();
} }
@@ -52,15 +48,6 @@
public void LoadMetersAsync() public void LoadMetersAsync()
{ {
if (!this.HasPruefpunkte)
{
return;
}
this.referenceMeter = new ReferenceMeterVM(OmniContext.Current);
this.Add(this.referenceMeter);
this.omniContext.LoadMeters(Appsettings.COMPorts, Appsettings.PSNR); this.omniContext.LoadMeters(Appsettings.COMPorts, Appsettings.PSNR);
foreach (var meter in this.omniContext.Meters) foreach (var meter in this.omniContext.Meters)
@@ -122,6 +109,15 @@
var pruefpunkte = this.omniContext var pruefpunkte = this.omniContext
.Auftrag .Auftrag
.Pruefpunkte; .Pruefpunkte;
var isQmax = true;
var awaiter = new ManualResetEventSlim();
cancellationToken.Register(() =>
{
this.referenceMeter.Dispose();
awaiter.Set();
});
foreach (var pp in pruefpunkte) foreach (var pp in pruefpunkte)
{ {
@@ -132,6 +128,12 @@
this.referenceMeter.Start(pp); this.referenceMeter.Start(pp);
if (isQmax)
{
isQmax = false;
awaiter.Wait(Appsettings.FlushMinutes * 60 * 1000);
}
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
{ {
break; break;
@@ -149,7 +151,7 @@
break; break;
} }
var refm3s = this.referenceMeter.GetFlow(); var m3s = this.referenceMeter.GetM3S(pp);
if (cancellationToken.IsCancellationRequested) if (cancellationToken.IsCancellationRequested)
{ {
@@ -158,7 +160,7 @@
foreach (var vm in metersVM) foreach (var vm in metersVM)
{ {
tasks.Add(vm.StopCalibrationAsync(pp, refm3s, cancellationToken)); tasks.Add(vm.StopCalibrationAsync(pp, m3s, cancellationToken));
} }
this.WaitAll(tasks); this.WaitAll(tasks);
@@ -179,6 +181,54 @@
this.WaitAll(tasks); this.WaitAll(tasks);
} }
internal void StartDisplayReading()
{
this.DispatcherInvoke(() =>
{
var headers = new List<ItemsGridRowVM>();
foreach (var row in this)
{
if (!(row is MeterVM _))
{
headers.Add(row);
}
}
foreach (var header in headers)
{
this.Remove(header);
}
this.Insert(0, new DisplayHeadersRowVM());
foreach (var row in this)
{
if (row is MeterVM meterVM)
{
meterVM.InitDisplayReading();
}
}
this.NotifyPropertyChanged();
});
this.cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = this.cancellationTokenSource.Token;
var tasks = new List<Task>();
var metersVM = this
.Select(x => x is MeterVM m ? m : null)
.Where(x => x != null)
.ToArray();
foreach (var meterVM in metersVM)
{
tasks.Add(meterVM.StartDisplayReadingAsync(cancellationToken));
}
this.WaitAll(tasks);
}
internal void LoadAuftrag(string size, string type) internal void LoadAuftrag(string size, string type)
{ {
this.Dispose(); this.Dispose();
@@ -187,6 +237,7 @@
this.omniContext.LoadAuftrag(size, type); this.omniContext.LoadAuftrag(size, type);
this.HasPruefpunkte = this.omniContext.Pruefpunkte.Any(); this.HasPruefpunkte = this.omniContext.Pruefpunkte.Any();
this.referenceMeter = new ReferenceMeterVM(OmniContext.Current);
if (this.HasPruefpunkte) if (this.HasPruefpunkte)
{ {
@@ -202,6 +253,7 @@
this.omniContext.LoadAuftrag(suchNr); this.omniContext.LoadAuftrag(suchNr);
this.HasPruefpunkte = this.omniContext.Pruefpunkte.Any(); this.HasPruefpunkte = this.omniContext.Pruefpunkte.Any();
this.referenceMeter = new ReferenceMeterVM(OmniContext.Current);
if (this.HasPruefpunkte) if (this.HasPruefpunkte)
{ {
@@ -213,9 +265,67 @@
{ {
this.DispatcherInvoke(() => this.DispatcherInvoke(() =>
{ {
this.Add(new HeadersRowVM()); var checkpoints = OmniContext
this.Add(new DefaultsHeaderRow()); .Current
this.Add(new DefaultsRowVM()); .Auftrag
.Pruefpunkte;
var checkpointsHeader = new ItemsGridRowVM();
checkpointsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
checkpointsHeader.Add(new ItemsGridHeaderVM { Value = "Prüfpunkte", Width = ItemsGridHeaderVM.Auto });
checkpointsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Star });
foreach (var cp in checkpoints)
{
checkpointsHeader.Add(new ItemsGridHeaderVM { Value = $"Q{cp.PPNR}", Width = ItemsGridHeaderVM.Star });
}
checkpointsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Star });
this.Add(checkpointsHeader);
var flowsHeader = new ItemsGridRowVM();
flowsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
flowsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
flowsHeader.Add(new ItemsGridHeaderVM { Value = "m³/h", Width = ItemsGridHeaderVM.Star });
foreach (var cp in checkpoints)
{
flowsHeader.Add(new ItemsGridHeaderVM { Value = $"{cp.FlowM3H:0.000}", Width = ItemsGridHeaderVM.Star });
}
flowsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Star });
this.Add(flowsHeader);
var configHeader = new ItemsGridRowVM();
configHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
configHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
configHeader.Add(new ItemsGridHeaderVM { Value = "r/s", Width = ItemsGridHeaderVM.Star });
foreach (var cp in checkpoints)
{
configHeader.Add(new ItemsGridHeaderVM { Value = $"{cp.Rotations}/{cp.Duration}", Width = ItemsGridHeaderVM.Star });
}
configHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Star });
this.Add(configHeader);
var limitsHeader = new ItemsGridRowVM();
limitsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
limitsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
limitsHeader.Add(new ItemsGridHeaderVM { Value = "min-max %", Width = ItemsGridHeaderVM.Star });
foreach (var cp in checkpoints)
{
limitsHeader.Add(new ItemsGridHeaderVM { Value = $"{cp.MinAccuracy:0.0} - {cp.MaxAccuracy:0.0}", Width = ItemsGridHeaderVM.Star });
}
limitsHeader.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Star });
this.Add(limitsHeader);
this.Add(this.referenceMeter);
}); });
} }
} }
@@ -1,248 +1,293 @@
namespace InspectionUI.ViewModels namespace InspectionUI.ViewModels
{ {
using ExchangeHub;
using InspectionUI.Models; using InspectionUI.Models;
using OmniPlus; using OmniPlus;
using SignalR;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading; using System.Threading;
using System.Timers; using System.Threading.Tasks;
public class ReferenceMeterVM : ItemsGridRowVM public class ReferenceMeterVM : ItemsGridRowVM
{ {
private readonly ICollection<double> flows;
private readonly OmniContext omniContext; private readonly OmniContext omniContext;
private readonly ExchangeConnection signarR; private readonly DataHub signarR;
private int ppnr; private int ppnr;
private bool cancel; private int column;
private Task flowWatcher;
private CancellationTokenSource cancellationTokenSource;
public ReferenceMeterVM(OmniContext omniContext) : base() public ReferenceMeterVM(OmniContext omniContext) : base()
{ {
this.flows = new List<double>();
this.omniContext = omniContext; this.omniContext = omniContext;
this.signarR = new ExchangeConnection(); this.signarR = new DataHub();
this.signarR.Connect(Appsettings.HubURL); this.ppnr = 0;
this.ppnr = 1;
this.LoadHeaders(); Task.Factory
.StartNew(state =>
{
if (state is DataHub dataHub)
{
dataHub.Connect(Appsettings.HubURL);
}
}, this.signarR, CancellationToken.None)
.ContinueWith(task =>
{
});
this.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
this.Add(new ItemsGridHeaderVM { Value = "Referenzzähler", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Value = "Ø m³/h", Width = ItemsGridHeaderVM.Star });
this.column = 2;
foreach (var _ in this.omniContext.Pruefpunkte)
{
this.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Star });
}
this.Add(new ItemsGridHeaderVM { Value = "(±) %", Width = ItemsGridHeaderVM.Star });
} }
internal void Start(OmniPruefpunkt pp) internal void Start(OmniPruefpunkt pp)
{ {
this.ppnr += 3; this.ppnr += 3;
this.cancel = false;
this.StartFlow(pp); this.StartFlow(pp);
this.StartRZ(pp); this.StartRZ(pp);
this.StartFlowWatcher(pp);
} }
private void StartFlow(OmniPruefpunkt pp) private void StartFlow(OmniPruefpunkt pp)
{ {
var interval = 1000; this.column++;
var timeout = 500;
var volume = default(double);
var waitHandle = new ManualResetEventSlim();
var timer = new System.Timers.Timer
{
AutoReset = true,
Enabled = true,
Interval = interval,
};
void FlowStarted(double value, string _) const string Job = nameof(Job);
{ const string GetFlow = nameof(GetFlow);
volume = value; const string StartFlow = nameof(StartFlow);
const string m3h = nameof(m3h);
timer.Stop(); var currentM3H = default(double);
waitHandle.Set();
void getCurrentFlow(DataDictionary _data)
{
var job = _data.GetString(Job);
if (job == GetFlow)
{
currentM3H = _data.GetDouble(m3h);
}
} }
void TimerElapsed(object _, ElapsedEventArgs _1) this.signarR.DataReceived += getCurrentFlow;
{
if (timeout < 0 || cancel)
{
timeout = 0;
timer.Stop(); var data = new DataDictionary();
waitHandle.Set(); data.AddString(Job, StartFlow);
data.AddDouble(m3h, pp.FlowM3H);
this.signarR.Send(data);
var waitHandle = new ManualResetEventSlim();
var secondsIn = default(int);
var qmin = pp.FlowM3H * 0.95;
var qmax = pp.FlowM3H * 1.05;
var timeout = 500;
void checkCurrentFlow(object _)
{
var _data = new DataDictionary();
data.AddString(Job, GetFlow);
this.signarR.Send(data);
timeout--;
if (qmin <= currentM3H && currentM3H <= qmax)
{
secondsIn++;
} }
else else
{ {
this.Set(timeout, "... {0}", this.ppnr + 1); secondsIn = 0;
} }
timeout--; this.Set(timeout, "... {0}", this.column);
if (secondsIn >= 20 || timeout <= 0)
{
waitHandle.Set();
}
} }
timer.Elapsed += TimerElapsed; var timer = new Timer(checkCurrentFlow, null, 0, 1000);
this.signarR.StartFlow += FlowStarted;
waitHandle.Wait(timeout * 1000);
timer.Dispose();
timer.Start(); this.signarR.DataReceived -= getCurrentFlow;
this.signarR.SendStartFlow(pp.FlowM3H); this.Set(string.Empty, null, this.column);
waitHandle.Wait(timeout * interval); this.flows.Add(currentM3H);
waitHandle.Reset();
this.signarR.StartFlow -= FlowStarted;
timer.Elapsed -= TimerElapsed;
waitHandle.Wait(1000);
this.Set(volume, "{0:0.000}", this.ppnr + 1);
} }
private void StartRZ(OmniPruefpunkt pp) private void StartRZ(OmniPruefpunkt pp)
{ {
var interval = 1000; const string Job = nameof(Job);
var timeout = 60; const string StartRZ = nameof(StartRZ);
var seconds = default(double); const string m3h = nameof(m3h);
const string ss = nameof(ss);
var waitHandle = new ManualResetEventSlim(); var waitHandle = new ManualResetEventSlim();
var timer = new System.Timers.Timer
{
AutoReset = true,
Enabled = true,
Interval = interval,
};
void RZStarted(int value, string _) void waitRZStart(DataDictionary _data)
{ {
seconds = value; if (_data.GetString(Job) == StartRZ)
timer.Stop();
waitHandle.Set();
}
void TimerElapsed(object _, ElapsedEventArgs _1)
{
if (timeout < 0 || cancel)
{ {
timeout = 0;
timer.Stop();
waitHandle.Set(); waitHandle.Set();
} }
else
{
this.Set(timeout, "... {0}", this.ppnr);
}
timeout--;
} }
timer.Elapsed += TimerElapsed; this.signarR.DataReceived += waitRZStart;
this.signarR.StartReferenceMessurement += RZStarted;
timer.Start(); var data = new DataDictionary();
this.signarR.SendStartReferenceMessurement(pp.Duration); data.AddDouble(m3h, pp.FlowM3H);
waitHandle.Wait(timeout * interval); data.AddDouble(ss, pp.Duration);
waitHandle.Reset(); data.AddString(Job, StartRZ);
this.signarR.Send(data);
this.signarR.StartReferenceMessurement -= RZStarted; var timeout = 60;
timer.Elapsed -= TimerElapsed;
waitHandle.Wait(1000); void updateTimeLeft(object _)
{
this.Set(timeout--, "... {0}", this.column);
this.Set(seconds, ".../{0:0.0}", this.ppnr); if (timeout <= 0)
{
waitHandle.Set();
}
}
var timer = new Timer(updateTimeLeft, null, 0, 1000);
waitHandle.Wait(timeout * 1000);
timer.Dispose();
this.signarR.DataReceived -= waitRZStart;
this.Set(this.flows.Average(), "{0:0.000}", this.column);
} }
internal double GetFlow() private void StartFlowWatcher(OmniPruefpunkt pp)
{ {
var interval = 1000; this.cancellationTokenSource = new CancellationTokenSource();
var timeout = 60; var cancellationToken = this.cancellationTokenSource.Token;
var referenceV = 0D;
var waitHandle = new ManualResetEventSlim();
var timer = new System.Timers.Timer
{
AutoReset = true,
Enabled = true,
Interval = interval,
};
void ReceiveFlow(double value, string _) this.flowWatcher = Task.Factory
{ .StartNew(() =>
timeout = 0;
referenceV = value;
timer.Stop();
waitHandle.Set();
}
void TimerElapsed(object _, ElapsedEventArgs _1)
{
if (timeout < 0 || cancel)
{ {
timeout = 0; const string Job = nameof(Job);
const string GetFlow = nameof(GetFlow);
void dataReceived(DataDictionary _data)
{
var job = _data.GetString(Job);
var m3h = default(double);
if (job == GetFlow)
{
m3h = _data.GetDouble(nameof(m3h));
this.flows.Add(m3h);
this.Set(this.flows.Average(), "{0:0.000}", this.column);
}
}
this.signarR.DataReceived += dataReceived;
void requestFlow(object _)
{
var data = new DataDictionary();
data.AddString(Job, GetFlow);
this.signarR.Send(data);
}
var waitHandle = new ManualResetEventSlim();
cancellationToken.Register(waitHandle.Set);
var timer = new Timer(requestFlow, null, 0, 1000);
waitHandle.Wait(pp.Duration * 1000);
timer.Dispose();
this.signarR.DataReceived += dataReceived;
}, cancellationToken);
}
internal double GetM3S(OmniPruefpunkt pp)
{
this.cancellationTokenSource.Cancel();
const string Job = nameof(Job);
const string StopRZ = nameof(StopRZ);
const string ss = nameof(ss);
var waitHandle = new ManualResetEventSlim();
var m3s = default(double);
void waitM3S(DataDictionary _data)
{
if (_data.GetString(Job) == StopRZ)
{
m3s = _data.GetDouble(nameof(m3s));
timer.Stop();
waitHandle.Set(); waitHandle.Set();
} }
else
{
this.Set(timeout, "... {0}", this.ppnr + 2);
}
timeout--;
} }
timer.Elapsed += TimerElapsed; this.signarR.DataReceived += waitM3S;
this.signarR.StopReferenceMessurement += ReceiveFlow;
timer.Start(); var data = new DataDictionary();
this.signarR.SendStopReferenceMessurement(); data.AddString(Job, StopRZ);
waitHandle.Wait(timeout * interval); data.AddDouble(nameof(m3s), pp.FlowM3H);
waitHandle.Reset(); data.AddInt(ss, pp.Duration);
this.signarR.Send(data);
this.signarR.StopReferenceMessurement -= ReceiveFlow; waitHandle.Wait(60_000);
timer.Elapsed -= TimerElapsed; this.signarR.DataReceived -= waitM3S;
waitHandle.Wait(1000); return m3s;
this.Set(referenceV, "{0:0.0000000}", this.ppnr + 1);
this.Set(referenceV == 0 ? 0 : 100, "{0:0.00}", this.ppnr + 2);
return referenceV;
} }
internal void Stop() internal void Stop()
{ {
this.cancel = true; this.cancellationTokenSource.Cancel();
this.signarR.SendStopFlow(); const string Job = nameof(Job);
const string StopFlow = nameof(StopFlow);
var data = new DataDictionary();
data.AddString(Job, StopFlow);
this.signarR.Send(data);
} }
public override void Dispose() public override void Dispose()
{ {
try try
{ {
this.signarR.SendStopFlow(); this.Stop();
this.signarR.Disconnect(); this.signarR.Disconnect();
} }
catch (Exception) catch (Exception _ )
{ {
} }
base.Dispose(); base.Dispose();
} }
private void LoadHeaders()
{
this.DispatcherInvoke(() =>
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM { Value = "RZ:" });
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
foreach (var _ in this.omniContext.Pruefpunkte)
{
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
this.Add(new ItemsGridHeaderVM());
}
this.Add(new ItemsGridHeaderVM());
});
}
} }
} }
@@ -0,0 +1,26 @@
namespace InspectionUI.ViewModels
{
using OmniPlus;
public class RotationsHeaderRow : ItemsGridRowVM
{
public RotationsHeaderRow()
{
var pruefpunkte = OmniContext
.Current
.Auftrag
.Pruefpunkte;
this.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Auto });
this.Add(new ItemsGridHeaderVM { Value = "Rotationen", Width = ItemsGridHeaderVM.Star });
this.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Star });
foreach (var pp in pruefpunkte)
{
this.Add(new ItemsGridHeaderVM { Value = $"{pp.Rotations}", Width = ItemsGridHeaderVM.Star });
}
this.Add(new ItemsGridHeaderVM { Width = ItemsGridHeaderVM.Star });
}
}
}
@@ -1,29 +1,132 @@
namespace OmniPlus.Connections namespace OmniPlus.Connections
{ {
using System;
internal sealed class IRDAEncoder : SerialDataEncoder internal sealed class IRDAEncoder : SerialDataEncoder
{ {
public override bool TryDecode(byte[] data, out byte[] message, out int start, out int length) const byte IRDA_START = 0x9B;
{ const byte IRDA_PING = 0x82;
message = default(byte[]); const byte IRDA_PC2REG = 0x33;
const byte IRDA_REG2PC = 0x43;
const byte IRDA_MIN_LENGTH = 5;
if (data.FromIrdaMessage(out byte[] payload, out start, out length)) public IRDAEncoder(SerialDataEncoder encoder = null) : base(encoder)
{
}
public override bool TryDecode(byte[] bytes, out byte[] data, out int start, out int length)
{
start = -1;
length = -1;
data = default(byte[]);
var payload = default(byte[]);
if (bytes is null)
{ {
if (payload.FromUI1236Message(out message, out start, out _)) return false;
}
var bytesLength = bytes.Length;
if (bytesLength == 0)
{
return false;
}
var reg2pc = -1;
var succeeded = false;
while (!succeeded && start < bytesLength)
{
start = Array.IndexOf(bytes, IRDA_START, start + 1);
if (start < 0)
{ {
return true; break;
}
reg2pc = Array.IndexOf(bytes, IRDA_REG2PC);
succeeded = reg2pc - start == 1;
if (reg2pc < 0 && !succeeded)
{
break;
} }
} }
return false; if (!succeeded)
{
return false;
}
var reg2pcIndex = start + 1;
var lengthIndex = start + 2;
var startIndexD = start + 3;
if (lengthIndex >= bytesLength)
{
return false;
}
length = bytes[lengthIndex] * 2;
if (start + length + 5 > bytesLength)
{
return false;
}
payload = new byte[length];
Array.Copy(bytes, startIndexD, payload, 0, length);
length += 5;
if (this.encoder is null)
{
data = payload;
return true;
}
return this.encoder.TryDecode(payload, out data, out _, out _);
} }
public override bool TryEncode(byte[] data, out byte[] message) public override bool TryEncode(byte[] data, out byte[] bytes)
{ {
message = data bytes = new byte[0];
.ToUI1236Message()
.ToIrdaMessage();
return message != null && message.Length > 0; if (data is null || data.Length == 0)
{
return false;
}
var payload = default(byte[]);
this.encoder?.TryEncode(data, out payload);
if (payload is null || payload.Length == 0)
{
return false;
}
var payloadLength = payload.Length;
var bytesLength = payloadLength;
bytesLength += bytesLength % 2;
var index = 0;
bytes = new byte[bytesLength + IRDA_MIN_LENGTH];
bytes[index++] = IRDA_START;
bytes[index++] = IRDA_PC2REG;
bytes[index++] = (byte)(bytesLength / 2);
payload.CopyTo(bytes, index);
var length = bytes.Length;
var crc16 = bytes.CalculateCRC8408(1, length - 2);
bytes[length - 2] = crc16[0];
bytes[length - 1] = crc16[1];
return true;
} }
} }
} }
@@ -4,47 +4,37 @@
internal sealed class IRDAStream : SerialDataStream internal sealed class IRDAStream : SerialDataStream
{ {
private readonly ManualResetEventSlim waitHandle;
public IRDAStream(SerialDataEncoder encoder, SerialPortSettings settings) : base(encoder, settings) public IRDAStream(SerialDataEncoder encoder, SerialPortSettings settings) : base(encoder, settings)
{ {
this.waitHandle = new ManualResetEventSlim();
} }
public override byte[] Send(params byte[] message) public override byte[] Send(params byte[] message)
{ {
var response = new byte[0]; var awaiter = new ManualResetEventSlim();
var received = false; var response = default(byte[]);
void DataReceived(byte[] data) void DataReceived(byte[] data)
{ {
response = data; response = data;
received = true;
this.waitHandle.Set(); awaiter.Set();
this.DataReceived -= DataReceived;
} }
this.DataReceived += DataReceived; this.DataReceived += DataReceived;
this.StartListening(); for (int i = 0; i < 3 && response is null; i++)
for (int i = 0; i < 3 && !received; i++)
{ {
this.WritePlain(1, 1, 1, 1); this.WritePlain(1, 1, 1, 1);
awaiter.Wait(1);
this.waitHandle.Reset(); awaiter.Reset();
this.waitHandle.Wait(1);
this.WriteEncoded(message); this.WriteEncoded(message);
awaiter.Wait(1000);
this.waitHandle.Reset(); awaiter.Reset();
this.waitHandle.Wait(3000);
} }
this.StopListening();
this.DataReceived -= DataReceived;
return response; return response;
} }
} }
@@ -2,8 +2,13 @@
{ {
internal abstract class SerialDataEncoder internal abstract class SerialDataEncoder
{ {
public abstract bool TryEncode(byte[] data, out byte[] message); protected readonly SerialDataEncoder encoder;
public abstract bool TryDecode(byte[] data, out byte[] message, out int start, out int length); protected SerialDataEncoder(SerialDataEncoder encoder = null)
=> this.encoder = encoder;
public abstract bool TryEncode(byte[] bytes, out byte[] payload);
public abstract bool TryDecode(byte[] data, out byte[] bytes, out int start, out int length);
} }
} }
@@ -218,11 +218,11 @@
/// <para>n-2. .... - CRC16 0 </para> /// <para>n-2. .... - CRC16 0 </para>
/// <para>n-1. .... - CRC16 1 </para> /// <para>n-1. .... - CRC16 1 </para>
/// </summary> /// </summary>
public static bool FromIrdaMessage(this byte[] bytes, out byte[] message, out int start, out int length) public static bool FromIrdaMessage(this byte[] bytes, out byte[] payload, out int start, out int length)
{ {
message = default(byte[]); payload = default(byte[]);
length = default(int); length = -1;
start = default(int); start = -1;
if (bytes is null) if (bytes is null)
{ {
@@ -231,41 +231,58 @@
var bytesLength = bytes.Length; var bytesLength = bytes.Length;
while (start < bytesLength) if (bytesLength == 0)
{ {
start = Array.IndexOf(bytes, IRDA_REG2PC, start) - 1; return false;
}
if (start < 0 || bytes[start] == IRDA_START) var reg2pc = -1;
var succeeded = false;
while (!succeeded && start < bytesLength)
{
start = Array.IndexOf(bytes, IRDA_START, start + 1);
if (start < 0)
{ {
break; break;
} }
start += 2; reg2pc = Array.IndexOf(bytes, IRDA_REG2PC);
succeeded = reg2pc - start == 1;
if (reg2pc < 0 && !succeeded)
{
break;
}
} }
if (start < 0) if (!succeeded)
{ {
return false; return false;
} }
start += 2; var reg2pcIndex = start + 1;
var lengthIndex = start + 2;
var startIndexD = start + 3;
if (start >= bytesLength) if (lengthIndex >= bytesLength)
{ {
return false; return false;
} }
length = bytes[start] * 2; length = bytes[lengthIndex] * 2;
if (start + length >= bytesLength) if (start + length + 5 > bytesLength)
{ {
return false; return false;
} }
start += 1; payload = new byte[length];
message = new byte[length];
Array.Copy(bytes, start, message, 0, length); Array.Copy(bytes, startIndexD, payload, 0, length);
length += 5;
return true; return true;
} }
@@ -279,17 +296,24 @@
/// <para>n-2. .... - Checksum 0 </para> /// <para>n-2. .... - Checksum 0 </para>
/// <para>n-1. .... - Checksum 1 </para> /// <para>n-1. .... - Checksum 1 </para>
/// </summary> /// </summary>
public static bool FromUI1236Message(this byte[] bytes, out byte[] message, out int start, out Int32 length) public static bool FromUI1236Message(this byte[] bytes, out byte[] message, out int start, out int length)
{ {
message = default(byte[]); message = default(byte[]);
length = default(int); length = -1;
start = default(int); start = -1;
if (bytes is null) if (bytes is null)
{ {
return false; return false;
} }
var bytesLength = bytes.Length;
if (bytesLength < 5)
{
return false;
}
start = Array.IndexOf(bytes, UI1236_START); start = Array.IndexOf(bytes, UI1236_START);
if (start < 0) if (start < 0)
@@ -313,7 +337,7 @@
start += 2; start += 2;
if (start + length >= bytes.Length) if (start + length > bytes.Length)
{ {
return false; return false;
} }
@@ -7,9 +7,7 @@
internal abstract class SerialDataStream : SerialPortStream internal abstract class SerialDataStream : SerialPortStream
{ {
private readonly ManualResetEventSlim waitHandle;
private readonly SerialDataEncoder encoder; private readonly SerialDataEncoder encoder;
private readonly List<byte> buffer;
private CancellationTokenSource cancellationTokenSource; private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken; private CancellationToken cancellationToken;
@@ -18,8 +16,6 @@
protected SerialDataStream(SerialDataEncoder encoder, SerialPortSettings settings) : base(settings) protected SerialDataStream(SerialDataEncoder encoder, SerialPortSettings settings) : base(settings)
{ {
this.encoder = encoder; this.encoder = encoder;
this.buffer = new List<byte>();
this.waitHandle = new ManualResetEventSlim();
} }
protected event Action<byte[]> DataReceived; protected event Action<byte[]> DataReceived;
@@ -55,32 +51,6 @@
} }
} }
protected void StartListening()
{
try
{
this.buffer.Clear();
this.waitHandle.Set();
}
catch (Exception e)
{
this.NotifyStateChanged($"EX|{e}");
}
}
protected void StopListening()
{
try
{
this.waitHandle.Reset();
this.buffer.Clear();
}
catch (Exception e)
{
this.NotifyStateChanged($"EX|{e}");
}
}
protected void WriteEncoded(params byte[] bytes) protected void WriteEncoded(params byte[] bytes)
{ {
try try
@@ -88,7 +58,6 @@
if (this.encoder.TryEncode(bytes, out byte[] message)) if (this.encoder.TryEncode(bytes, out byte[] message))
{ {
this.Write(message, 0, message.Length); this.Write(message, 0, message.Length);
this.NotifyStateChanged($"TX|{BitConverter.ToString(bytes)}"); this.NotifyStateChanged($"TX|{BitConverter.ToString(bytes)}");
} }
} }
@@ -112,23 +81,30 @@
private void ReadingTaskHandler(object state) private void ReadingTaskHandler(object state)
{ {
if (state is SerialDataStream serialDataStream) if (state is SerialDataStream stream)
{ {
while (serialDataStream.IsOpen) var buffer = new List<byte>();
while (stream.IsOpen)
{ {
serialDataStream.waitHandle.Wait(); var bytes = stream.Read();
var data = serialDataStream.Read(); if (bytes.Length == 0)
var buffer = serialDataStream.buffer;
buffer.AddRange(data);
if (serialDataStream.encoder.TryDecode(buffer.ToArray(), out byte[] message, out int start, out int count))
{ {
buffer.RemoveRange(0, Math.Min(start + count, buffer.Count)); continue;
}
serialDataStream.DataReceived?.Invoke(message);
serialDataStream.NotifyStateChanged($"RX|{BitConverter.ToString(message)}"); buffer.AddRange(bytes);
if (stream.encoder.TryDecode(buffer.ToArray(), out var data, out var start, out var length))
{
stream.DataReceived?.Invoke(data);
stream.NotifyStateChanged($"RX|{BitConverter.ToString(data)}");
buffer.RemoveRange(0, Math.Min(start + length, buffer.Count));
}
else if (start < 0)
{
buffer.Clear();
} }
} }
} }
@@ -147,7 +123,8 @@
} }
this.StartReading(); this.StartReading();
});
}, this.cancellationToken);
} }
} }
} }
@@ -23,39 +23,9 @@
public event StateChanged StateChanged; public event StateChanged StateChanged;
public int BytesToRead public int BytesToRead => this.serialPort?.BytesToRead ?? default(int);
{
get
{
try
{
return this.serialPort?.BytesToRead ?? default(int);
}
catch (Exception e)
{
this.NotifyStateChanged($"EX|{e}");
return default(int); public bool IsOpen => this.serialPort?.IsOpen ?? false;
}
}
}
public bool IsOpen
{
get
{
try
{
return this.serialPort?.IsOpen ?? false;
}
catch (Exception e)
{
this.NotifyStateChanged($"EX|{e}");
return default(bool);
}
}
}
public virtual void Close() public virtual void Close()
{ {
@@ -126,24 +96,17 @@
public abstract byte[] Send(params byte[] message); public abstract byte[] Send(params byte[] message);
protected void NotifyStateChanged(object state) protected void NotifyStateChanged(object state)
{ => this.StateChanged?.Invoke(state);
this.StateChanged?.Invoke(state);
}
protected byte[] Read() protected byte[] Read()
{ {
var bytes = new byte[] { }; var bytes2read = this.BytesToRead;
var bytes = new byte[bytes2read];
try if (bytes2read > 0)
{ {
bytes = new byte[this.BytesToRead]; this.serialPort.Read(bytes, 0, bytes2read);
this.serialPort.Read(bytes, 0, bytes.Length);
}
catch (Exception e)
{
this.NotifyStateChanged($"EX|{e}");
} }
return bytes; return bytes;
@@ -151,22 +114,15 @@
protected void Write(byte[] bytes, int start, int length) protected void Write(byte[] bytes, int start, int length)
{ {
try var lock_object = new object();
{
var lock_object = new object();
lock (lock_object) lock (lock_object)
{
this.serialPort.Write(bytes, 0, length);
}
}
catch (Exception e)
{ {
this.NotifyStateChanged($"EX|{e}"); this.serialPort.Write(bytes, 0, length);
} }
} }
private void DiscardInOut() protected void DiscardInOut()
{ {
try try
{ {
@@ -0,0 +1,102 @@
namespace OmniPlus.Connections
{
using System;
internal sealed class UI1236Encoder : SerialDataEncoder
{
public const byte UI1236_START = 0x0D;
public const byte UI1236_LEN_INDEX = 1;
public const byte UI1236_DATA_INDEX = 3;
public const byte UI1236_MIN_LENGTH = 5;
public UI1236Encoder(SerialDataEncoder encoder = null) : base(encoder)
{
}
public override bool TryDecode(byte[] bytes, out byte[] payload, out int start, out int length)
{
payload = default(byte[]);
length = -1;
start = -1;
if (bytes is null || bytes.Length == 0)
{
return false;
}
var bytesLength = bytes.Length;
start = Array.IndexOf(bytes, UI1236_START);
if (start < 0)
{
return false;
}
var lengthIndex = start + 1;
if (lengthIndex >= bytesLength)
{
return false;
}
length = bytes[lengthIndex] - 3;
if (length <= 0)
{
return false;
}
var controlIndex = lengthIndex + 1;
if (controlIndex >= bytesLength)
{
return false;
}
var dataIndex = controlIndex + 1;
if (dataIndex + length > bytesLength)
{
return false;
}
payload = new byte[length];
Array.Copy(bytes, dataIndex, payload, 0, length);
return true;
}
public override bool TryEncode(byte[] data, out byte[] bytes)
{
bytes = new byte[0];
if (data is null || data.Length == 0)
{
return false;
}
var dataLength = data.Length;
var bytesLength = dataLength + UI1236_MIN_LENGTH;
var index = 0;
bytes = new byte[bytesLength];
bytes[index++] = UI1236_START;
bytes[index++] = (byte)(dataLength + 3);
UI1236Control control = 0;
control.ReturnResponse = true;
bytes[index++] = control;
data.CopyTo(bytes, index);
var checksum = bytes.CalculateCheckSUM(bytesLength - 2);
var checksumIndex = dataLength + 3;
bytes[checksumIndex++] = checksum[1];
bytes[checksumIndex++] = checksum[0];
return true;
}
}
}
@@ -4,43 +4,44 @@
internal class UniProStream : SerialDataStream internal class UniProStream : SerialDataStream
{ {
private readonly ManualResetEventSlim waitHandle;
public UniProStream(SerialDataEncoder encoder, SerialPortSettings settings) : base(encoder, settings) public UniProStream(SerialDataEncoder encoder, SerialPortSettings settings) : base(encoder, settings)
{ {
this.waitHandle = new ManualResetEventSlim();
} }
public override byte[] Send(params byte[] message) public override byte[] Send(params byte[] message)
{ {
var response = new byte[0]; byte[] SendMessage(int count = 3)
var received = false;
void DataReceived(byte[] data)
{ {
response = data; var awaiter = new ManualResetEventSlim();
received = true; var response = new byte[0];
var received = false;
this.waitHandle.Set(); void DataReceived(byte[] data)
} {
response = data;
received = true;
this.DataReceived += DataReceived; awaiter.Set();
}
this.StartListening(); this.DataReceived += DataReceived;
for (int i = 0; i < 3 && !received; i++)
{
this.WriteEncoded(message); this.WriteEncoded(message);
this.waitHandle.Reset(); awaiter.Wait(5000);
this.waitHandle.Wait(3000); awaiter.Reset();
this.DataReceived -= DataReceived;
if (!received && count > 1)
{
return SendMessage(count - 1);
}
return response;
} }
this.StopListening(); return SendMessage();
this.DataReceived -= DataReceived;
return response;
} }
} }
} }
@@ -67,8 +67,8 @@
public class ConfigurationParametersSet : FeatureRequest public class ConfigurationParametersSet : FeatureRequest
{ {
const int LENGTH = 80; // const int LENGTH = 80;
// const int LENGTH = 89; const int LENGTH = 89;
public ConfigurationParametersSet() : base(LENGTH) public ConfigurationParametersSet() : base(LENGTH)
{ {
+1 -1
View File
@@ -398,7 +398,7 @@
return new FeatureResponse(response); return new FeatureResponse(response);
} }
public FeatureResponse FactorySeal(bool? seal = null) public FactorySeal FactorySeal(bool? seal = null)
{ {
var request = default(byte[]); var request = default(byte[]);
+21 -6
View File
@@ -20,7 +20,7 @@
public OmniParameter Defaults public OmniParameter Defaults
{ {
get => this.Auftrag?.TypeParameters ?? new OmniParameter(); get => this.Auftrag?.TypeParameters;
} }
public IEnumerable<OmniPruefpunkt> Pruefpunkte public IEnumerable<OmniPruefpunkt> Pruefpunkte
@@ -86,18 +86,33 @@
} }
} }
internal int UpdateTestRun(IDictionary<string, object> parameters, int id, byte slotNr) internal int UpdateTestRun(IDictionary<string, object> parameters, int id, byte slotNr)
{ => this.database.UpdateTestRun(parameters, id, slotNr);
return this.database.UpdateTestRun(parameters, id, slotNr);
}
public static OmniContext Current { get; private set; } public static OmniContext Current { get; private set; }
public static OmniContext Create(String omniDB, String outputDirectory) public static OmniContext Create(String omniDB, String outputDirectory)
{ {
Current = new OmniContext(omniDB, outputDirectory); if (Current is null)
{
Current = new OmniContext(omniDB, outputDirectory);
}
return Current; return Current;
} }
public class Programming
{
public string ProgrammableID { get; set; }
public string FactoryID { get; set; }
}
internal Programming NextProgrammingNumbers()
{
// TODO: get the programming numbers
return new Programming();
}
} }
} }
+104 -19
View File
@@ -107,6 +107,8 @@
Factor = reader.GetSmallint(17), Factor = reader.GetSmallint(17),
PulsePerRotation = reader.GetTinyint(18) PulsePerRotation = reader.GetTinyint(18)
}; };
this.LoadDefaults(auftrag.TypeParameters, reader.GetTinyint(12), reader.GetString(21));
} }
if (auftrag.Pruefpunkte is null) if (auftrag.Pruefpunkte is null)
@@ -214,6 +216,8 @@
Factor = reader.GetSmallint(7), Factor = reader.GetSmallint(7),
PulsePerRotation = reader.GetTinyint(8) PulsePerRotation = reader.GetTinyint(8)
}; };
this.LoadDefaults(auftrag.TypeParameters, reader.GetTinyint(2), reader.GetString(11));
} }
if (auftrag.Pruefpunkte is null) if (auftrag.Pruefpunkte is null)
@@ -248,9 +252,8 @@
return auftrag; return auftrag;
} }
public OmniPruefgang AddTestRun(int id, string psnr, int slotnr, string buildInfo) public OmniPruefgang AddTestRun(int id, string psnr, int slotnr, string buildInfo)
{ => this.sqlConnection
return this.sqlConnection
.CreateCommand($@" .CreateCommand($@"
INSERT INSERT
INTO [OmniTestRuns] ([Id], [PsNr], [SlotNr], [BuildInfo]) INTO [OmniTestRuns] ([Id], [PsNr], [SlotNr], [BuildInfo])
@@ -270,7 +273,6 @@
BuildInfo = reader.GetString(), BuildInfo = reader.GetString(),
AddDate = reader.GetDate() AddDate = reader.GetDate()
}); });
}
public int UpdateTestRun(IDictionary<string, object> parameters, int id, byte slotNr) public int UpdateTestRun(IDictionary<string, object> parameters, int id, byte slotNr)
{ {
@@ -289,27 +291,73 @@
.ExecuteNonQuery(); .ExecuteNonQuery();
} }
public bool OmniPlus_Exists(string meterNr) public bool OmniPlus_Exists(string meterNr)
{ => this.sqlConnection
return this.sqlConnection
.CreateCommand($@"SELECT COUNT(1) FROM [OmniPlus] WHERE [MeterNr] = @{nameof(meterNr)}") .CreateCommand($@"SELECT COUNT(1) FROM [OmniPlus] WHERE [MeterNr] = @{nameof(meterNr)}")
.SetParameter(nameof(meterNr), meterNr) .SetParameter(nameof(meterNr), meterNr)
.ExecuteScalar(x => x.GetInt()) > 0; .ExecuteScalar(x => x.GetInt()) > 0;
}
public int OmniPlus_Insert(string meterNr, string meterState) public int OmniPlus_Insert(string meterNr, string meterState)
{ => this.sqlConnection
return this.sqlConnection
.CreateCommand($@"INSERT INTO [OmniPlus] ([MeterNr], [MeterState]) VALUES (@{nameof(meterNr)}, @{nameof(meterState)})") .CreateCommand($@"INSERT INTO [OmniPlus] ([MeterNr], [MeterState]) VALUES (@{nameof(meterNr)}, @{nameof(meterState)})")
.SetParameter(nameof(meterNr), meterNr) .SetParameter(nameof(meterNr), meterNr)
.SetParameter(nameof(meterState), meterState) .SetParameter(nameof(meterState), meterState)
.ExecuteNonQuery(); .ExecuteNonQuery();
}
private void ErrorLogger(string error) private void ErrorLogger(string error)
{ => File.AppendAllText(this.outputFile, $"{error}{Environment.NewLine}");
File.AppendAllText(this.outputFile, $"{error}{Environment.NewLine}");
} private void LoadDefaults(OmniParameter defaults, byte size, string variant)
=> this.sqlConnection
.CreateCommand($@"
SELECT [MeterUnits]
, [FlowUnits]
, [FlowRate]
, [PulseWeight]
, [PulseWidth]
, [PulseUpdate]
, [AlarmPercistancePeriodDays]
, [DataLogIntervalMinutes]
, [NumberOfReadingDigits]
, [OptionalUniDirFields]
, [ReadingPreset]
, [RebootCount]
, [DeviceID]
, [LeakAlarmGPM]
, [LeakAlarmTime]
, [HighFlowAlarmGPM]
, [HighFlowAlarmTime]
, [ReverseFlowAlarmGPM]
, [ReverseFlowAlarmTime]
FROM [OmniDefaults]
WHERE [Size] = @{nameof(size)}
AND [Variant] = @{nameof(variant)}")
.SetParameter(nameof(size), $"{size}")
.SetParameter(nameof(variant), variant)
.FirstOrDefault(x =>
{
defaults.MeterUnits = x.GetValue<byte>(0);
defaults.FlowUnits = x.GetValue<byte>(1);
defaults.FlowRate = x.GetValue<byte>(2);
defaults.PulseWeight = x.GetValue<byte>(3);
defaults.PulseWidth = x.GetValue<byte>(4);
defaults.PulseUpdate = x.GetValue<byte>(5);
defaults.AlarmPercistancePeriodDays = x.GetValue<byte>(6);
defaults.DataLogIntervalMinutes = x.GetValue<ushort>(7);
defaults.NumberOfReadingDigits = x.GetValue<sbyte>(8);
defaults.OptionalUniDirFields = x.GetValue<ushort>(9);
defaults.ReadingPreset = x.GetValue<string>(10);
defaults.RebootCount = x.GetValue<byte>(11);
defaults.DeviceID = x.GetValue<string>(12);
defaults.LeakAlarmGPM = x.GetValue<float>(13);
defaults.LeakAlarmTime = x.GetValue<uint>(14);
defaults.HighFlowAlarmGPM = x.GetValue<float>(15);
defaults.HighFlowAlarmTime = x.GetValue<uint>(16);
defaults.ReverseFlowAlarmGPM = x.GetValue<float>(17);
defaults.ReverseFlowAlarmTime = x.GetValue<uint>(18);
return default(object);
});
} }
public class OmniAuftrag public class OmniAuftrag
@@ -373,6 +421,44 @@
public short Factor { get; internal set; } public short Factor { get; internal set; }
public byte PulsePerRotation { get; internal set; } public byte PulsePerRotation { get; internal set; }
public byte MeterUnits { get; internal set; }
public byte FlowUnits { get; internal set; }
public byte FlowRate { get; internal set; }
public byte PulseWeight { get; internal set; }
public byte PulseWidth { get; internal set; }
public byte PulseUpdate { get; internal set; }
public byte AlarmPercistancePeriodDays { get; internal set; }
public ushort DataLogIntervalMinutes { get; internal set; }
public sbyte NumberOfReadingDigits { get; internal set; }
public ushort OptionalUniDirFields { get; internal set; }
public string ReadingPreset { get; internal set; }
public byte RebootCount { get; internal set; }
public string DeviceID { get; internal set; }
public float LeakAlarmGPM { get; internal set; }
public uint LeakAlarmTime { get; internal set; }
public float HighFlowAlarmGPM { get; internal set; }
public uint HighFlowAlarmTime { get; internal set; }
public float ReverseFlowAlarmGPM { get; internal set; }
public uint ReverseFlowAlarmTime { get; internal set; }
} }
public class OmniPruefpunkt public class OmniPruefpunkt
@@ -397,8 +483,6 @@
public double FlowM3H => this.GalPerMin.GPM2M3H(); public double FlowM3H => this.GalPerMin.GPM2M3H();
public int TargetDuration => this.CalculateTargetDuration();
public OmniParameter Defaults { get; internal set; } public OmniParameter Defaults { get; internal set; }
} }
@@ -471,7 +555,7 @@
.ToArray(); .ToArray();
} }
internal void CloseTestRun() internal void CloseTestRun(string Debug)
{ {
this.EndDate = DateTime.Now; this.EndDate = DateTime.Now;
@@ -480,6 +564,7 @@
{ nameof(CrrfAfter), this.CrrfAfter }, { nameof(CrrfAfter), this.CrrfAfter },
{ nameof(Succeeded), this.Succeeded }, { nameof(Succeeded), this.Succeeded },
{ nameof(EndDate), this.EndDate }, { nameof(EndDate), this.EndDate },
{ nameof(Debug), Debug },
}; };
foreach (var testedPP in this.TestedPoints) foreach (var testedPP in this.TestedPoints)
@@ -11,7 +11,7 @@
public OmniIrdaConnection(string portName) public OmniIrdaConnection(string portName)
{ {
this.stream = new IRDAStream( this.stream = new IRDAStream(
encoder: new IRDAEncoder(), encoder: new IRDAEncoder(new UI1236Encoder()),
settings: new SerialPortSettings settings: new SerialPortSettings
{ {
BaudRate = 115200, BaudRate = 115200,
+155 -172
View File
@@ -10,6 +10,7 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
public class OmniMeter public class OmniMeter
@@ -45,6 +46,37 @@
public bool IsActive { get; private set; } public bool IsActive { get; private set; }
private RegisterSettings registerSettings;
private string meterUnits;
public string MeterUnits
{
get
{
if (this.registerSettings is null)
{
this.registerSettings = this.connection.ViewRegisterSettings();
}
if (string.IsNullOrWhiteSpace(this.meterUnits))
{
if (this.registerSettings.MeterUnits == (byte)MessurementUnits.CubicMeters)
{
this.meterUnits = "m³";
}
else if (this.registerSettings.MeterUnits == (byte)MessurementUnits.USGallons)
{
this.meterUnits = "GAL";
}
else
{
this.meterUnits = "unknown";
}
}
return this.meterUnits;
}
}
public void Connect(int connectionType = 0) public void Connect(int connectionType = 0)
{ {
if (this.connection is null) if (this.connection is null)
@@ -90,6 +122,36 @@
} }
} }
public string ReadDisplay()
{
try
{
if (this.registerSettings is null)
{
this.registerSettings = this.connection.ViewRegisterSettings();
}
var displayValue = this.connection.ViewReadings().Value ?? string.Empty;
if (double.TryParse(displayValue, out var readings))
{
if (this.registerSettings.MeterUnits == (byte)MessurementUnits.CubicMeters)
{
readings = readings / 1000;
displayValue = $"{readings:0.000}";
}
}
return displayValue;
}
catch (Exception)
{
return string.Empty;
}
}
public void Dispose() public void Dispose()
{ {
if (this.connection != null) if (this.connection != null)
@@ -149,9 +211,6 @@
public Tuple<double, string, double> StopCalibration(OmniPruefpunkt pp, double refm3s) public Tuple<double, string, double> StopCalibration(OmniPruefpunkt pp, double refm3s)
{ {
var response = this.connection.ViewChamberCalibration(); var response = this.connection.ViewChamberCalibration();
Thread.Sleep(1000);
var rotations = response.Rotations; var rotations = response.Rotations;
var duration = response.DurationSec; var duration = response.DurationSec;
@@ -167,15 +226,15 @@
public void FinishInspection() public void FinishInspection()
{ {
var crrf = this.TestRun var correctionFactor = this.TestRun
.GetAccuracies() .GetAccuracies()
.GetCalibrationFactor(out bool succeeded); .GetCalibrationFactor(out var succeeded);
var testPoints = OmniContext var testPoints = OmniContext
.Current .Current
.Auftrag .Auftrag
.Pruefpunkte .Pruefpunkte
.ToDictionary(x => x.PPNR, x => new Tuple<double, double>(x.MinAccuracy, x.MaxAccuracy)); .ToDictionary(x => x.PPNR, x => new Tuple<double, double>(x.MinAccuracy, x.MaxAccuracy));
foreach (var test in this.TestRun.TestedPoints) foreach (var test in this.TestRun.TestedPoints)
{ {
var ppnr = test.PPNR ?? 0; var ppnr = test.PPNR ?? 0;
@@ -188,7 +247,7 @@
} }
var point = testPoints[ppnr]; var point = testPoints[ppnr];
var acc = test.Accuracy + crrf; var acc = test.Accuracy + correctionFactor;
test.Acc = acc; test.Acc = acc;
test.Succeeded = point.Item1 <= acc && acc <= point.Item2; test.Succeeded = point.Item1 <= acc && acc <= point.Item2;
@@ -199,118 +258,106 @@
} }
} }
//if (succeeded) var debug = new StringBuilder();
//{
// // if (Variant == "R2")
// //{
// // var deviceIDcmd = new byte[11];
// // deviceIDcmd[0] = 0xFD;
// // deviceIDcmd[1] = 0x27;
// // Encoding void appendState(object arg)
// // .ASCII
// // .GetBytes("OMNI-02")
// // .CopyTo(deviceIDcmd, 2);
// // var rs = connection.Send(deviceIDcmd);
// //}
// //var settings = this.connection.ViewRegisterSettings();
// //var parameters = this.connection.ViewSystemParameters();
// //var configuration = this.connection.ViewConfigurationParameters();
// //var systemReset = this.connection.Set(new SystemTime());
// //Thread.Sleep(30000);
// //var response = this.connection.Set(new RegisterSettings
// //{
// // IntPart = this.defaults.IntPart,
// // Fraction = (ushort)this.defaults.Fraction,
// // Size = this.defaults.Size,
// // Range = this.defaults.Range,
// // VolumePerPulseUnit = 0x00,
// // MeterUnits = (byte)MessurementUnits.USGallons,
// // FlowUnits = (byte)MessurementUnits.USGallons,
// // FlowRate = (byte)TimeUnits.Minutes,
// // FactoryCorrection = (sbyte)(crrf * 10),
// // FieldCorrection = 0x00,
// // PulseWeight = 1,
// // PulseWidth = 2,
// // PulseUpdate = 0,
// //});
// //response = this.connection.Set(new ConfigurationParametersSet
// //{
// // BuildInfo = parameters.BuildInfo.Value,
// // ProgrammableID = configuration.ProgrammableID.Value,
// // FactoryID = configuration.FactoryID.Value,
// // AlarmPercistancePeriodDays = 31,
// // DataLogIntervalMinutes = 60,
// // ManifacturingTime = parameters.ManifacturingTime.SecondsSince,
// // NumberOfReadingDigits = 8,
// // OptionalUniDirFields = 0x01FC,
// // ReadingPreset = "000000101",
// // RebootCount = 0,
// // SystemTime = Epoch20000101.UTCNow,
// // DeviceID = "OMNI-01"
// //});
// //response = this.connection.ClearDisplay();
// //response = this.connection.Set(new LeakAlarm
// //{
// // FlowRateGPM = 0.25F,
// // TimeLimit = 24 * 60 * 60
// //});
// //response = this.connection.Set(new HighFlowAlarm
// //{
// // FlowRateGPM = 25F,
// // TimeLimit = 1 * 60 * 60
// //});
// //response = this.connection.Set(new ReverseFlowAlarm
// //{
// // FlowRateGPM = -1F,
// // TimeLimit = 60
// //});
// //response = this.connection.ClearAlarms();
// //response = this.connection.EnableNFC();
// //var alarmsState = this.connection.ViewAlarmsState();
// //response = this.connection.ViewAlarmSettings(0x01);
// //response = this.connection.ViewAlarmSettings(0x02);
// //response = this.connection.ViewAlarmSettings(0x04);
// //response = this.connection.FactorySeal(true);
// //response = this.connection.FactorySeal();
//}
var response = this.connection.Set(new RegisterSettings
{ {
IntPart = this.defaults.IntPart, debug.AppendLine($"{arg}");
Fraction = (ushort)this.defaults.Fraction, }
Size = this.defaults.Size,
Range = this.defaults.Range, connection.StateChenged += appendState;
var parameters = connection.ViewSystemParameters();
var settings = connection.ViewRegisterSettings();
var configuration = connection.ViewConfigurationParameters();
var systemReset = connection.Set(new SystemTime());
Thread.Sleep(10000);
var response = connection.Set(new RegisterSettings
{
IntPart = settings.IntPart,
Fraction = settings.Fraction,
Size = settings.Size,
Range = settings.Range,
VolumePerPulseUnit = 0x00, VolumePerPulseUnit = 0x00,
MeterUnits = (byte)MessurementUnits.USGallons, MeterUnits = this.defaults.MeterUnits,
FlowUnits = (byte)MessurementUnits.USGallons, FlowUnits = this.defaults.FlowUnits,
FlowRate = (byte)TimeUnits.Minutes, FlowRate = this.defaults.FlowRate,
FactoryCorrection = (sbyte)(crrf * 10), FactoryCorrection = (sbyte)(correctionFactor * 10),
FieldCorrection = 0x00, FieldCorrection = 0x00,
PulseWeight = 1, PulseWeight = this.defaults.PulseWeight,
PulseWidth = 2, PulseWidth = this.defaults.PulseWidth,
PulseUpdate = 0, PulseUpdate = this.defaults.PulseUpdate,
}); });
var buildInfo = parameters.BuildInfo.Value;
var programming = OmniContext.Current.NextProgrammingNumbers();
response = connection.Set(new ConfigurationParametersSet
{
BuildInfo = buildInfo,
ProgrammableID = programming.ProgrammableID ?? buildInfo,
FactoryID = programming.FactoryID ?? buildInfo,
AlarmPercistancePeriodDays = this.defaults.AlarmPercistancePeriodDays,
DataLogIntervalMinutes = this.defaults.DataLogIntervalMinutes,
ManifacturingTime = parameters.ManifacturingTime.SecondsSince,
NumberOfReadingDigits = this.defaults.NumberOfReadingDigits,
OptionalUniDirFields = this.defaults.OptionalUniDirFields,
ReadingPreset = this.defaults.ReadingPreset,
RebootCount = this.defaults.RebootCount,
SystemTime = Epoch20000101.UTCNow,
DeviceID = this.defaults.DeviceID
});
response = connection.ClearDisplay();
response = connection.Set(new LeakAlarm
{
FlowRateGPM = this.defaults.LeakAlarmGPM,
TimeLimit = this.defaults.LeakAlarmTime
});
response = connection.Set(new HighFlowAlarm
{
FlowRateGPM = this.defaults.HighFlowAlarmGPM,
TimeLimit = this.defaults.HighFlowAlarmTime
});
response = connection.Set(new ReverseFlowAlarm
{
FlowRateGPM = this.defaults.ReverseFlowAlarmGPM,
TimeLimit = this.defaults.ReverseFlowAlarmTime
});
response = connection.ClearAlarms();
response = connection.EnableNFC();
var alarmsState = connection.ViewAlarmsState();
response = connection.ViewAlarmSettings(0x01);
response = connection.ViewAlarmSettings(0x02);
response = connection.ViewAlarmSettings(0x04);
response = connection.FactorySeal(true);
response = connection.FactorySeal();
parameters = connection.ViewSystemParameters();
settings = connection.ViewRegisterSettings();
configuration = connection.ViewConfigurationParameters();
this.TestRun.Succeeded = succeeded; this.TestRun.Succeeded = succeeded;
this.TestRun.CrrfAfter = this.connection.ViewFactoryCorrection(); this.TestRun.CrrfAfter = this.connection.ViewFactoryCorrection();
this.TestRun.CloseTestRun(); this.TestRun.CloseTestRun(debug.ToString());
//if (this.factorySealed) connection.StateChenged -= appendState;
//{
// this.connection.FactorySeal(true);
//}
} }
public void NotifyStateChanged(object state) public void NotifyStateChanged(object state)
{ {
this.logger.Trace(state); try
{
this.logger.Trace(state);
}
catch (Exception _)
{
}
} }
private ILogger CreateNLogger(string name) private ILogger CreateNLogger(string name)
@@ -327,7 +374,7 @@
{ {
CreateDirs = true, CreateDirs = true,
KeepFileOpen = true, KeepFileOpen = true,
FileName = $"${{CurrentDir}}/{name}/{DateTime.Now:yyyy-MM-dd}/{DateTime.Now:HHmmss}.txt" FileName = $"${{CurrentDir}}/{name}/{DateTime.Now:yyyyMMdd}.txt"
}); });
LogManager.Configuration.AddRule(LogLevel.Trace, LogLevel.Fatal, name); LogManager.Configuration.AddRule(LogLevel.Trace, LogLevel.Fatal, name);
LogManager.ReconfigExistingLoggers(); LogManager.ReconfigExistingLoggers();
@@ -335,68 +382,4 @@
return LogManager.GetLogger(name); return LogManager.GetLogger(name);
} }
} }
} }
/***
* System parameters:
* - Build information
* - Manifacturing time
* - System time
* - Reboot count
* - Version & Type
* - Battery voltage
* - Volts
* - ADC counts
* - Factory seal
* Input volume:
* - Integer part
* - Fractional part
* - Meter size
* - Meter range
* For each test point:
* - Calibration type
* - Rotations
* - Seconds
* Aggregate configuration parameters:
* - Programmable ID
* - Factory ID
* - Number of reading digits
* - Reading
* - Optional uni-directional fields
* - Alarm presistance period
* - Data log interval
* - Device ID
* Register settings:
* - Volume per ml - integer part
* - Volume per ml - fractional part
* - Meter size
* - Meter range
* - Volum per pulse units - always 0x00 (m³)
* - Meter units
* - Flow units
* - Flow rate
* - Factory correction
* - Field correction
* - Pulse weight
* - Pulse width
* - Pulse update rate
* Alarm settings:
* - Leak alarm
* - Device ID = 0x00
* - Alarm Type = 0x04
* - Alarm ID = 0x01
* - Rate = GPM * 1/60 * 1/1
* - Time limit - hh
* - High flow alarm
* - Device ID = 0x00
* - Alarm Type = 0x04
* - Alarm ID = 0x02
* - Rate = GPM * 1/60 * 1/1
* - Time limit - ss
* - Reverse flow alarm
* - Device ID = 0x00
* - Alarm Type = 0x05
* - Alarm ID = 0x04
* - Rate = GPM * 1/60 * 1/1
* - Time limit - ss
*/
+1
View File
@@ -69,6 +69,7 @@
<Compile Include="Connections\SIRTEncoder.cs" /> <Compile Include="Connections\SIRTEncoder.cs" />
<Compile Include="Connections\SIRTExtensions.cs" /> <Compile Include="Connections\SIRTExtensions.cs" />
<Compile Include="Connections\SIRTStream.cs" /> <Compile Include="Connections\SIRTStream.cs" />
<Compile Include="Connections\UI1236Encoder.cs" />
<Compile Include="Connections\UniProEncoder.cs" /> <Compile Include="Connections\UniProEncoder.cs" />
<Compile Include="Connections\UniProStream.cs" /> <Compile Include="Connections\UniProStream.cs" />
<Compile Include="Connections\SerialDataEncoder.cs" /> <Compile Include="Connections\SerialDataEncoder.cs" />
+47 -1
View File
@@ -125,4 +125,50 @@ CREATE TABLE [OmniTestRuns] (
[EndDate] DATETIME NULL, [EndDate] DATETIME NULL,
CONSTRAINT [PK_OmniTestRuns] PRIMARY KEY ([Id], [SlotNr]) CONSTRAINT [PK_OmniTestRuns] PRIMARY KEY ([Id], [SlotNr])
); );
IF OBJECT_ID(N'[OmniDefaults]') IS NOT NULL DROP TABLE [OmniDefaults]
GO
CREATE TABLE [OmniDefaults] (
[Size] TINYINT NOT NULL
, [Variant] VARCHAR(30) NOT NULL
, [MeterUnits] TINYINT NOT NULL DEFAULT(0)
, [FlowUnits] TINYINT NOT NULL DEFAULT(0)
, [FlowRate] TINYINT NOT NULL DEFAULT(0)
, [PulseWeight] TINYINT NOT NULL DEFAULT(0)
, [PulseWidth] TINYINT NOT NULL DEFAULT(0)
, [PulseUpdate] TINYINT NOT NULL DEFAULT(0)
, [AlarmPercistancePeriodDays] TINYINT NOT NULL DEFAULT(0)
, [DataLogIntervalMinutes] INT NOT NULL DEFAULT(0)
, [NumberOfReadingDigits] SMALLINT NOT NULL DEFAULT(9)
, [OptionalUniDirFields] INT NOT NULL DEFAULT(0)
, [ReadingPreset] VARCHAR(15) NOT NULL DEFAULT('000000000')
, [RebootCount] TINYINT NOT NULL DEFAULT(0)
, [DeviceID] VARCHAR(15) NOT NULL DEFAULT('OMNI-01')
, [LeakAlarmGPM] FLOAT NOT NULL DEFAULT(0)
, [LeakAlarmTime] BIGINT NOT NULL DEFAULT(0)
, [HighFlowAlarmGPM] FLOAT NOT NULL DEFAULT(0)
, [HighFlowAlarmTime] BIGINT NOT NULL DEFAULT(0)
, [ReverseFlowAlarmGPM] FLOAT NOT NULL DEFAULT(0)
, [ReverseFlowAlarmTime] BIGINT NOT NULL DEFAULT(0)
)
GO
CREATE
UNIQUE
INDEX [IX_OnniDefaults_Size_Variant]
ON [OmniDefaults]([Size], [Variant])
GO
INSERT
INTO [OmniDefaults]
( [Size]
, [Variant])
SELECT DISTINCT
[TP].[Size]
, [PP].[OmniVariant]
FROM [OmniTypes] AS [TP]
JOIN [OmniTestPoints] AS [PP]
ON [PP].[OmniTypeId] = [TP].[TypeId]
GO
+18 -18
View File
@@ -1,21 +1,21 @@
01: 01-39-34-37-30-35-36-39-33-00 01: 01-39-34-37-30-35-36-39-33-00
03: 01-39-38-30-35-38-34-31-34-00 03: 01-39-38-30-35-38-34-31-34-00
05: 01-52-31-2E-32-34-2C-4F-4D-4E-49-2D-30-31-2C-52-30-2E-33-2E-31-39-00 05: 01-52-31-2E-32-34-2C-4F-4D-4E-49-2D-30-31-2C-52-30-2E-33-2E-31-39-00
07: 01-00 07: 01-00
09: 01-08-00 09: 01-08-00
0B: 01-04 0B: 01-04
0D: 01-04-02 0D: 01-04-02
0F: 01-00 0F: 01-00
11: 01-FD 11: 01-FD
13: 01-30-30-30-30-30-31-30-30-00 13: 01-30-30-30-30-30-31-30-30-00
15: 01-FF 15: 01-FF
17: 01-38-31-36-32-33-33-35-31-35-36-35-30-00 17: 01-38-31-36-32-33-33-35-31-35-36-35-30-00
1F: 02 1F: 02
21: 02 21: 02
25: 02 25: 02
27: 01-FC-01-0C-00 27: 01-FC-01-0C-00
29: 02 29: 02
2B: 01-2E-59-FC-01-05-04-08-00-01-34-00-00-00-00-00-FF-C9-9A-3B 2B: 01-2E-59-FC-01-05-04-08-00-01-34-00-00-00-00-00-FF-C9-9A-3B
FD-02: 01-00-00-E1-84-05-00 FD-02: 01-00-00-E1-84-05-00
FD-05: 01-B2-C2-0D-2D FD-05: 01-B2-C2-0D-2D
FD-06: 01-00-00-00-01-FE-04 FD-06: 01-00-00-00-01-FE-04
+40 -8
View File
@@ -106,17 +106,49 @@
public T GetValue<T>(int index = -1) public T GetValue<T>(int index = -1)
{ {
this.SetIndex(index); if (index > 0)
if (!this.sqlDataReader.IsDBNull(this.index))
{ {
if (this.sqlDataReader.GetValue(this.index) is T value) if (!this.sqlDataReader.IsDBNull(index))
{ {
return value; var value = this.sqlDataReader.GetValue(index);
} var type = Nullable.GetUnderlyingType(typeof(T));
}
return default(T); if (type is null)
{
type = typeof(T);
}
try
{
value = Convert.ChangeType(value, type);
}
catch (Exception)
{
// TODO:
}
if (value is T _value)
{
return _value;
}
}
return default(T);
}
else
{
this.SetIndex(index);
if (!this.sqlDataReader.IsDBNull(this.index))
{
if (this.sqlDataReader.GetValue(this.index) is T value)
{
return value;
}
}
return default(T);
}
} }
public object GetValue(string column) public object GetValue(string column)
-8
View File
@@ -1,8 +0,0 @@
namespace Plugins.Abstraction
{
using System;
public interface IMeter : IDisposable
{
}
}
@@ -1,8 +0,0 @@
namespace Plugins.Abstraction
{
using System;
public interface IMeterBatch : IDisposable
{
}
}
-21
View File
@@ -1,21 +0,0 @@
namespace Plugins.OMNI
{
using Plugins.Abstraction;
using System.Collections.Generic;
public class OmniBatch : IMeterBatch
{
private readonly ICollection<IMeter> meters;
public OmniBatch()
{
this.meters = new List<IMeter>();
}
public void Dispose()
{
}
}
}
-12
View File
@@ -1,12 +0,0 @@
namespace Plugins.OMNI
{
using Plugins.Abstraction;
internal class OmniMeter : IMeter
{
public void Dispose()
{
}
}
}
@@ -50,7 +50,7 @@ namespace ProductionUiCordonel.ProductionProcesses.Actions
apps.Add(new CordonelAppVersion(item.AppId, item.StrVersion, item.AppId != 15)); apps.Add(new CordonelAppVersion(item.AppId, item.StrVersion, item.AppId != 15));
} }
apps.Add(new CordonelAppVersion(-1, GenesisMeter.BuildFwVersionString(Meter.CoreRevision), false)); apps.Add(new CordonelAppVersion(-1, Meter.StrCoreRevision, false));
var url = $"{ServiceUrls.MeterProcessStateUrl()}SetCordonelProgress?PcbId={Meter.PcbId}&ProgressName=Shipping&version={Assembly.GetExecutingAssembly().GetName().Version}"; var url = $"{ServiceUrls.MeterProcessStateUrl()}SetCordonelProgress?PcbId={Meter.PcbId}&ProgressName=Shipping&version={Assembly.GetExecutingAssembly().GetName().Version}";
LocalWebRequest.PostRequestAsync(url, json: apps); LocalWebRequest.PostRequestAsync(url, json: apps);
+30 -77
View File
@@ -68,6 +68,8 @@ namespace Xylem.Common.Ui.GenesisToolBox
private readonly DataGridViewCellStyle _styleValidated = new DataGridViewCellStyle(); private readonly DataGridViewCellStyle _styleValidated = new DataGridViewCellStyle();
private readonly DataGridViewCellStyle _styleVerificationRequired = new DataGridViewCellStyle(); private readonly DataGridViewCellStyle _styleVerificationRequired = new DataGridViewCellStyle();
private readonly DataGridViewCellStyle _styleEraseRequired = new DataGridViewCellStyle(); private readonly DataGridViewCellStyle _styleEraseRequired = new DataGridViewCellStyle();
private readonly DataGridViewCellStyle _styleCommunicationError = new DataGridViewCellStyle();
private Boolean _updateGui = true; private Boolean _updateGui = true;
private MeterFwUpdate _meterFwUpdate; private MeterFwUpdate _meterFwUpdate;
private MeterResetPsu _meterResetPsu; private MeterResetPsu _meterResetPsu;
@@ -186,8 +188,8 @@ namespace Xylem.Common.Ui.GenesisToolBox
_styleNotInstalled.BackColor = Color.LightGray; _styleNotInstalled.BackColor = Color.LightGray;
_styleNotInstalled.ForeColor = Color.Black; _styleNotInstalled.ForeColor = Color.Black;
_styleInvalidMeterCrc.BackColor = Color.White; _styleCommunicationError.BackColor = Color.LightPink;
_styleInvalidMeterCrc.ForeColor = Color.Purple; _styleCommunicationError.ForeColor = Color.Red;
_styleUpdateRequired.BackColor = Color.White; _styleUpdateRequired.BackColor = Color.White;
_styleUpdateRequired.ForeColor = Color.Red; _styleUpdateRequired.ForeColor = Color.Red;
@@ -352,24 +354,17 @@ namespace Xylem.Common.Ui.GenesisToolBox
/// </summary> /// </summary>
private void UpdateInformationStyleSet() private void UpdateInformationStyleSet()
{ {
if (_meterFwUpdate == null)
return;
foreach (DataGridViewRow dataGridRow in gridViewApplic.Rows) foreach (DataGridViewRow dataGridRow in gridViewApplic.Rows)
{ {
var testString = dataGridRow.Cells[StrStatus].Value.ToString(); var testString = dataGridRow.Cells[StrStatus].Value.ToString();
//var meterAppState = MeterAppState.MeterAppNotInstalled;
var meterAppStateInfo = new MeterAppStateInfo(); var meterAppStateInfo = new MeterAppStateInfo();
//if (testString == "" && dataGridRow.Cells[StrMeterVersion].Value.ToString() == "")
//{
// //dataGridRow.Cells[StrStatus].Value = meterAppStateInfo.GetTextFromState(meterAppState);
// //dataGridRow.Cells[StrStatus].Value = MeterAppStateInfo.GetTextFromState(meterAppState);
//}
var meterAppState = meterAppStateInfo.GetStateFromText(testString); var meterAppState = meterAppStateInfo.GetStateFromText(testString);
//meterAppState = MeterAppStateInfo.GetStateFromText(testString);
switch (meterAppState) switch (meterAppState)
{ {
case MeterAppState.MeterAppInstalledUnchecked:
dataGridRow.DefaultCellStyle = _styleInstalled;
break;
case MeterAppState.MeterAppUpToDate: case MeterAppState.MeterAppUpToDate:
dataGridRow.DefaultCellStyle = _styleValidated; dataGridRow.DefaultCellStyle = _styleValidated;
break; break;
@@ -377,14 +372,20 @@ namespace Xylem.Common.Ui.GenesisToolBox
dataGridRow.DefaultCellStyle = _styleUpdateRequired; dataGridRow.DefaultCellStyle = _styleUpdateRequired;
break; break;
case MeterAppState.FileAppInvalid: case MeterAppState.FileAppInvalid:
dataGridRow.DefaultCellStyle = _styleDownloadOngoing; dataGridRow.DefaultCellStyle = _styleNotInstalled;
break; break;
case MeterAppState.MeterAppVersionOutdated: case MeterAppState.MeterAppVersionOutdated:
dataGridRow.DefaultCellStyle = _styleUpdateRequired; dataGridRow.DefaultCellStyle = _styleUpdateRequired;
break; break;
case MeterAppState.Unknown:
dataGridRow.DefaultCellStyle = _styleCommunicationError;
break;
case MeterAppState.MeterAppNotInstalled: case MeterAppState.MeterAppNotInstalled:
dataGridRow.DefaultCellStyle = _styleNotInstalled; dataGridRow.DefaultCellStyle = _styleNotInstalled;
break; break;
case MeterAppState.MeterAppNotRequired:
dataGridRow.DefaultCellStyle = _styleNotInstalled;
break;
case MeterAppState.InvalidCrc: case MeterAppState.InvalidCrc:
dataGridRow.DefaultCellStyle = _styleInvalidMeterCrc; dataGridRow.DefaultCellStyle = _styleInvalidMeterCrc;
break; break;
@@ -414,62 +415,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
break; break;
} }
} }
//foreach (DataGridViewRow dataGridRow in gridViewApplic.Rows) }
//{
// var testString = dataGridRow.Cells[StrStatus].Value.ToString();
// if (testString == "" && dataGridRow.Cells[StrMeterVersion].Value.ToString() == "")
// {
// dataGridRow.Cells[StrStatus].Value = MeterFwUpdate.StrMeterAppNotInstalled;
// testString = MeterFwUpdate.StrMeterAppNotInstalled;
// }
// switch (testString)
// {
// case MeterFwUpdate.StrMeterAppUpToDate:
// dataGridRow.DefaultCellStyle = _styleValidated;
// break;
// case MeterFwUpdate.StrMeterAppInstallationRequired:
// dataGridRow.DefaultCellStyle = _styleUpdateRequired;
// break;
// case MeterFwUpdate.StrFileAppInvalid:
// dataGridRow.DefaultCellStyle = _styleDownloadOngoing;
// break;
// case MeterFwUpdate.StrMeterAppVersionOutdated:
// dataGridRow.DefaultCellStyle = _styleUpdateRequired;
// break;
// case MeterFwUpdate.StrMeterAppNotInstalled:
// dataGridRow.DefaultCellStyle = _styleNotInstalled;
// break;
// case MeterFwUpdate.StrInvalidCrc:
// dataGridRow.DefaultCellStyle = _styleInvalidMeterCrc;
// break;
// case MeterFwUpdate.StrMeterAppErasureRequired:
// dataGridRow.DefaultCellStyle = _styleEraseRequired;
// break;
// case MeterFwUpdate.StrMeterAppDownloadSucceeded:
// dataGridRow.DefaultCellStyle = _styleDownloadSucceeded;
// break;
// case MeterFwUpdate.StrMeterAppDownloadSuspicious:
// dataGridRow.DefaultCellStyle = _styleVerificationRequired;
// break;
// case MeterFwUpdate.StrMeterAppSuccessfulErased:
// dataGridRow.DefaultCellStyle = _styleDownloadSucceeded;
// break;
// case MeterFwUpdate.StrMeterAppSuccessfulUpdated:
// dataGridRow.DefaultCellStyle = _styleDownloadSucceeded;
// break;
// case MeterFwUpdate.StrMeterAppDownloadFailed:
// dataGridRow.DefaultCellStyle = _styleDownloadFailed;
// break;
// case MeterFwUpdate.StrMeterAppDownloadActive:
// dataGridRow.DefaultCellStyle = _styleDownloadOngoing;
// break;
// default:
// dataGridRow.DefaultCellStyle = _styleInstalled;
// break;
// }
//}
}
/// <summary> /// <summary>
/// After changing the grid view cell and data row cell contents, the meter application lists /// After changing the grid view cell and data row cell contents, the meter application lists
@@ -722,10 +668,9 @@ namespace Xylem.Common.Ui.GenesisToolBox
Invoke(new Action(() => Invoke(new Action(() =>
{ {
lblConnectPcb.Text = StrPartPcbConnected + _currentGenesis.PcbId; lblConnectPcb.Text = StrPartPcbConnected + _currentGenesis.PcbId;
lblCoreRevision.Text = StrCoreRevision + lblCoreRevision.Text = StrCoreRevision + _currentGenesis.StrCoreRevision;
GenesisMeter.BuildFwVersionString(_currentGenesis.CoreRevision);
lblConnectPcb.ForeColor = Color.Green; lblConnectPcb.ForeColor = Color.Green;
_meterFwUpdate?.CompareAllMeterAndFileApps(); _meterFwUpdate?.CompareAllMeterAndFileApps(true);
FillDataGridWithAllInfos(); FillDataGridWithAllInfos();
CheckUpdateEnabled(); CheckUpdateEnabled();
_currentGenesis.Logout(); _currentGenesis.Logout();
@@ -819,6 +764,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
Invoke(new Action(() => Invoke(new Action(() =>
{ {
ProcessViewControl(false); ProcessViewControl(false);
_meterFwUpdate?.CompareAllMeterAndFileApps();
FillDataGridWithAllInfos(); FillDataGridWithAllInfos();
SetControlsDownloadIsFinished(); SetControlsDownloadIsFinished();
@@ -941,6 +887,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
Invoke(new Action(() => Invoke(new Action(() =>
{ {
ProcessViewControl(false); ProcessViewControl(false);
_meterFwUpdate?.CompareAllMeterAndFileApps();
FillDataGridWithAllInfos(); FillDataGridWithAllInfos();
SetControlsDownloadIsFinished(); SetControlsDownloadIsFinished();
@@ -1000,6 +947,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
Invoke(new Action(() => Invoke(new Action(() =>
{ {
ProcessViewControl(false); ProcessViewControl(false);
_meterFwUpdate?.CompareAllMeterAndFileApps();
FillDataGridWithAllInfos(); FillDataGridWithAllInfos();
SetControlsDownloadIsFinished(); SetControlsDownloadIsFinished();
@@ -1040,6 +988,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
Invoke(new Action(() => Invoke(new Action(() =>
{ {
ProcessViewControl(false); ProcessViewControl(false);
_meterFwUpdate?.CompareAllMeterAndFileApps();
FillDataGridWithAllInfos(); FillDataGridWithAllInfos();
SetControlsDownloadIsFinished(); SetControlsDownloadIsFinished();
@@ -1107,9 +1056,13 @@ namespace Xylem.Common.Ui.GenesisToolBox
//this check has been placed here to force display update //this check has been placed here to force display update
if (_meterFwUpdate != null && _currentGenesis != null && if (_meterFwUpdate != null && _currentGenesis != null &&
// avoid activation on invalidated update files
_packageFileToFileAppsValidated && _packageFileToFileAppsValidated &&
(_currentGenesis.MeterAppListVersion.Any(f => f.Update) // avoid activation on unknown app installation status due to communication error
|| _currentGenesis.MeterAppListVersion.Any(f => f.Erase))) _currentGenesis.MeterAppListVersion.All( f => f.Status != MeterAppState.Unknown) &&
// check if anything has to be updated or erased
(_currentGenesis.MeterAppListVersion.Any(f => f.Update) ||
_currentGenesis.MeterAppListVersion.Any(f => f.Erase)))
{ {
SetControlDownloadsUnlocked(); SetControlDownloadsUnlocked();
return true; return true;
@@ -1691,8 +1644,8 @@ namespace Xylem.Common.Ui.GenesisToolBox
return false; return false;
} }
_meterFwUpdate?.CompareAllMeterAndFileApps();
_meterFwUpdate?.AssignGenesis(_currentGenesis); _meterFwUpdate?.AssignGenesis(_currentGenesis);
_meterFwUpdate?.CompareAllMeterAndFileApps();
FillDataGridWithAllInfos(); FillDataGridWithAllInfos();
@@ -1848,8 +1801,8 @@ namespace Xylem.Common.Ui.GenesisToolBox
return; return;
} }
_meterFwUpdate?.CompareAllMeterAndFileApps();
_meterFwUpdate?.AssignGenesis(_currentGenesis); _meterFwUpdate?.AssignGenesis(_currentGenesis);
_meterFwUpdate?.CompareAllMeterAndFileApps();
FillDataGridWithAllInfos(); FillDataGridWithAllInfos();
CheckUpdateEnabled(); CheckUpdateEnabled();
_resetTimeMeasurement = true; _resetTimeMeasurement = true;
+15 -9
View File
@@ -12,6 +12,7 @@ using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Const;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus;
@@ -167,6 +168,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
btnEraseFile.Enabled = false; btnEraseFile.Enabled = false;
tbxFileToEraseName.Enabled = false; tbxFileToEraseName.Enabled = false;
tbxFileToEraseDrive.Enabled = false; tbxFileToEraseDrive.Enabled = false;
btnUploadPWFile.Enabled = false;
} }
/// <summary> /// <summary>
@@ -189,6 +191,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
btnEraseFile.Enabled = true; btnEraseFile.Enabled = true;
tbxFileToEraseName.Enabled = true; tbxFileToEraseName.Enabled = true;
tbxFileToEraseDrive.Enabled = true; tbxFileToEraseDrive.Enabled = true;
btnUploadPWFile.Enabled = true;
} }
/// <summary> /// <summary>
@@ -517,7 +520,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
LogText(StrSeparator); LogText(StrSeparator);
LogText($"PCB ID: {_currentGenesis.PcbId}"); LogText($"PCB ID: {_currentGenesis.PcbId}");
LogText($"Core Version: {GenesisMeter.BuildFwVersionString(_currentGenesis.CoreRevision)}"); LogText($"Core Version: {_currentGenesis.StrCoreRevision}");
LogText(""); LogText("");
LogText("Installed Applications:"); LogText("Installed Applications:");
@@ -525,6 +528,9 @@ namespace Xylem.Common.Ui.GenesisToolBox
{ {
var versionString = var versionString =
app.IsInstalled ? $"V: {app.StrVersion} - CRC: 0x{app.Crc:X4}" : "App NOT Installed"; 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}"); LogText($"AppId: 0x{app.AppId:X2} - {versionString} - " + $"AppName: {app.AppName}");
if (app.IsInstalled) if (app.IsInstalled)
@@ -559,8 +565,8 @@ namespace Xylem.Common.Ui.GenesisToolBox
_currentGenesis.ReLogin(); _currentGenesis.ReLogin();
var dt = DateTime.UtcNow; var dt = DateTime.UtcNow;
var msg = $@"{dt:yyyy-MM-dd HH:mm:ss}"; var msg = $@"{dt:yyyy-MM-dd HH:mm:ss} UTC";
LogText($@"PC date time [UTC]: {msg}"); LogText($@"PC date time: {msg}");
CalculateMeterDateTime(RegisterConverter.ByteArrayToValue<Int32>( CalculateMeterDateTime(RegisterConverter.ByteArrayToValue<Int32>(
_currentGenesis.ReadRegister("SYSTEM_CalendarSeconds"))); _currentGenesis.ReadRegister("SYSTEM_CalendarSeconds")));
@@ -585,7 +591,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
var meterDateTime = new TimeT { SecondsSince2000 = secSince2000 }; var meterDateTime = new TimeT { SecondsSince2000 = secSince2000 };
var msg = meterDateTime.ToString(); var msg = meterDateTime.ToString();
Invoke(new Action(() => { tbxDateTime.Text = msg; })); Invoke(new Action(() => { tbxDateTime.Text = msg; }));
LogText($@"Meter date time [UTC]: {msg}"); LogText($@"Meter date time: {msg}");
} }
/// <summary> /// <summary>
@@ -855,10 +861,10 @@ namespace Xylem.Common.Ui.GenesisToolBox
LogText("File is empty", logFileName); LogText("File is empty", logFileName);
} }
foreach (var rawBat in rawDic) //foreach (var rawBat in rawDic)
{ //{
} //}
} }
var sb = new StringBuilder(); var sb = new StringBuilder();
@@ -1466,9 +1472,9 @@ namespace Xylem.Common.Ui.GenesisToolBox
LogText($"Station: {ddlLocation.Items[ddlLocation.SelectedIndex]}", filename); LogText($"Station: {ddlLocation.Items[ddlLocation.SelectedIndex]}", filename);
var dt = DateTime.UtcNow; var dt = DateTime.UtcNow;
msg = $@"{dt:yyyy-MM-dd HH:mm:ss}"; msg = $@"{dt:yyyy-MM-dd HH:mm:ss} UTC";
LogText($@"PC date time [UTC]: {msg}", filename); LogText($@"PC date time: {msg}", filename);
_currentGenesis.ReLogin(); _currentGenesis.ReLogin();
+5 -1
View File
@@ -10,6 +10,7 @@ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using Logic.ProductionToProductMapper.Cordonel; using Logic.ProductionToProductMapper.Cordonel;
using Newtonsoft.Json; using Newtonsoft.Json;
using Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Const;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore; using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
@@ -390,7 +391,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
return; return;
LogText(StrSeparator); LogText(StrSeparator);
LogText($"PCB ID: {_currentGenesis.PcbId}"); LogText($"PCB ID: {_currentGenesis.PcbId}");
LogText($"Core Version: {GenesisMeter.BuildFwVersionString(_currentGenesis.CoreRevision)}"); LogText($"Core Version: {_currentGenesis.StrCoreRevision}");
LogText(""); LogText("");
LogText("Installed Applications:"); LogText("Installed Applications:");
@@ -398,6 +399,9 @@ namespace Xylem.Common.Ui.GenesisToolBox
{ {
var versionString = app.IsInstalled ? $"V: {app.StrVersion} - CRC: 0x{app.Crc:X4}" : var versionString = app.IsInstalled ? $"V: {app.StrVersion} - CRC: 0x{app.Crc:X4}" :
"App NOT Installed"; "App NOT Installed";
if (app.Status == MeterAppState.Unknown)
versionString = "COMMUNICATION ERROR";
LogText($"AppId: 0x{app.AppId:X2} - {versionString} - " + $"AppName: {app.AppName}"); LogText($"AppId: 0x{app.AppId:X2} - {versionString} - " + $"AppName: {app.AppName}");
if (app.IsInstalled) if (app.IsInstalled)
+48 -47
View File
@@ -33,11 +33,12 @@ namespace Xylem.Common.Ui.GenesisToolBox
this.components = new System.ComponentModel.Container(); this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components); this.timer1 = new System.Windows.Forms.Timer(this.components);
this.timer2 = new System.Windows.Forms.Timer(this.components); this.timer2 = new System.Windows.Forms.Timer(this.components);
this.automaticCalibrationTabControl = new System.Windows.Forms.TabControl(); this.multiflancshCalibration = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage(); this.tabPage1 = new System.Windows.Forms.TabPage();
this.btnRefreshLut = new System.Windows.Forms.Button(); this.btnRefreshLut = new System.Windows.Forms.Button();
this.txtLuts = new System.Windows.Forms.TextBox(); this.txtLuts = new System.Windows.Forms.TextBox();
this.tabPage2 = new System.Windows.Forms.TabPage(); this.tabPage2 = new System.Windows.Forms.TabPage();
this.txtComport = new System.Windows.Forms.TextBox();
this.lblCheck = new System.Windows.Forms.Label(); this.lblCheck = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label();
this.btnCheck = new System.Windows.Forms.Button(); this.btnCheck = new System.Windows.Forms.Button();
@@ -58,6 +59,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
this.automaticContentBox = new System.Windows.Forms.RichTextBox(); this.automaticContentBox = new System.Windows.Forms.RichTextBox();
this.autometicControlsSplitter = new System.Windows.Forms.Splitter(); this.autometicControlsSplitter = new System.Windows.Forms.Splitter();
this.automaticControlsPanel = new System.Windows.Forms.Panel(); this.automaticControlsPanel = new System.Windows.Forms.Panel();
this.connectedMeters = new System.Windows.Forms.ListView();
this.saveSettingsBtn = new System.Windows.Forms.Button(); this.saveSettingsBtn = new System.Windows.Forms.Button();
this.messurementDauerMS = new System.Windows.Forms.TextBox(); this.messurementDauerMS = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label();
@@ -67,11 +69,9 @@ namespace Xylem.Common.Ui.GenesisToolBox
this.label2 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label();
this.GMHPort = new System.Windows.Forms.TextBox(); this.GMHPort = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label();
this.tabPage4 = new System.Windows.Forms.TabPage();
this.timer3 = new System.Windows.Forms.Timer(this.components); this.timer3 = new System.Windows.Forms.Timer(this.components);
this.mainMenuStrip = new System.Windows.Forms.MenuStrip(); this.mainMenuStrip = new System.Windows.Forms.MenuStrip();
this.txtComport = new System.Windows.Forms.TextBox(); this.multiflancshCalibration.SuspendLayout();
this.automaticCalibrationTabControl.SuspendLayout();
this.tabPage1.SuspendLayout(); this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout(); this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout(); this.tabPage3.SuspendLayout();
@@ -89,23 +89,22 @@ namespace Xylem.Common.Ui.GenesisToolBox
// //
this.timer2.Tick += new System.EventHandler(this.timer2_Tick); this.timer2.Tick += new System.EventHandler(this.timer2_Tick);
// //
// automaticCalibrationTabControl // multiflancshCalibration
// //
this.automaticCalibrationTabControl.Controls.Add(this.tabPage1); this.multiflancshCalibration.Controls.Add(this.tabPage1);
this.automaticCalibrationTabControl.Controls.Add(this.tabPage2); this.multiflancshCalibration.Controls.Add(this.tabPage2);
this.automaticCalibrationTabControl.Controls.Add(this.tabPage3); this.multiflancshCalibration.Controls.Add(this.tabPage3);
this.automaticCalibrationTabControl.Controls.Add(this.AutomaticCalibrationTab); this.multiflancshCalibration.Controls.Add(this.AutomaticCalibrationTab);
this.automaticCalibrationTabControl.Controls.Add(this.tabPage4); this.multiflancshCalibration.Dock = System.Windows.Forms.DockStyle.Fill;
this.automaticCalibrationTabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.multiflancshCalibration.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.automaticCalibrationTabControl.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.multiflancshCalibration.Location = new System.Drawing.Point(0, 24);
this.automaticCalibrationTabControl.Location = new System.Drawing.Point(0, 24); this.multiflancshCalibration.Margin = new System.Windows.Forms.Padding(0);
this.automaticCalibrationTabControl.Margin = new System.Windows.Forms.Padding(0); this.multiflancshCalibration.Name = "multiflancshCalibration";
this.automaticCalibrationTabControl.Name = "automaticCalibrationTabControl"; this.multiflancshCalibration.Padding = new System.Drawing.Point(0, 0);
this.automaticCalibrationTabControl.Padding = new System.Drawing.Point(0, 0); this.multiflancshCalibration.SelectedIndex = 0;
this.automaticCalibrationTabControl.SelectedIndex = 0; this.multiflancshCalibration.Size = new System.Drawing.Size(1225, 676);
this.automaticCalibrationTabControl.Size = new System.Drawing.Size(1225, 676); this.multiflancshCalibration.TabIndex = 55;
this.automaticCalibrationTabControl.TabIndex = 55; this.multiflancshCalibration.Tag = "";
this.automaticCalibrationTabControl.Tag = "";
// //
// tabPage1 // tabPage1
// //
@@ -151,6 +150,19 @@ namespace Xylem.Common.Ui.GenesisToolBox
this.tabPage2.Text = "Manual check temp"; this.tabPage2.Text = "Manual check temp";
this.tabPage2.UseVisualStyleBackColor = true; this.tabPage2.UseVisualStyleBackColor = true;
// //
// txtComport
//
this.txtComport.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtComport.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtComport.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtComport.Location = new System.Drawing.Point(77, 24);
this.txtComport.Margin = new System.Windows.Forms.Padding(0);
this.txtComport.MinimumSize = new System.Drawing.Size(2, 25);
this.txtComport.Name = "txtComport";
this.txtComport.Size = new System.Drawing.Size(318, 24);
this.txtComport.TabIndex = 55;
//
// lblCheck // lblCheck
// //
this.lblCheck.AutoSize = true; this.lblCheck.AutoSize = true;
@@ -363,6 +375,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
// automaticControlsPanel // automaticControlsPanel
// //
this.automaticControlsPanel.BackColor = System.Drawing.SystemColors.Menu; this.automaticControlsPanel.BackColor = System.Drawing.SystemColors.Menu;
this.automaticControlsPanel.Controls.Add(this.connectedMeters);
this.automaticControlsPanel.Controls.Add(this.saveSettingsBtn); this.automaticControlsPanel.Controls.Add(this.saveSettingsBtn);
this.automaticControlsPanel.Controls.Add(this.messurementDauerMS); this.automaticControlsPanel.Controls.Add(this.messurementDauerMS);
this.automaticControlsPanel.Controls.Add(this.label3); this.automaticControlsPanel.Controls.Add(this.label3);
@@ -379,6 +392,17 @@ namespace Xylem.Common.Ui.GenesisToolBox
this.automaticControlsPanel.Size = new System.Drawing.Size(328, 647); this.automaticControlsPanel.Size = new System.Drawing.Size(328, 647);
this.automaticControlsPanel.TabIndex = 0; this.automaticControlsPanel.TabIndex = 0;
// //
// connectedMeters
//
this.connectedMeters.HideSelection = false;
this.connectedMeters.Location = new System.Drawing.Point(5, 285);
this.connectedMeters.MultiSelect = false;
this.connectedMeters.Name = "connectedMeters";
this.connectedMeters.Size = new System.Drawing.Size(318, 356);
this.connectedMeters.TabIndex = 17;
this.connectedMeters.UseCompatibleStateImageBehavior = false;
this.connectedMeters.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.MeterSelected);
//
// saveSettingsBtn // saveSettingsBtn
// //
this.saveSettingsBtn.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) this.saveSettingsBtn.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
@@ -500,16 +524,6 @@ namespace Xylem.Common.Ui.GenesisToolBox
this.label1.Text = "Messgerät (COM port)"; this.label1.Text = "Messgerät (COM port)";
this.label1.TextAlign = System.Drawing.ContentAlignment.BottomLeft; this.label1.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
// //
// tabPage4
//
this.tabPage4.Location = new System.Drawing.Point(4, 25);
this.tabPage4.Name = "tabPage4";
this.tabPage4.Padding = new System.Windows.Forms.Padding(3);
this.tabPage4.Size = new System.Drawing.Size(1217, 647);
this.tabPage4.TabIndex = 4;
this.tabPage4.Text = "tabPage4";
this.tabPage4.UseVisualStyleBackColor = true;
//
// timer3 // timer3
// //
this.timer3.Interval = 10000; this.timer3.Interval = 10000;
@@ -524,30 +538,17 @@ namespace Xylem.Common.Ui.GenesisToolBox
this.mainMenuStrip.TabIndex = 57; this.mainMenuStrip.TabIndex = 57;
this.mainMenuStrip.Text = "menuStrip1"; this.mainMenuStrip.Text = "menuStrip1";
// //
// txtComport
//
this.txtComport.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtComport.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtComport.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtComport.Location = new System.Drawing.Point(77, 24);
this.txtComport.Margin = new System.Windows.Forms.Padding(0);
this.txtComport.MinimumSize = new System.Drawing.Size(2, 25);
this.txtComport.Name = "txtComport";
this.txtComport.Size = new System.Drawing.Size(318, 25);
this.txtComport.TabIndex = 55;
//
// FrmTempMeter // FrmTempMeter
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1225, 700); this.ClientSize = new System.Drawing.Size(1225, 700);
this.Controls.Add(this.automaticCalibrationTabControl); this.Controls.Add(this.multiflancshCalibration);
this.Controls.Add(this.mainMenuStrip); this.Controls.Add(this.mainMenuStrip);
this.MainMenuStrip = this.mainMenuStrip; this.MainMenuStrip = this.mainMenuStrip;
this.Name = "FrmTempMeter"; this.Name = "FrmTempMeter";
this.Text = "FrmTempMeter"; this.Text = "FrmTempMeter";
this.automaticCalibrationTabControl.ResumeLayout(false); this.multiflancshCalibration.ResumeLayout(false);
this.tabPage1.ResumeLayout(false); this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout(); this.tabPage1.PerformLayout();
this.tabPage2.ResumeLayout(false); this.tabPage2.ResumeLayout(false);
@@ -566,7 +567,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
#endregion #endregion
private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Timer timer2; private System.Windows.Forms.Timer timer2;
private System.Windows.Forms.TabControl automaticCalibrationTabControl; private System.Windows.Forms.TabControl multiflancshCalibration;
private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.Button btnRefreshLut; private System.Windows.Forms.Button btnRefreshLut;
private System.Windows.Forms.TextBox txtLuts; private System.Windows.Forms.TextBox txtLuts;
@@ -602,7 +603,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
private System.Windows.Forms.TextBox messurementDauerMS; private System.Windows.Forms.TextBox messurementDauerMS;
private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button saveSettingsBtn; private System.Windows.Forms.Button saveSettingsBtn;
private System.Windows.Forms.TabPage tabPage4;
private System.Windows.Forms.TextBox txtComport; private System.Windows.Forms.TextBox txtComport;
private System.Windows.Forms.ListView connectedMeters;
} }
} }
+159 -115
View File
@@ -47,6 +47,7 @@
this.InitializeComponent(); this.InitializeComponent();
this.InitializeContent(); this.InitializeContent();
this.meterBatch = new MeterBatch();
this.reftempRangeReq = new List<RefTempRange>() this.reftempRangeReq = new List<RefTempRange>()
{ {
new RefTempRange() { Min = 7, Max= 9 }, new RefTempRange() { Min = 7, Max= 9 },
@@ -61,70 +62,64 @@
}; };
} }
private void BtnConnect_Click(Object sender, EventArgs e) private void BtnConnect_Click(Object sender, EventArgs e)
{ => this.Connect();
this.Connect();
}
private void Connect() private void Connect()
{ {
try try
{ {
if (!int.TryParse($"{this.slotsList.SelectedItem}", out var slotNr)) if (int.TryParse($"{this.slotsList.SelectedItem}", out var slotNr))
{ {
return; var meter = new ZeroFlowGenesisMeter(slotNr, 3, false);
this.meterBatch.AddMeter(meter);
Task.Factory.StartNew(() =>
{
meter.Login();
if (!meter.IsLoggedOn)
{
Thread.Sleep(2000);
meter.Login();
}
if (!meter.IsLoggedOn)
{
SetEnabled(ProgrammState.Start);
return;
}
this.currentGenesis = meter;
meter.InitMeasurement();
meter.WriteRegister(Register.Genesisflow.SampleRate, (byte)10, checkRegister: true);
meter.WriteRegister("GENESISFLOW_MaxValidDeltaToF", 4294967295, checkRegister: true);
meter.WriteRegister("GENESISFLOW_MaxValidToF", 4294967295, checkRegister: true);
meter.WriteRegister("GENESISFLOW_MinValidToF", (uint)0, checkRegister: true);
meter.StartMeasurement();
InvokeOnUIThread(new Action(() =>
{
txtLuts.Text = GetLutsText(meter.PcbId);
if (lutIsMissing)
{
txtLuts.BackColor = Color.IndianRed;
}
else
{
txtLuts.BackColor = Color.LightGreen;
}
this.pcbidTextBox.Text = meter.PcbId;
this.SetEnabled(ProgrammState.Connected);
this.UpdateConnectedMetersList();
}));
});
} }
//var drive = 1;
currentGenesis?.DisposeMeter();
//dispose old meter
meterBatch = new MeterBatch();
currentGenesis = null;
Thread.Sleep(200);
//assign new meter and assign meter to FW update file if this exists
currentGenesis = new ZeroFlowGenesisMeter(slotNr, 3, false);
//_currentGenesis.SetupFromConfigFile(slotNr);
meterBatch.AddMeter(currentGenesis);
Task.Factory.StartNew(() =>
{
meterBatch.MetersLogin();
if (!currentGenesis.IsLoggedOn)
{
Thread.Sleep(2000);
meterBatch.MetersLogin();
}
if (!currentGenesis.IsLoggedOn)
{
SetEnabled(ProgrammState.Start);
return;
}
var a = GetLutsText(currentGenesis.PcbId);
currentGenesis.InitMeasurement();
InvokeOnUIThread(new Action(() =>
{
txtLuts.Text = a;
if (lutIsMissing)
{
txtLuts.BackColor = Color.IndianRed;
}
else
{
txtLuts.BackColor = Color.LightGreen;
}
this.pcbidTextBox.Text = currentGenesis.PcbId;
this.SetEnabled(ProgrammState.Connected);
}));
});
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -134,6 +129,30 @@
} }
} }
private void UpdateConnectedMetersList()
{
this.InvokeOnUIThread(() =>
{
this.connectedMeters.Clear();
foreach (var meter in this.meterBatch.ListOfMeters)
{
if (meter is ZeroFlowGenesisMeter gns)
{
var pcbId = gns.PcbId;
var connected = !string.IsNullOrWhiteSpace(pcbId);
var item = new ListViewItem
{
BackColor = connected ? Color.LightGreen : Color.IndianRed,
Text = pcbId,
};
this.connectedMeters.Items.Add(item);
}
}
});
}
private void btnRefreshLut_Click(Object sender, EventArgs e) private void btnRefreshLut_Click(Object sender, EventArgs e)
{ {
if (!string.IsNullOrEmpty(currentGenesis?.PcbId)) if (!string.IsNullOrEmpty(currentGenesis?.PcbId))
@@ -242,10 +261,7 @@
} }
currentGenesis.StartRecordData(); currentGenesis.StartRecordData();
timer1.Enabled = true; timer1.Enabled = true;
@@ -624,7 +640,8 @@
TextAlign = ContentAlignment.MiddleCenter, TextAlign = ContentAlignment.MiddleCenter,
Margin = new Padding(10, 0, 0, 0), Margin = new Padding(10, 0, 0, 0),
Padding = new Padding(10, 0, 10, 0), Padding = new Padding(10, 0, 10, 0),
BackColor = Color.LightGray BackColor = Color.LightGray,
Visible = true
}; };
this.connectBtn.Click += this.BtnConnect_Click; this.connectBtn.Click += this.BtnConnect_Click;
@@ -636,7 +653,8 @@
TextAlign = ContentAlignment.MiddleCenter, TextAlign = ContentAlignment.MiddleCenter,
Margin = new Padding(10, 0, 0, 0), Margin = new Padding(10, 0, 0, 0),
Padding = new Padding(10, 0, 10, 0), Padding = new Padding(10, 0, 10, 0),
BackColor = Color.LightGray BackColor = Color.LightGray,
Visible = true
}; };
this.disconnectBtn.Click += this.BtnDisconnect_Click; this.disconnectBtn.Click += this.BtnDisconnect_Click;
@@ -660,7 +678,7 @@
this.mainMenuStrip.Items.Add(this.disconnectBtn); this.mainMenuStrip.Items.Add(this.disconnectBtn);
this.mainMenuStrip.Items.Add(this.testBtn); this.mainMenuStrip.Items.Add(this.testBtn);
this.automaticCalibrationTabControl.GotFocus += (Object sender, EventArgs e) => this.multiflancshCalibration.GotFocus += (Object sender, EventArgs e) =>
{ {
this.GMHPort.Text = Appsettings.GMHPort.ToString(); this.GMHPort.Text = Appsettings.GMHPort.ToString();
this.messurementStepMS.Text = Appsettings.MessurementStep.ToString(); this.messurementStepMS.Text = Appsettings.MessurementStep.ToString();
@@ -674,7 +692,7 @@
{ {
try try
{ {
this.currentGenesis.DisposeMeter(); this.currentGenesis.Dispose();
} }
catch (Exception e) catch (Exception e)
{ {
@@ -682,16 +700,17 @@
} }
finally finally
{ {
this.currentGenesis = null; this.meterBatch.RemoveMeter(this.currentGenesis);
} }
this.InvokeOnUIThread(new Action(() => this.InvokeOnUIThread(new Action(() =>
{ {
this.currentGenesis = null;
this.txtLuts.Text = string.Empty; this.txtLuts.Text = string.Empty;
this.txtLuts.BackColor = Color.White; this.txtLuts.BackColor = Color.White;
this.pcbidTextBox.Text = "not connected"; this.pcbidTextBox.Text = "not connected";
this.SetEnabled(ProgrammState.Start); this.SetEnabled(ProgrammState.Start);
this.UpdateConnectedMetersList();
})); }));
} }
@@ -707,8 +726,6 @@
this.btnAddLut.Enabled = false; this.btnAddLut.Enabled = false;
this.nudRef.Visible = false; this.nudRef.Visible = false;
this.btnRefreshLut.Enabled = false; this.btnRefreshLut.Enabled = false;
this.disconnectBtn.Visible = false;
this.connectBtn.Visible = true;
break; break;
case ProgrammState.Connected: case ProgrammState.Connected:
this.btnStartRecord.Enabled = true; this.btnStartRecord.Enabled = true;
@@ -716,8 +733,6 @@
this.btnAddLut.Enabled = false; this.btnAddLut.Enabled = false;
this.nudRef.Visible = false; this.nudRef.Visible = false;
this.btnRefreshLut.Enabled = true; this.btnRefreshLut.Enabled = true;
this.disconnectBtn.Visible = true;
this.connectBtn.Visible = false;
break; break;
case ProgrammState.RecordRuning: case ProgrammState.RecordRuning:
this.btnStartRecord.Enabled = false; this.btnStartRecord.Enabled = false;
@@ -746,26 +761,18 @@
private void StartAutomaticBtn_Clicked(object sender, EventArgs args) private void StartAutomaticBtn_Clicked(object sender, EventArgs args)
{ {
if (this.currentGenesis is null) if (this.connectedMeters.Items.Count == 0)
{ {
MessageBox.Show(this, "Water meter not connected!", "Start aborted", MessageBoxButtons.OK); MessageBox.Show(this, "There is no meter not connected!", "Start aborted", MessageBoxButtons.OK);
return; return;
} }
try try
{ {
this.currentGenesis?.WriteRegister(Register.Genesisflow.SampleRate, (byte)16, checkRegister: true);
this.currentGenesis?.WriteRegister("GENESISFLOW_MaxValidDeltaToF", 4294967295, checkRegister: true);
this.currentGenesis?.WriteRegister("GENESISFLOW_MaxValidToF", 4294967295, checkRegister: true);
this.currentGenesis?.WriteRegister("GENESISFLOW_MinValidToF", (uint)0, checkRegister: true);
this.automatic = true; this.automatic = true;
this.start = DateTimeOffset.Now; this.start = DateTimeOffset.Now;
this.automaticCalibration = new AutomaticTemperatureCalibration(this);
var pcbid = this.currentGenesis?.PcbId ?? "0000000000";
this.automaticCalibration = new AutomaticTemperatureCalibration(pcbid, this);
this.automaticCalibration.StartMessuring(); this.automaticCalibration.StartMessuring();
this.SetEnabled(ProgrammState.RecordRuning); this.SetEnabled(ProgrammState.RecordRuning);
@@ -784,10 +791,12 @@
{ {
this.automatic = false; this.automatic = false;
this.automaticCalibration.StopMessuring();
this.MergeToAutoFile(); this.MergeToAutoFile();
this.automaticCalibration.StopMessuring();
this.meterBatch.Dispose();
this.meterBatch.RemoveAllMeters();
this.SetEnabled(ProgrammState.RecordStoped); this.SetEnabled(ProgrammState.RecordStoped);
this.startAutomaticBtn.Enabled = true; this.startAutomaticBtn.Enabled = true;
@@ -801,13 +810,12 @@
public void StartRecording() public void StartRecording()
{ {
try foreach (var meter in this.meterBatch.ListOfMeters)
{ {
this.currentGenesis.StartRecordData(); if (meter is ZeroFlowGenesisMeter zfgnsm)
} {
catch (Exception e) zfgnsm.StartRecordData();
{ }
this.AddMessage($"{e}");
} }
} }
@@ -820,7 +828,7 @@
try try
{ {
var text = $"{message}{Environment.NewLine}" + this.automaticContentBox.Text; var text = $"{message}{Environment.NewLine}" + this.automaticContentBox.Text;
text = text.Substring(0, Math.Min(5000, text?.Length ?? 0)); text = text.Substring(0, Math.Min(2000, text?.Length ?? 0));
this.automaticContentBox.ResetText(); this.automaticContentBox.ResetText();
this.automaticContentBox.AppendText(text); this.automaticContentBox.AppendText(text);
@@ -840,6 +848,7 @@
if (this.automaticCalibration != null) if (this.automaticCalibration != null)
{ {
this.automaticCalibration.StopMessuring(); this.automaticCalibration.StopMessuring();
this.meterBatch.Dispose();
} }
try try
@@ -854,30 +863,6 @@
base.OnClosed(args); base.OnClosed(args);
} }
public Double GetAverageTOF()
{
try
{
if (this.currentGenesis is null)
{
this.automaticCalibration.StopMessuring();
return double.MinValue;
}
return this.currentGenesis
.CurrentRecords
.Where(s => s.Channel == 2)
.Average(x => x.TotalTimeOfFlightS);
}
catch (Exception e)
{
this.AddMessage($"{e}");
return 0;
}
}
protected override void OnFormClosed(FormClosedEventArgs e) protected override void OnFormClosed(FormClosedEventArgs e)
=> this.BtnDisconnect_Click(default(object), EventArgs.Empty); => this.BtnDisconnect_Click(default(object), EventArgs.Empty);
@@ -903,5 +888,64 @@
public void InvokeOnUIThread(Action action) public void InvokeOnUIThread(Action action)
=> this.Invoke(action); => this.Invoke(action);
public IDictionary<String, Double> GetAverageTOFForeachMeter()
{
var results = new Dictionary<string, double>();
foreach (var meter in this.meterBatch.ListOfMeters)
{
if (meter is ZeroFlowGenesisMeter zfgnsm)
{
var avg = default(double);
try
{
avg = zfgnsm
.CurrentRecords
.Where(s => s.Channel == 2)
.Average(x => x.TotalTimeOfFlightS);
}
catch (Exception e)
{
this.AddMessage(e.Message);
}
finally
{
zfgnsm.StartRecordData();
}
var pcbId = zfgnsm.PcbId;
if (string.IsNullOrWhiteSpace(pcbId))
{
pcbId = "---------";
}
results[pcbId] = avg;
}
}
return results;
}
private void MeterSelected(Object sender, ListViewItemSelectionChangedEventArgs e)
{
var pcbId = e?.Item?.Text;
this.InvokeOnUIThread(() =>
{
foreach (var meter in this.meterBatch.ListOfMeters)
{
if (meter is ZeroFlowGenesisMeter zfgnsm && zfgnsm.PcbId == pcbId)
{
this.currentGenesis = zfgnsm;
this.pcbidTextBox.Text = pcbId;
break;
}
}
});
}
} }
} }
+1 -1
View File
@@ -130,6 +130,6 @@
<value>278, 17</value> <value>278, 17</value>
</metadata> </metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>120</value> <value>42</value>
</metadata> </metadata>
</root> </root>
@@ -1,140 +1,103 @@
namespace Xylem.Common.Ui.GenesisToolBox.Infrastructure namespace Xylem.Common.Ui.GenesisToolBox.Infrastructure
{ {
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Timers; using System.Timers;
internal interface ITempMeterForm internal interface ITempMeterForm
{ {
void AddMessage(string message); void AddMessage(string message);
double GetAverageTOF();
void StartRecording(); void StartRecording();
void InvokeOnUIThread(Action action); void InvokeOnUIThread(Action action);
IDictionary<string, double> GetAverageTOFForeachMeter();
} }
partial class AutomaticTemperatureCalibration partial class AutomaticTemperatureCalibration
{ {
private readonly string pcbId;
private readonly ITempMeterForm tempMeterForm; private readonly ITempMeterForm tempMeterForm;
private readonly TemperatureSource temperatureSource; private TemperatureSource temperatureSource;
private readonly string outputFile;
private string messurementsFile; private Timer timer;
private Timer startTimer; private bool hasHeaders;
private Timer resultsTimer;
public AutomaticTemperatureCalibration(string pcbId, ITempMeterForm genesisMeter) public AutomaticTemperatureCalibration(ITempMeterForm tempMeterForm)
{ {
this.pcbId = pcbId; this.tempMeterForm = tempMeterForm;
this.tempMeterForm = genesisMeter; this.outputFile = Path.Combine(Appsettings.WorkingDirectory, $"{DateTime.Now:yyyy_MM_dd}_mesurements.txt");
try Directory.CreateDirectory(Path.GetDirectoryName(this.outputFile));
{ File.AppendAllText(this.outputFile, default(string));
this.temperatureSource = new TemperatureSource();
}
catch (Exception e)
{
this.tempMeterForm.AddMessage($"{e}");
}
} }
public void StartMessuring() public void StartMessuring()
{ {
try this.temperatureSource = new TemperatureSource();
this.tempMeterForm.StartRecording();
this.GetResults(null, null);
this.timer = new Timer()
{ {
this.messurementsFile = Path.Combine(Appsettings.WorkingDirectory, $"{this.pcbId}_{DateTime.Now:yyyyMMddHHmmss}_messurements.txt"); AutoReset = true,
Interval = Appsettings.MessurementStep,
File.AppendAllText(this.messurementsFile, string.Empty); };
this.timer.Elapsed += this.GetResults;
this.resultsTimer = new Timer() this.timer.Start();
{
AutoReset = true,
Interval = Appsettings.MessurementStep,
};
this.resultsTimer.Elapsed += this.StartGettingResults;
this.startTimer = new Timer
{
AutoReset = true,
Interval = Appsettings.MessurementDauer,
};
this.startTimer.Elapsed += this.StartMessuring;
this.StartMessuring(null, null);
this.startTimer.Start();
}
catch (Exception e)
{
File.AppendAllText(this.messurementsFile, $"{e}{Environment.NewLine}");
this.tempMeterForm.AddMessage($"{e}");
}
} }
private void StartMessuring(Object sender, ElapsedEventArgs args) private void GetResults(Object sender, ElapsedEventArgs args)
{ {
try this.tempMeterForm.InvokeOnUIThread(() =>
{ {
if (this.resultsTimer.Enabled) try
{
this.resultsTimer.Stop();
}
else
{
this.tempMeterForm.StartRecording();
this.resultsTimer.Start();
}
}
catch (Exception e)
{
File.AppendAllText(this.messurementsFile, $"{e}{Environment.NewLine}");
this.tempMeterForm.AddMessage($"{e}");
}
}
private void StartGettingResults(Object sender, ElapsedEventArgs args)
{
try
{
this.tempMeterForm.InvokeOnUIThread(() =>
{ {
var temp = this.temperatureSource.GetTemperature(); var temp = this.temperatureSource.GetTemperature();
var avgTOF = this.tempMeterForm.GetAverageTOF(); var results = this.tempMeterForm.GetAverageTOFForeachMeter();
var messurement = $"{this.pcbId};{DateTime.Now:yyyy-MM-dd HH:mm:ss:fff};{temp:0.00};{avgTOF:0.0000000000}";
File.AppendAllText(this.messurementsFile, $"{messurement}{Environment.NewLine}"); if (!this.hasHeaders)
{
File.AppendAllText(this.outputFile, $"Timestamp;°C;{string.Join(";", results.Keys)}{Environment.NewLine}");
this.hasHeaders = true;
}
var messurement = $"{temp:0.00};{string.Join(";", results.Values.Select(x => $"{x:0.0000000000}"))}";
File.AppendAllText(this.outputFile, $"{messurement}{Environment.NewLine}");
this.tempMeterForm.AddMessage(messurement); this.tempMeterForm.AddMessage(messurement);
this.tempMeterForm.StartRecording(); }
}); catch (Exception e)
} {
catch (Exception e) this.tempMeterForm.AddMessage(e.ToString());
{ }
File.AppendAllText(this.messurementsFile, $"{e}{Environment.NewLine}"); });
this.tempMeterForm.AddMessage($"{e}");
}
} }
public void StopMessuring() public void StopMessuring()
{ {
try try
{ {
this.resultsTimer.Stop(); this.timer.Stop();
this.resultsTimer.Dispose(); this.timer.Dispose();
this.resultsTimer = null; this.timer = null;
this.startTimer.Stop();
this.startTimer.Dispose();
this.startTimer = null;
} }
catch (Exception e) catch (Exception e)
{ {
File.AppendAllText(this.messurementsFile, $"{e}{Environment.NewLine}"); this.tempMeterForm.AddMessage($"{e}");
}
try
{
this.temperatureSource.Dispose();
}
catch (Exception e)
{
this.tempMeterForm.AddMessage($"{e}"); this.tempMeterForm.AddMessage($"{e}");
} }
} }
@@ -14,10 +14,10 @@
[DllImport("GMH3x32E.dll")] [DllImport("GMH3x32E.dll")]
unsafe public static extern Int16 GMH_Transmit(Int16 ini16DeviceAddress, Int16 ini16TransmitCode, Int16* refi16ptrPriority, double* refdblptrFloatValue, Int32* refi32ptrIntegerValue); unsafe public static extern Int16 GMH_Transmit(Int16 ini16DeviceAddress, Int16 ini16TransmitCode, Int16* refi16ptrPriority, double* refdblptrFloatValue, Int32* refi32ptrIntegerValue);
public TemperatureSource() private readonly bool connected;
{
UniversalOpenCom(Appsettings.GMHPort, 4800, 8, 0, 0); public TemperatureSource()
} => this.connected = UniversalOpenCom(Appsettings.GMHPort, 4800, 8, 0, 0) == 2;
public double GetTemperature() public double GetTemperature()
{ {
@@ -33,9 +33,18 @@
result = GMH_Transmit(1, 0, &priority, &temperature, &value); result = GMH_Transmit(1, 0, &priority, &temperature, &value);
} }
if (temperature < 50)
{
return -1.11;
}
else if (temperature > 50)
{
return 1.11;
}
return temperature; return temperature;
} }
catch (Exception e) catch
{ {
return 0; return 0;
} }
+7 -4
View File
@@ -16,6 +16,7 @@ using System.Windows.Forms;
using Xylem.Common.CommonCore.Configuration; using Xylem.Common.CommonCore.Configuration;
using Xylem.Common.CommonCore.Consts; using Xylem.Common.CommonCore.Consts;
using Xylem.Common.Hardware.Interfaces.Ports.PortCore; using Xylem.Common.Hardware.Interfaces.Ports.PortCore;
using Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Const;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile;
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus;
@@ -1093,12 +1094,14 @@ namespace Xylem.Common.Ui.GenesisToolBox
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.AppendLine($"PCBID: {_currentGenesis.PcbId}"); sb.AppendLine($"PCBID: {_currentGenesis.PcbId}");
sb.AppendLine($"Date: {DateTimeOffset.UtcNow}"); sb.AppendLine($"Date: {DateTimeOffset.UtcNow}");
sb.AppendLine($"System Core Revision: {BuildFwVersionString(_currentGenesis.CoreRevision)}"); sb.AppendLine($"System Core Revision: {_currentGenesis.StrCoreRevision}");
foreach (var fm in _currentGenesis.MeterAppListVersion.OrderBy(o => o.AppId)) foreach (var fm in _currentGenesis.MeterAppListVersion.OrderBy(o => o.AppId))
{ {
var versionString = fm.IsInstalled var versionString = fm.IsInstalled
? $"V: {fm.Version / 100}.{fm.Version % 100:D2} - CRC: 0x{fm.Crc:X4}\t" ? $"V: {fm.StrVersion} - CRC: 0x{fm.Crc:X4}" : "Not installed";
: "Not installed\t\t"; if (fm.Status == MeterAppState.Unknown)
versionString = "Communication error";
sb.AppendLine($"AppId: 0x{fm.AppId:X2} - {versionString} - AppName: {fm.AppName}"); sb.AppendLine($"AppId: 0x{fm.AppId:X2} - {versionString} - AppName: {fm.AppName}");
} }
@@ -1901,7 +1904,7 @@ namespace Xylem.Common.Ui.GenesisToolBox
apps.Add(new CordonelAppVersion(item.AppId, item.StrVersion, item.AppId != 15)); apps.Add(new CordonelAppVersion(item.AppId, item.StrVersion, item.AppId != 15));
} }
apps.Add(new CordonelAppVersion(-1, BuildFwVersionString(_currentGenesis.CoreRevision), false)); apps.Add(new CordonelAppVersion(-1, _currentGenesis.StrCoreRevision, false));
var url = $"{ServiceUrls.MeterProcessStateUrl()}SetCordonelProgress?PcbId={_currentGenesis.PcbId}&ProgressName=toolbox&version={Assembly.GetExecutingAssembly().GetName().Version}"; var url = $"{ServiceUrls.MeterProcessStateUrl()}SetCordonelProgress?PcbId={_currentGenesis.PcbId}&ProgressName=toolbox&version={Assembly.GetExecutingAssembly().GetName().Version}";
var a = LocalWebRequest.PostRequestAsync(url, json: apps); var a = LocalWebRequest.PostRequestAsync(url, json: apps);
+2
View File
@@ -538,6 +538,8 @@ namespace Xylem.Common.Ui.MagFluxToolBox
//{ //{
// var versionString = app.IsInstalled ? $"V: {app.StrVersion} - CRC: 0x{app.Crc:X4}" : // var versionString = app.IsInstalled ? $"V: {app.StrVersion} - CRC: 0x{app.Crc:X4}" :
// "App NOT Installed"; // "App NOT Installed";
// if (app.Status == MeterAppState.Unknown)
// versionString = "COMMUNICATION ERROR";
// LogText($"AppId: 0x{app.AppId:X2} - {versionString} - " + $"AppName: {app.AppName}"); // LogText($"AppId: 0x{app.AppId:X2} - {versionString} - " + $"AppName: {app.AppName}");
// if (app.IsInstalled) // if (app.IsInstalled)
@@ -0,0 +1,26 @@
namespace LaaProduction.Data.Cordonel
{
using LaaProduction.Data.Cordonel.Interfaces;
using LaaProduction.Data.Cordonel.Models;
using LaaProduction.Data.Cordonel.Repositories;
using LaaProduction.Data.SQL;
using LaaProduction.Data.SQL.Interfaces;
using System;
public class CordonelDbContext
{
private readonly ISQLConnection sqlConnection;
public CordonelDbContext(string connectionString, Action<string> errorsCallback = null)
{
this.sqlConnection = new SQLConnection(connectionString, errorsCallback);
this.SpecialRequirements = new SpecialRequirementsRepository(this.sqlConnection);
this.StandardRequirements = new StandardRequirementsRepository(this.sqlConnection);
}
public IRepository<CordonelSpecialRequirement> SpecialRequirements { get; }
public IRepository<CordonelStandardRequirement> StandardRequirements { get; }
}
}
@@ -0,0 +1,17 @@
namespace LaaProduction.Data.Cordonel.Interfaces
{
using System.Collections.Generic;
public interface IRepository<T> : IEnumerable<T>
{
T Add(T model);
T Delete(object id);
T FirstOrDefault(object id);
T FirstOrDefault(params object[] ids);
T Update(T model);
}
}
@@ -4,11 +4,11 @@
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D96612D9-5B00-42CB-9779-FE5C251BB78F}</ProjectGuid> <ProjectGuid>{03784923-1FD3-4535-80F5-286728DF62AB}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Plugins.Abstraction</RootNamespace> <RootNamespace>LaaProduction.Data.Cordonel</RootNamespace>
<AssemblyName>Plugins.Abstraction</AssemblyName> <AssemblyName>LaaProduction.Data.Cordonel</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
@@ -32,6 +32,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
@@ -40,9 +41,21 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="IMeter.cs" /> <Compile Include="CordonelDbContext.cs" />
<Compile Include="IMeterBatch.cs" /> <Compile Include="Models\CordonelSpecialRequirement.cs" />
<Compile Include="Models\CordonelSpecialRequirementChange.cs" />
<Compile Include="Models\CordonelStandardRequirement.cs" />
<Compile Include="Interfaces\IRepository[T].cs" />
<Compile Include="Models\CordonelStandardRequirementChange.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repositories\SpecialRequirementsRepository.cs" />
<Compile Include="Repositories\StandardRequirementsRepository.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\LaaProduction.Data.SQL\LaaProduction.Data.SQL.csproj">
<Project>{82D34580-23FE-4315-BC51-51D565ABAE23}</Project>
<Name>LaaProduction.Data.SQL</Name>
</ProjectReference>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>
@@ -0,0 +1,120 @@
namespace LaaProduction.Data.Cordonel.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class CordonelSpecialRequirement
{
private int? standardId;
private string fwVersion;
private string lutVersion;
private double? requiredLifeTimeYearsAssembly;
private double? requiredLifeTimeYearsShipping;
private double? maxDrainedBatteryLoadPercentAssembly;
private double? maxDrainedBatteryLoadPercentShipping;
private double? maxStorageMonths;
private double? maxStorageMonthsBigOrders;
private string comment;
[Display(Name = "Id", Description = "Die in der Datenbank zugewiesene Id. Nicht änderbar!")]
public int Id { get; set; }
[Display(Name = "Versionsnr.", Description = "Die in der Datenbank zugewiesene Versionsnr. Nicht änderbar!")]
public int Nr { get; set; }
[Required]
[Display(Name = "Standard Id", Description = "...")]
public int? StandardId
{
get => this.standardId ?? this.StandardRequirement?.Id;
set => this.standardId = value;
}
[Required]
[Display(Name = "Fertigungsauftragnr.", Description = "...")]
public int? ProductionOrderNr { get; set; }
[Display(Name = "Pcb Id", Description = "...")]
public int? PcbId { get; set; }
[Display(Name = "Firmware-Version", Description = "Standardmäßig zu installierende Firmware-Version.")]
public string FwVersion
{
get => this.fwVersion ?? this.StandardRequirement?.FwVersion;
set => this.fwVersion = value;
}
[Display(Name = "LUT-Version", Description = "Standardmäßig zu installierende LUT-Version.")]
public string LutVersion
{
get => this.lutVersion ?? this.StandardRequirement?.LutVersion;
set => this.lutVersion = value;
}
[Display(Name = "Erforderliche Lebensdauer in Jahren (Assembly)", Description = "Erforderliche Lebensdauer in Jahren.")]
public double? RequiredLifeTimeYearsAssembly
{
get => this.requiredLifeTimeYearsAssembly ?? this.StandardRequirement?.RequiredLifeTimeYearsAssembly;
set => this.requiredLifeTimeYearsAssembly = value;
}
[Display(Name = "Erforderliche Lebensdauer in Jahren (Shipping)", Description = "Erforderliche Lebensdauer in Jahren.")]
public double? RequiredLifeTimeYearsShipping
{
get => this.requiredLifeTimeYearsShipping ?? this.StandardRequirement?.RequiredLifeTimeYearsShipping;
set => this.requiredLifeTimeYearsShipping = value;
}
[Display(Name = "Max. entladene Batterieladung in Prozent (Assembly)", Description = "Max. entladene Batterieladung in Prozent.")]
public double? MaxDrainedBatteryLoadPercentAssembly
{
get => this.maxDrainedBatteryLoadPercentAssembly ?? this.StandardRequirement?.MaxDrainedBatteryLoadPercentAssembly;
set => this.maxDrainedBatteryLoadPercentAssembly = value;
}
[Display(Name = "Max. entladene Batterieladung in Prozent (Shipping)", Description = "Max. entladene Batterieladung in Prozent.")]
public double? MaxDrainedBatteryLoadPercentShipping
{
get => this.maxDrainedBatteryLoadPercentShipping ?? this.StandardRequirement?.MaxDrainedBatteryLoadPercentShipping;
set => this.maxDrainedBatteryLoadPercentShipping = value;
}
[Display(Name = "Maximale Lagerzeit in Monate", Description = "Maximale Lagerzeit in Monate.")]
public double? MaxStorageMonths
{
get => this.maxStorageMonths ?? this.StandardRequirement?.MaxStorageMonths;
set => this.maxStorageMonths = value;
}
[Display(Name = "Maximale Lagerzeit in Monate (Big orders)", Description = "Maximale Lagerzeit in Monate.")]
public double? MaxStorageMonthsBigOrders
{
get => this.maxStorageMonthsBigOrders ?? this.StandardRequirement?.MaxStorageMonthsBigOrders;
set => this.maxStorageMonthsBigOrders = value;
}
[Display(Name = "Zeitstämpel", Description = "Zeitstämpel der letzten änderung. Nicht änderbar!")]
[DateTimeInRange(3600, 10)]
public DateTime Timestamp { get; set; }
[Display(Name = "Bearbeiter", Description = "Name des Bearbeiters. Nicht änderbar!")]
[Required]
public string CreatedBy { get; set; }
[Display(Name = "Kommentar", Description = "Kommentar über die änderungen.")]
[Required]
public string Comment
{
get => this.comment ?? this.StandardRequirement?.Comment;
set => this.comment = value;
}
[Display(Name = "ist zur Produktion freigegeben", Description = "Ist zur Produktion freigegeben.")]
public bool IsActive { get; set; }
public CordonelStandardRequirement StandardRequirement { get; set; }
public IEnumerable<CordonelSpecialRequirementChange> History { get; set; }
}
}
@@ -0,0 +1,27 @@
namespace LaaProduction.Data.Cordonel.Models
{
using System;
using System.ComponentModel.DataAnnotations;
public class CordonelSpecialRequirementChange
{
[Display(Name = "Id", Description = "Die in der Datenbank zugewiesene Id. Nicht änderbar!")]
public int Id { get; set; }
[Display(Name = "Versionsnr.", Description = "Die in der Datenbank zugewiesene Versionsnr. Nicht änderbar!")]
public int Nr { get; set; }
[Display(Name = "Zeitstämpel", Description = "Zeitstämpel der letzten änderung. Nicht änderbar!")]
public DateTime Timestamp { get; set; }
[Display(Name = "Bearbeiter", Description = "Name des Bearbeiters. Nicht änderbar!")]
[Required]
public string CreatedBy { get; set; }
[Display(Name = "Kommentar", Description = "Kommentar über die änderungen.")]
public string Comment { get; set; }
[Display(Name = "ist zur Produktion freigegeben", Description = "Ist zur Produktion freigegeben.")]
public bool IsActive { get; set; }
}
}
@@ -0,0 +1,101 @@
namespace LaaProduction.Data.Cordonel.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class CordonelStandardRequirement
{
[Display(Name = "Id", Description = "Die in der Datenbank zugewiesene Id. Nicht änderbar!")]
public int Id { get; set; }
[Display(Name = "Versionsnr.", Description = "Die in der Datenbank zugewiesene Versionsnr. Nicht änderbar!")]
public int Nr { get; set; }
[Display(Name = "Key", Description = "Eindeutiger Schlüssel für Region und Zählergröße. Nicht änderbar!")]
public string Key { get; set; }
[Display(Name = "Region", Description = "Der Region für den Zähler wird gebaut. Nicht änderbar!")]
public string Region { get; set; }
[Display(Name = "Nennweite bezeichnung", Description = "Die Bezeichnung des Nenndurchmessers basierend auf der Region. Nicht änderbar!")]
public string MeterSize { get; set; }
[Display(Name = "Firmware-Version", Description = "Standardmäßig zu installierende Firmware-Version.")]
[Required]
public string FwVersion { get; set; }
[Display(Name = "LUT-Version", Description = "Standardmäßig zu installierende LUT-Version.")]
[Required]
public string LutVersion { get; set; }
[Display(Name = "Erforderliche Lebensdauer in Jahren (Assembly)", Description = "Erforderliche Lebensdauer in Jahren.")]
[Range(0D, 100D)]
public double RequiredLifeTimeYearsAssembly { get; set; }
[Display(Name = "Erforderliche Lebensdauer in Jahren (Shipping)", Description = "Erforderliche Lebensdauer in Jahren.")]
[Range(0D, 100D)]
public double RequiredLifeTimeYearsShipping { get; set; }
[Display(Name = "Max. entladene Batterieladung in Prozent (Assembly)", Description = "Max. entladene Batterieladung in Prozent.")]
[Range(0D, 100D)]
public double MaxDrainedBatteryLoadPercentAssembly { get; set; }
[Display(Name = "Max. entladene Batterieladung in Prozent (Shipping)", Description = "Max. entladene Batterieladung in Prozent.")]
[Range(0D, 100D)]
public double MaxDrainedBatteryLoadPercentShipping { get; set; }
[Display(Name = "Maximale Lagerzeit in Monate", Description = "Maximale Lagerzeit in Monate.")]
[Range(0D, 1000D)]
public double MaxStorageMonths { get; set; }
[Display(Name = "Maximale Lagerzeit in Monate (Big orders)", Description = "Maximale Lagerzeit in Monate.")]
[Range(0D, 1000D)]
public double MaxStorageMonthsBigOrders { get; set; }
[Display(Name = "Zeitstämpel", Description = "Zeitstämpel der letzten änderung. Nicht änderbar!")]
[DateTimeInRange(3600, 10)]
public DateTime Timestamp { get; set; }
[Display(Name = "Bearbeiter", Description = "Name des Bearbeiters. Nicht änderbar!")]
[Required]
public string CreatedBy { get; set; }
[Display(Name = "Kommentar", Description = "Kommentar über die änderungen.")]
[Required]
public string Comment { get; set; }
[Display(Name = "ist zur Produktion freigegeben", Description = "Ist zur Produktion freigegeben.")]
public bool IsActive { get; set; }
public IEnumerable<CordonelStandardRequirementChange> History { get; set; }
}
public class DateTimeInRange : RangeAttribute
{
private readonly int minimum;
private readonly int maximum;
public DateTimeInRange(int minimum, int maximum) : base(minimum, maximum)
{
this.minimum = minimum;
this.maximum = maximum;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value is DateTime timestamp)
{
var min = timestamp.AddSeconds(this.minimum);
var max = timestamp.AddSeconds(this.maximum);
if ((min - timestamp).TotalSeconds >= 0 && (max - timestamp).TotalSeconds >= 0)
{
return ValidationResult.Success;
}
}
return new ValidationResult("Invalid date/time.");
}
}
}
@@ -0,0 +1,27 @@
namespace LaaProduction.Data.Cordonel.Models
{
using System;
using System.ComponentModel.DataAnnotations;
public class CordonelStandardRequirementChange
{
[Display(Name = "Id", Description = "Die in der Datenbank zugewiesene Id. Nicht änderbar!")]
public int Id { get; set; }
[Display(Name = "Versionsnr.", Description = "Die in der Datenbank zugewiesene Versionsnr. Nicht änderbar!")]
public int Nr { get; set; }
[Display(Name = "Zeitstämpel", Description = "Zeitstämpel der letzten änderung. Nicht änderbar!")]
public DateTime Timestamp { get; set; }
[Display(Name = "Bearbeiter", Description = "Name des Bearbeiters. Nicht änderbar!")]
[Required]
public string CreatedBy { get; set; }
[Display(Name = "Kommentar", Description = "Kommentar über die änderungen.")]
public string Comment { get; set; }
[Display(Name = "ist zur Produktion freigegeben", Description = "Ist zur Produktion freigegeben.")]
public bool IsActive { get; set; }
}
}
@@ -0,0 +1,36 @@
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("LaaProduction.Data.Cordonel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LaaProduction.Data.Cordonel")]
[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)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("03784923-1fd3-4535-80f5-286728df62ab")]
// 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")]
@@ -0,0 +1,53 @@
namespace LaaProduction.Data.Cordonel.Repositories
{
using LaaProduction.Data.Cordonel.Interfaces;
using LaaProduction.Data.Cordonel.Models;
using LaaProduction.Data.SQL.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
public class SpecialRequirementsRepository : IRepository<CordonelSpecialRequirement>
{
private ISQLConnection sqlConnection;
public SpecialRequirementsRepository(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public CordonelSpecialRequirement Add(CordonelSpecialRequirement model)
{
throw new NotImplementedException();
}
public CordonelSpecialRequirement Delete(object id)
{
throw new NotImplementedException();
}
public CordonelSpecialRequirement FirstOrDefault(object id)
{
throw new NotImplementedException();
}
public CordonelSpecialRequirement FirstOrDefault(params object[] ids)
{
throw new NotImplementedException();
}
public IEnumerator<CordonelSpecialRequirement> GetEnumerator()
{
throw new NotImplementedException();
}
public CordonelSpecialRequirement Update(CordonelSpecialRequirement model)
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,324 @@
namespace LaaProduction.Data.Cordonel.Repositories
{
using LaaProduction.Data.Cordonel.Interfaces;
using LaaProduction.Data.Cordonel.Models;
using LaaProduction.Data.SQL.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
public class StandardRequirementsRepository : IRepository<CordonelStandardRequirement>
{
private readonly ISQLConnection sqlConnection;
public StandardRequirementsRepository(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public CordonelStandardRequirement Add(CordonelStandardRequirement model)
{
var insertedId = this.sqlConnection
.CreateCommand($@"
INSERT INTO [Cordonel_Standard_Requirements]
( [Id]
, [Nr]
, [Key]
, [Region]
, [MeterSize]
, [FwVersion]
, [LutVersion]
, [RequiredLifeTimeYearsAssembly]
, [RequiredLifeTimeYearsShipping]
, [MaxDrainedBatteryLoadPercentAssembly]
, [MaxDrainedBatteryLoadPercentShipping]
, [MaxStorageMonths]
, [MaxStorageMonthsBigOrders]
, [Timestamp]
, [CreatedBy]
, [Comment]
, [IsActive])
OUTPUT [inserted].[Id]
VALUES ((SELECT MAX([Id]) + 1 FROM [Cordonel_Standard_Requirements]))
, 1
, @{nameof(model.Key)}
, @{nameof(model.Region)}
, @{nameof(model.MeterSize)}
, @{nameof(model.FwVersion)}
, @{nameof(model.LutVersion)}
, @{nameof(model.RequiredLifeTimeYearsAssembly)}
, @{nameof(model.RequiredLifeTimeYearsShipping)}
, @{nameof(model.MaxDrainedBatteryLoadPercentAssembly)}
, @{nameof(model.MaxDrainedBatteryLoadPercentShipping)}
, @{nameof(model.MaxStorageMonths)}
, @{nameof(model.MaxStorageMonthsBigOrders)}
, @{nameof(model.Timestamp)}
, @{nameof(model.CreatedBy)}
, @{nameof(model.Comment)}
, @{nameof(model.IsActive)}")
.SetParameter(nameof(model.Key), model.Key)
.SetParameter(nameof(model.Region), model.Region)
.SetParameter(nameof(model.MeterSize), model.MeterSize)
.SetParameter(nameof(model.FwVersion), model.FwVersion)
.SetParameter(nameof(model.LutVersion), model.LutVersion)
.SetParameter(nameof(model.RequiredLifeTimeYearsAssembly), model.RequiredLifeTimeYearsAssembly)
.SetParameter(nameof(model.RequiredLifeTimeYearsShipping), model.RequiredLifeTimeYearsShipping)
.SetParameter(nameof(model.MaxDrainedBatteryLoadPercentAssembly), model.MaxDrainedBatteryLoadPercentAssembly)
.SetParameter(nameof(model.MaxDrainedBatteryLoadPercentShipping), model.MaxDrainedBatteryLoadPercentShipping)
.SetParameter(nameof(model.MaxStorageMonths), model.MaxStorageMonths)
.SetParameter(nameof(model.MaxStorageMonthsBigOrders), model.MaxStorageMonthsBigOrders)
.SetParameter(nameof(model.Timestamp), model.Timestamp)
.SetParameter(nameof(model.CreatedBy), model.CreatedBy)
.SetParameter(nameof(model.Comment), model.Comment)
.SetParameter(nameof(model.IsActive), model.IsActive)
.ExecuteScalar(x => x.GetValue<int>(0));
return this.FirstOrDefault(insertedId);
}
public CordonelStandardRequirement Delete(object id)
=> throw new NotImplementedException($"{nameof(CordonelStandardRequirement)} could not be deleted");
public CordonelStandardRequirement FirstOrDefault(object id)
{
var requirement = this.sqlConnection
.CreateCommand($@"
SELECT TOP 1
[Id]
, [Nr]
, [Key]
, [Region]
, [MeterSize]
, [FwVersion]
, [LutVersion]
, [RequiredLifeTimeYearsAssembly]
, [RequiredLifeTimeYearsShipping]
, [MaxDrainedBatteryLoadPercentAssembly]
, [MaxDrainedBatteryLoadPercentShipping]
, [MaxStorageMonths]
, [MaxStorageMonthsBigOrders]
, [Timestamp]
, [CreatedBy]
, [Comment]
, [IsActive]
FROM [Cordonel_Standard_Requirements]
WHERE [Id] = @{nameof(id)}
ORDER BY [Nr] DESC")
.SetParameter(nameof(id), id)
.FirstOrDefault(x => new CordonelStandardRequirement
{
Id = x.GetValue<int>(0),
Nr = x.GetValue<int>(1),
Key = x.GetValue<string>(2),
Region = x.GetValue<string>(3),
MeterSize = x.GetValue<string>(4),
FwVersion = x.GetValue<string>(5),
LutVersion = x.GetValue<string>(6),
RequiredLifeTimeYearsAssembly = x.GetValue<double>(7),
RequiredLifeTimeYearsShipping = x.GetValue<double>(8),
MaxDrainedBatteryLoadPercentAssembly = x.GetValue<double>(9),
MaxDrainedBatteryLoadPercentShipping = x.GetValue<double>(10),
MaxStorageMonths = x.GetValue<double>(11),
MaxStorageMonthsBigOrders = x.GetValue<double>(12),
Timestamp = x.GetValue<DateTime>(13),
CreatedBy = x.GetValue<string>(14),
Comment = x.GetValue<string>(15),
IsActive = x.GetValue<bool>(16),
});
requirement.History = this.sqlConnection
.CreateCommand($@"
SELECT [Id]
, [Nr]
, [Timestamp]
, [CreatedBy]
, [Comment]
, [IsActive]
FROM [Cordonel_Standard_Requirements]
WHERE [Id] = @{nameof(requirement.Id)}
AND [Nr] <> @{nameof(requirement.Nr)}
ORDER BY [Nr] DESC")
.SetParameter(nameof(requirement.Id), requirement.Id)
.SetParameter(nameof(requirement.Nr), requirement.Nr)
.ExecuteReader(x => new CordonelStandardRequirementChange
{
Id = x.GetValue<int>(0),
Nr = x.GetValue<int>(1),
Timestamp = x.GetValue<DateTime>(2),
CreatedBy = x.GetValue<string>(3),
Comment = x.GetValue<string>(4),
IsActive = x.GetValue<bool>(5),
});
return requirement;
}
public CordonelStandardRequirement FirstOrDefault(params object[] ids)
{
var requirement = this.sqlConnection
.CreateCommand($@"
SELECT TOP 1
[Id]
, [Nr]
, [Key]
, [Region]
, [MeterSize]
, [FwVersion]
, [LutVersion]
, [RequiredLifeTimeYearsAssembly]
, [RequiredLifeTimeYearsShipping]
, [MaxDrainedBatteryLoadPercentAssembly]
, [MaxDrainedBatteryLoadPercentShipping]
, [MaxStorageMonths]
, [MaxStorageMonthsBigOrders]
, [Timestamp]
, [CreatedBy]
, [Comment]
, [IsActive]
FROM [Cordonel_Standard_Requirements]
WHERE [Id] = @{nameof(CordonelStandardRequirement.Id)}
AND [Nr] = @{nameof(CordonelStandardRequirement.Nr)}")
.SetParameter(nameof(CordonelStandardRequirement.Id), ids[0])
.SetParameter(nameof(CordonelStandardRequirement.Nr), ids[1])
.FirstOrDefault(x => new CordonelStandardRequirement
{
Id = x.GetValue<int>(0),
Nr = x.GetValue<int>(1),
Key = x.GetValue<string>(2),
Region = x.GetValue<string>(3),
MeterSize = x.GetValue<string>(4),
FwVersion = x.GetValue<string>(5),
LutVersion = x.GetValue<string>(6),
RequiredLifeTimeYearsAssembly = x.GetValue<double>(7),
RequiredLifeTimeYearsShipping = x.GetValue<double>(8),
MaxDrainedBatteryLoadPercentAssembly = x.GetValue<double>(9),
MaxDrainedBatteryLoadPercentShipping = x.GetValue<double>(10),
MaxStorageMonths = x.GetValue<double>(11),
MaxStorageMonthsBigOrders = x.GetValue<double>(12),
Timestamp = x.GetValue<DateTime>(13),
CreatedBy = x.GetValue<string>(14),
Comment = x.GetValue<string>(15),
IsActive = x.GetValue<bool>(16),
});
requirement.History = this.sqlConnection
.CreateCommand($@"
SELECT [Id]
, [Nr]
, [Timestamp]
, [CreatedBy]
, [Comment]
, [IsActive]
FROM [Cordonel_Standard_Requirements]
WHERE [Id] = @{nameof(requirement.Id)}
AND [Nr] <> @{nameof(requirement.Nr)}
ORDER BY [Nr] DESC")
.SetParameter(nameof(requirement.Id), requirement.Id)
.SetParameter(nameof(requirement.Nr), requirement.Nr)
.ExecuteReader(x => new CordonelStandardRequirementChange
{
Id = x.GetValue<int>(0),
Nr = x.GetValue<int>(1),
Timestamp = x.GetValue<DateTime>(2),
CreatedBy = x.GetValue<string>(3),
Comment = x.GetValue<string>(4),
IsActive = x.GetValue<bool>(5),
});
return requirement;
}
public IEnumerator<CordonelStandardRequirement> GetEnumerator()
{
return this.sqlConnection
.CreateCommand(@"
SELECT [Id]
, [Nr]
, [Key]
, [Region]
, [MeterSize]
, [FwVersion]
, [LutVersion]
, [RequiredLifeTimeYearsAssembly]
, [RequiredLifeTimeYearsShipping]
, [MaxDrainedBatteryLoadPercentAssembly]
, [MaxDrainedBatteryLoadPercentShipping]
, [MaxStorageMonths]
, [MaxStorageMonthsBigOrders]
, [Timestamp]
, [CreatedBy]
, [Comment]
, [IsActive]
FROM (SELECT *, RANK() OVER (PARTITION BY [Id]
ORDER BY [Nr] DESC) AS [RowNr]
FROM [Cordonel_Standard_Requirements])
AS [Latest]
WHERE [Latest].[RowNr] = 1
ORDER BY [Region] ASC
, LEN([MeterSize]) ASC
, [MeterSize] ASC")
.ExecuteReader(x => new CordonelStandardRequirement
{
Id = x.GetValue<int>(0),
Nr = x.GetValue<int>(1),
Key = x.GetValue<string>(2),
Region = x.GetValue<string>(3),
MeterSize = x.GetValue<string>(4),
FwVersion = x.GetValue<string>(5),
LutVersion = x.GetValue<string>(6),
RequiredLifeTimeYearsAssembly = x.GetValue<double>(7),
RequiredLifeTimeYearsShipping = x.GetValue<double>(8),
MaxDrainedBatteryLoadPercentAssembly = x.GetValue<double>(9),
MaxDrainedBatteryLoadPercentShipping = x.GetValue<double>(10),
MaxStorageMonths = x.GetValue<double>(11),
MaxStorageMonthsBigOrders = x.GetValue<double>(12),
Timestamp = x.GetValue<DateTime>(13),
CreatedBy = x.GetValue<string>(14),
Comment = x.GetValue<string>(15),
IsActive = x.GetValue<bool>(16),
})
.GetEnumerator();
}
public CordonelStandardRequirement Update(CordonelStandardRequirement model)
{
var rowsAffected = this.sqlConnection
.CreateCommand($@"
UPDATE [Cordonel_Standard_Requirements]
SET [FwVersion] = @{nameof(model.FwVersion)}
, [LutVersion] = @{nameof(model.LutVersion)}
, [RequiredLifeTimeYearsAssembly] = @{nameof(model.RequiredLifeTimeYearsAssembly)}
, [RequiredLifeTimeYearsShipping] = @{nameof(model.RequiredLifeTimeYearsShipping)}
, [MaxDrainedBatteryLoadPercentAssembly] = @{nameof(model.MaxDrainedBatteryLoadPercentAssembly)}
, [MaxDrainedBatteryLoadPercentShipping] = @{nameof(model.MaxDrainedBatteryLoadPercentShipping)}
, [MaxStorageMonths] = @{nameof(model.MaxStorageMonths)}
, [MaxStorageMonthsBigOrders] = @{nameof(model.MaxStorageMonthsBigOrders)}
, [Timestamp] = @{nameof(model.Timestamp)}
, [CreatedBy] = @{nameof(model.CreatedBy)}
, [Comment] = @{nameof(model.Comment)}
, [IsActive] = @{nameof(model.IsActive)}
WHERE [Id] = @{nameof(model.Id)}
AND [Nr] = (SELECT MAX([Nr])
FROM [Cordonel_Standard_Requirements]
WHERE [Id] = @{nameof(model.Id)})")
.SetParameter(nameof(model.FwVersion), model.FwVersion)
.SetParameter(nameof(model.LutVersion), model.LutVersion)
.SetParameter(nameof(model.RequiredLifeTimeYearsAssembly), model.RequiredLifeTimeYearsAssembly)
.SetParameter(nameof(model.RequiredLifeTimeYearsShipping), model.RequiredLifeTimeYearsShipping)
.SetParameter(nameof(model.MaxDrainedBatteryLoadPercentAssembly), model.MaxDrainedBatteryLoadPercentAssembly)
.SetParameter(nameof(model.MaxDrainedBatteryLoadPercentShipping), model.MaxDrainedBatteryLoadPercentShipping)
.SetParameter(nameof(model.MaxStorageMonths), model.MaxStorageMonths)
.SetParameter(nameof(model.MaxStorageMonthsBigOrders), model.MaxStorageMonthsBigOrders)
.SetParameter(nameof(model.Timestamp), model.Timestamp)
.SetParameter(nameof(model.CreatedBy), model.CreatedBy)
.SetParameter(nameof(model.Comment), model.Comment)
.SetParameter(nameof(model.IsActive), model.IsActive)
.SetParameter(nameof(model.Id), model.Id)
.ExecuteNonQuery();
return this.FirstOrDefault(model.Id);
}
IEnumerator IEnumerable.GetEnumerator()
=> this.GetEnumerator();
}
}
@@ -25,6 +25,14 @@
public CSRModel Find(int id) public CSRModel Find(int id)
=> this.csrRepository.Find(id); => this.csrRepository.Find(id);
public IEnumerable<CordonelRequirementsModel> FindAll()
=> this.csrRepository.FindAll()
?? new List<CordonelRequirementsModel>();
public CordonelRequirementsModel FindFirstOrDefault(string nr)
=> this.csrRepository.FindFirstOrDefault(nr)
?? new CordonelRequirementsModel();
public CSRModel Update(CSRModel model) public CSRModel Update(CSRModel model)
=> this.csrRepository.Update(model); => this.csrRepository.Update(model);
} }
@@ -90,6 +90,165 @@
.FirstOrDefault(this.MapToCSRModel); .FirstOrDefault(this.MapToCSRModel);
} }
public IEnumerable<CordonelRequirementsModel> FindAll()
{
return this.sqlConnection
.CreateCommand($@"
SELECT [CSR1].[Id] AS [Id]
, [CSR1].[Key] AS [Key]
, [CSR1].[Region] AS [Region]
, [CSR1].[MeterSize] AS [MeterSize]
, [CSR1].[FwVersion] AS [FwVersion]
, [CSR1].[LutVersion]) AS [LutVersion]
, [CSR1].[RequiredLifeTimeYearsAssembly] AS [RequiredLifeTimeYearsAssembly]
, [CSR1].[RequiredLifeTimeYearsShipping] AS [RequiredLifeTimeYearsShipping]
, [CSR1].[MaxDrainedBatteryLoadPercentAssembly] AS [MaxDrainedBatteryLoadPercentAssembly]
, [CSR1].[MaxDrainedBatteryLoadPercentShipping] AS [MaxDrainedBatteryLoadPercentShipping]
, [CSR1].[MaxStorageMonths] AS [MaxStorageMonths]
, [CSR1].[MaxStorageMonthsBigOrders] AS [MaxStorageMonthsBigOrders]
, [CSR1].[Timestamp] AS [Timestamp1]
, [CSR1].[CreatedBy] AS [CreatedBy1]
, [CSR1].[Comment] AS [Comment]
, [CSR1].[IsActive] AS [IsActive]
FROM [Cordonel_Standard_Requirements] AS [CSR1]
ORDER BY [CSR1].[Region]
, [CSR1].[MeterSize]
, [CSR1].[IsActive]")
.ExecuteReader(reader => new CordonelRequirementsModel
{
Id = reader.GetValue<int>(),
Key = reader.GetValue<string>(),
Region = reader.GetValue<string>(),
MeterSize = reader.GetValue<string>(),
FwVersion = reader.GetValue<string>(),
LutVersion = reader.GetValue<string>(),
RequiredLifeTimeYearsAssembly = reader.GetValue<float>(),
RequiredLifeTimeYearsShipping = reader.GetValue<float>(),
MaxDrainedBatteryLoadPercentAssembly = reader.GetValue<float>(),
MaxDrainedBatteryLoadPercentShipping = reader.GetValue<float>(),
MaxStorageMonths = reader.GetValue<float>(),
MaxStorageMonthsBigOrders = reader.GetValue<float>(),
StandardTimestamp = reader.GetValue<DateTime>(),
StandardCreatedBy = reader.GetValue<string>(),
StandardComment = reader.GetValue<string>(),
StandardIsActive = reader.GetValue<bool>()
});
}
public CordonelRequirementsModel FindFirstOrDefault(string nr)
{
return this.sqlConnection
.CreateCommand($@"
DECLARE @searchNr INT;
DECLARE @fertigungsAuftragNr INT;
DECLARE @identNr INT;
------------------------------------------------------------------------------------------------------------------------------------------------
SET @searchNr = @{nameof(nr)};
SET @fertigungsAuftragNr = 0;
SET @identNr = 0;
------------------------------------------------------------------------------------------------------------------------------------------------
SELECT TOP 1
@fertigungsAuftragNr = ISNULL([AAP].[FertigungsauftragNr], 0)
, @identNr = ISNULL([AAP].[IdentNr], 0)
FROM [AuftragPositionSerienNr] AS [APS]
LEFT JOIN [AlleAuftragPositionen] AS [AAP]
ON [AAP].[AuftragNr] = [APS].[AuftragNr]
AND [AAP].[PositionNr] = [APS].[PositionNr]
WHERE [APS].[SerienNr] = (SELECT [PCBSN].[MapPcbIdToSerialNumber_SerialNumber]
FROM [MapPcbIdToSerialNumber] AS [PCBSN]
WHERE [PCBSN].[MapPcbIdToSerialNumber_PcbId] = @searchNr)
------------------------------------------------------------------------------------------------------------------------------------------------
IF @fertigungsAuftragNr = 0 OR @identNr = 0
BEGIN
SELECT @fertigungsAuftragNr = ISNULL([AAP].[FertigungsauftragNr], 0)
, @identNr = ISNULL([AAP].[IdentNr], 0)
FROM [AlleAuftragPositionen] AS [AAP]
WHERE [AAP].[FertigungsauftragNr] = @searchNr
END
------------------------------------------------------------------------------------------------------------------------------------------------
IF @fertigungsAuftragNr <> 0 AND @identNr <> 0
BEGIN
--------------------------------------------------------------------------------------------------------------------------------------------
SELECT [CSR1].[Id] AS [Id]
, [CSR2].[ProductionOrderNo] AS [ProductionOrderNo]
, [CSR2].[PcbId] AS [PcbId]
, [REG].[Key] AS [Key]
, [CSR1].[Region] AS [Region]
, [CSR1].[MeterSize] AS [MeterSize]
, ISNULL([CSR2].[FwVersion], [CSR1].[FwVersion]) AS [FwVersion]
, ISNULL([CSR2].[LutVersion], [CSR1].[LutVersion]) AS [LutVersion]
, ISNULL([CSR2].[RequiredLifeTimeYearsAssembly], [CSR1].[RequiredLifeTimeYearsAssembly]) AS [RequiredLifeTimeYearsAssembly]
, ISNULL([CSR2].[RequiredLifeTimeYearsShipping], [CSR1].[RequiredLifeTimeYearsShipping]) AS [RequiredLifeTimeYearsShipping]
, ISNULL([CSR2].[MaxDrainedBatteryLoadPercentAssembly], [CSR1].[MaxDrainedBatteryLoadPercentAssembly]) AS [MaxDrainedBatteryLoadPercentAssembly]
, ISNULL([CSR2].[MaxDrainedBatteryLoadPercentShipping], [CSR1].[MaxDrainedBatteryLoadPercentShipping]) AS [MaxDrainedBatteryLoadPercentShipping]
, ISNULL([CSR2].[MaxStorageMonths], [CSR1].[MaxStorageMonths]) AS [MaxStorageMonths]
, ISNULL([CSR2].[MaxStorageMonthsBigOrders], [CSR1].[MaxStorageMonthsBigOrders]) AS [MaxStorageMonthsBigOrders]
, [CSR1].[Timestamp] AS [Timestamp1]
, [CSR2].[Timestamp] AS [Timestamp2]
, [CSR1].[CreatedBy] AS [CreatedBy1]
, [CSR2].[CreatedBy] AS [CreatedBy2]
, [CSR1].[Comment] AS [Comment1]
, [CSR2].[Comment] AS [Comment1]
, [CSR1].[IsActive] AS [IsActive1]
, [CSR2].[IsActive] AS [IsActive2]
, CAST(CASE WHEN [CSR2].[Id] IS NULL THEN 0 ELSE 1 END AS BIT) AS [HasSpecialRequirement]
FROM (SELECT DISTINCT
[VMM].[Charcode] AS [Key]
, [CMS].[Dn_Name] AS [Size]
, [REG].[Wert] AS [Region]
FROM [VAKO_Merkmale] AS [VMM]
LEFT JOIN (SELECT [Charcode]
, [Wert]
FROM [VAKO_Merkmale]
WHERE [Basis] = 'GNS'
AND [Stelle] = 5)
AS [REG]
ON [VMM].[Charcode] LIKE '_' + [REG].[Charcode]
LEFT JOIN [Identnr] AS [IDN]
ON [VMM].[Charcode] = SUBSTRING([IDN].[VakoCode], [VMM].[Stelle], [VMM].[Laenge])
LEFT JOIN [CordonelMeterSizes] AS [CMS]
ON [CMS].[Dn_VakoID] = [VMM].[Charcode]
WHERE [VMM].[Basis] = 'GNS'
AND [VMM].[Bezeichnung] = 'NW'
AND [IDN].[IdentNr] = @identNr)
AS [REG]
JOIN [Cordonel_Standard_Requirements] AS [CSR1]
ON [CSR1].[Key] = [REG].[Key]
LEFT JOIN [Cordonel_Special_Requirements] AS [CSR2]
ON [CSR2].[StandardId] = [CSR1].[Id]
WHERE [CSR1].[IsActive] = 1
AND ISNULL([CSR2].[IsActive], 1) = 1
--------------------------------------------------------------------------------------------------------------------------------------------
END")
.SetParameter(nameof(nr), nr)
.FirstOrDefault(reader => new CordonelRequirementsModel
{
Id = reader.GetValue<int>(),
ProductionOrderNr = reader.GetValue<int?>(),
PcbId = reader.GetValue<int?>(),
Key = reader.GetValue<string>(),
Region = reader.GetValue<string>(),
MeterSize = reader.GetValue<string>(),
FwVersion = reader.GetValue<string>(),
LutVersion = reader.GetValue<string>(),
RequiredLifeTimeYearsAssembly = reader.GetValue<float>(),
RequiredLifeTimeYearsShipping = reader.GetValue<float>(),
MaxDrainedBatteryLoadPercentAssembly = reader.GetValue<float>(),
MaxDrainedBatteryLoadPercentShipping = reader.GetValue<float>(),
MaxStorageMonths = reader.GetValue<float>(),
MaxStorageMonthsBigOrders = reader.GetValue<float>(),
StandardTimestamp = reader.GetValue<DateTime>(),
SpecialTimestamp = reader.GetValue<DateTime?>(),
StandardCreatedBy = reader.GetValue<string>(),
SpecialCreatedBy = reader.GetValue<string>(),
StandardComment = reader.GetValue<string>(),
SpecialComment = reader.GetValue<string>(),
StandardIsActive = reader.GetValue<bool>(),
SpecialIsActive = reader.GetValue<bool?>(),
HasSpecialRequirement = reader.GetValue<bool>()
});
}
public CSRModel Insert(CSRModel model) public CSRModel Insert(CSRModel model)
{ {
var csrId = this.sqlConnection var csrId = this.sqlConnection
@@ -129,7 +288,7 @@
, @{nameof(model.KitronProductionDate)} , @{nameof(model.KitronProductionDate)}
, @{nameof(model.MaxDrainedBatteryLoadPercent)} , @{nameof(model.MaxDrainedBatteryLoadPercent)}
, @{nameof(model.MaxStorageMonths)} , @{nameof(model.MaxStorageMonths)}
, GETDATE() , GetValue<DateTime>()
, @{nameof(model.CreatedBy)} , @{nameof(model.CreatedBy)}
, @{nameof(model.Comment)})") , @{nameof(model.Comment)})")
.SetParameter(nameof(model.OrderNumber), model.OrderNumber) .SetParameter(nameof(model.OrderNumber), model.OrderNumber)
@@ -149,7 +308,7 @@
.SetParameter(nameof(model.MaxStorageMonths), model.MaxStorageMonths) .SetParameter(nameof(model.MaxStorageMonths), model.MaxStorageMonths)
.SetParameter(nameof(model.CreatedBy), model.CreatedBy) .SetParameter(nameof(model.CreatedBy), model.CreatedBy)
.SetParameter(nameof(model.Comment), model.Comment) .SetParameter(nameof(model.Comment), model.Comment)
.FirstOrDefault(x => x.GetInt()); .FirstOrDefault(x => x.GetValue<int>());
return this.Find(csrId); return this.Find(csrId);
} }
@@ -174,7 +333,7 @@
, [KitronProductionDate] = @{nameof(model.KitronProductionDate)} , [KitronProductionDate] = @{nameof(model.KitronProductionDate)}
, [MaxDrainedBatteryLoadPercent] = @{nameof(model.MaxDrainedBatteryLoadPercent)} , [MaxDrainedBatteryLoadPercent] = @{nameof(model.MaxDrainedBatteryLoadPercent)}
, [MaxStorageMonths] = @{nameof(model.MaxStorageMonths)} , [MaxStorageMonths] = @{nameof(model.MaxStorageMonths)}
, [AddDate] = GETDATE() , [AddDate] = GetValue<DateTime>()
, [CreatedBy] = @{nameof(model.CreatedBy)} , [CreatedBy] = @{nameof(model.CreatedBy)}
, [Comment] = @{nameof(model.Comment)} , [Comment] = @{nameof(model.Comment)}
WHERE [Id] = @{nameof(model.Id)}") WHERE [Id] = @{nameof(model.Id)}")
@@ -204,13 +363,13 @@
private CSRModel MapToCSRModel(ISQLReader reader) private CSRModel MapToCSRModel(ISQLReader reader)
=> new CSRModel => new CSRModel
{ {
Id = reader.GetInt(), Id = reader.GetValue<int>(),
OrderNumber = reader.GetValue<int?>(), OrderNumber = reader.GetValue<int?>(),
PcbId = reader.GetValue<int?>(), PcbId = reader.GetValue<int?>(),
Region = reader.GetString(), Region = reader.GetValue<string>(),
MeterSize = reader.GetValue<short?>(), MeterSize = reader.GetValue<short?>(),
FirmwareV = reader.GetString(), FirmwareV = reader.GetValue<string>(),
LutV = reader.GetString(), LutV = reader.GetValue<string>(),
BatteryLifetimeYears = reader.GetValue<float?>(), BatteryLifetimeYears = reader.GetValue<float?>(),
SkipRadioParametersCheck = reader.GetValue<bool?>(), SkipRadioParametersCheck = reader.GetValue<bool?>(),
OverrideFwCheck = reader.GetValue<int?>(), OverrideFwCheck = reader.GetValue<int?>(),
@@ -220,9 +379,9 @@
KitronProductionDate = reader.GetValue<DateTime?>(), KitronProductionDate = reader.GetValue<DateTime?>(),
MaxDrainedBatteryLoadPercent = reader.GetValue<float?>(), MaxDrainedBatteryLoadPercent = reader.GetValue<float?>(),
MaxStorageMonths = reader.GetValue<float?>(), MaxStorageMonths = reader.GetValue<float?>(),
AddDate = reader.GetDate(), AddDate = reader.GetValue<DateTime>(),
CreatedBy = reader.GetString(), CreatedBy = reader.GetValue<string>(),
Comment = reader.GetString() Comment = reader.GetValue<string>()
}; };
} }
} }
@@ -22,7 +22,7 @@
UPDATE [Cordonel_EOL_Progress] UPDATE [Cordonel_EOL_Progress]
SET [Completed] = @{nameof(status)} SET [Completed] = @{nameof(status)}
, [EditedBy] = @{nameof(editedBy)} , [EditedBy] = @{nameof(editedBy)}
, [CompleteDate] = GETDATE() , [CompleteDate] = GetValue<DateTime>()
WHERE [PcbId] = @{nameof(pcbid)} WHERE [PcbId] = @{nameof(pcbid)}
AND [Completed] IS NULL") AND [Completed] IS NULL")
.SetParameter(nameof(pcbid), pcbid) .SetParameter(nameof(pcbid), pcbid)
@@ -100,22 +100,22 @@
.SetParameter(nameof(pcbid), pcbid) .SetParameter(nameof(pcbid), pcbid)
.FirstOrDefault(reader => new EOLProgressModel .FirstOrDefault(reader => new EOLProgressModel
{ {
Id = reader.GetInt(), Id = reader.GetValue<int>(),
PcbId = reader.GetInt(), PcbId = reader.GetValue<int>(),
AddDate = reader.GetValue<DateTime>(), AddDate = reader.GetValue<DateTime>(),
RequirementId = reader.GetValue<int?>(), RequirementId = reader.GetValue<int?>(),
RequirementChecked = reader.GetString(), RequirementChecked = reader.GetValue<string>(),
PasswordFileInstalled = reader.GetString(), PasswordFileInstalled = reader.GetValue<string>(),
ProductionStatusChecked = reader.GetString(), ProductionStatusChecked = reader.GetValue<string>(),
ParameterizationDone = reader.GetString(), ParameterizationDone = reader.GetValue<string>(),
RebootDone = reader.GetString(), RebootDone = reader.GetValue<string>(),
StoreConfigurationDone = reader.GetString(), StoreConfigurationDone = reader.GetValue<string>(),
ExportDone = reader.GetString(), ExportDone = reader.GetValue<string>(),
RaioCheckId = reader.GetValue<long?>(), RaioCheckId = reader.GetValue<long?>(),
SentinelDate = reader.GetValue<DateTime?>(), SentinelDate = reader.GetValue<DateTime?>(),
Completed = reader.GetString(), Completed = reader.GetValue<string>(),
CompleteDate = reader.GetValue<DateTime?>(), CompleteDate = reader.GetValue<DateTime?>(),
EditedBy = reader.GetString(), EditedBy = reader.GetValue<string>(),
}); });
} }
@@ -12,6 +12,10 @@
CSRModel Find(int id); CSRModel Find(int id);
IEnumerable<CordonelRequirementsModel> FindAll();
CordonelRequirementsModel FindFirstOrDefault(string nr);
CSRModel Insert(CSRModel model); CSRModel Insert(CSRModel model);
CSRModel Update(CSRModel model); CSRModel Update(CSRModel model);
@@ -14,6 +14,10 @@
CSRModel Find(int id); CSRModel Find(int id);
IEnumerable<CordonelRequirementsModel> FindAll();
CordonelRequirementsModel FindFirstOrDefault(string nr);
CSRModel Update(CSRModel model); CSRModel Update(CSRModel model);
} }
} }
@@ -71,6 +71,7 @@
<Compile Include="EOLProgressService.cs" /> <Compile Include="EOLProgressService.cs" />
<Compile Include="Interfaces\IEOLProgressService.cs" /> <Compile Include="Interfaces\IEOLProgressService.cs" />
<Compile Include="Interfaces\ICSRService.cs" /> <Compile Include="Interfaces\ICSRService.cs" />
<Compile Include="Models\CordonelRequirementsModel.cs" />
<Compile Include="Models\CSRModel.cs" /> <Compile Include="Models\CSRModel.cs" />
<Compile Include="Models\EOLProgressModel.cs" /> <Compile Include="Models\EOLProgressModel.cs" />
<Compile Include="Models\WhereQuery.cs" /> <Compile Include="Models\WhereQuery.cs" />
@@ -0,0 +1,53 @@
namespace LaaProduction.Cordonel.Models
{
using System;
public class CordonelRequirementsModel
{
public int Id { get; set; }
public int? ProductionOrderNr { get; set; }
public int? PcbId { get; set; }
public string Key { get; set; }
public string Region { get; set; }
public string MeterSize { get; set; }
public string FwVersion { get; set; }
public string LutVersion { get; set; }
public float RequiredLifeTimeYearsAssembly { get; set; }
public float RequiredLifeTimeYearsShipping { get; set; }
public float MaxDrainedBatteryLoadPercentAssembly { get; set; }
public float MaxDrainedBatteryLoadPercentShipping { get; set; }
public float MaxStorageMonths { get; set; }
public float MaxStorageMonthsBigOrders { get; set; }
public DateTime StandardTimestamp { get; internal set; }
public DateTime? SpecialTimestamp { get; internal set; }
public string StandardCreatedBy { get; internal set; }
public string SpecialCreatedBy { get; internal set; }
public string StandardComment { get; internal set; }
public string SpecialComment { get; internal set; }
public bool StandardIsActive { get; internal set; }
public bool? SpecialIsActive { get; internal set; }
public bool HasSpecialRequirement { get; internal set; }
}
}
@@ -0,0 +1,18 @@
namespace LaaProduction.Data.SQL.Interfaces
{
using System;
using System.Collections.Generic;
public interface ISQLCommand
{
int ExecuteNonQuery();
IEnumerable<T> ExecuteReader<T>(Func<ISQLReader, T> expression);
T ExecuteScalar<T>(Func<ISQLReader, T> expression);
T FirstOrDefault<T>(Func<ISQLReader, T> expression);
ISQLCommand SetParameter(string name, object value);
}
}
@@ -0,0 +1,15 @@
namespace LaaProduction.Data.SQL.Interfaces
{
/// <summary>
/// <see cref="ISQLConnection"/> simply exposes the <see cref="ISQLConnection.CreateCommand(string)"/> method.
/// </summary>
public interface ISQLConnection
{
/// <summary>
/// Creates a command with given command text.
/// </summary>
/// <param name="commandText"><see cref="System.String"/> - SQL query string.</param>
/// <returns></returns>
ISQLCommand CreateCommand(string commandText);
}
}

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