diff --git a/Common/.shared/SharedAssemblyInfo.cs b/Common/.shared/SharedAssemblyInfo.cs index 8b771807..6c4ebd47 100644 --- a/Common/.shared/SharedAssemblyInfo.cs +++ b/Common/.shared/SharedAssemblyInfo.cs @@ -14,4 +14,4 @@ using System.Reflection; //[assembly: AssemblyVersion("1.2.*.0")] -[assembly: AssemblyVersion("2.6.20.*")] +[assembly: AssemblyVersion("2.7.0.*")] diff --git a/Common/.vs/config/applicationhost.config b/Common/.vs/config/applicationhost.config index a894c3cf..883679a3 100644 --- a/Common/.vs/config/applicationhost.config +++ b/Common/.vs/config/applicationhost.config @@ -155,7 +155,7 @@ - + diff --git a/Common/CommonCore.Configuration/ServiceUrls.cs b/Common/CommonCore.Configuration/ServiceUrls.cs index 1cee286c..952a32e7 100644 --- a/Common/CommonCore.Configuration/ServiceUrls.cs +++ b/Common/CommonCore.Configuration/ServiceUrls.cs @@ -420,6 +420,32 @@ namespace Xylem.Common.CommonCore.Configuration DefaultGetCordonelRequirementInfoUrl; } + /// + /// Get all production infos for skip process checks or limits for production like: + /// - Battery drained percentage upper limit, + /// - Production due date for a special register, + /// - Required life time for assembly line, + /// - Required life time for shipping line. + /// + /// + public static String GetCordonelRequirementByFANrInfoServiceUrl(string ponr) + { + return $"http://sla12iis01.emea.sensus.net/LaaProductionWeb/api/cordonel/requirements/pono/{ponr}"; + } + + /// + /// Get all production infos for skip process checks or limits for production like: + /// - Battery drained percentage upper limit, + /// - Production due date for a special register, + /// - Required life time for assembly line, + /// - Required life time for shipping line. + /// + /// + public static string GetCordonelRequirementByMeterSizeInfoServiceUrl(int size) + { + return $"http://sla12iis01.emea.sensus.net/LaaProductionWeb/api/cordonel/requirements/isize/{size}"; + } + /// /// Get all applications versions installed to a specific Cordonel. /// diff --git a/Common/CordonelAssemblyLine/CordonelAssemblyLine.csproj b/Common/CordonelAssemblyLine/CordonelAssemblyLine.csproj index 5aa52c31..4fade0db 100644 --- a/Common/CordonelAssemblyLine/CordonelAssemblyLine.csproj +++ b/Common/CordonelAssemblyLine/CordonelAssemblyLine.csproj @@ -230,6 +230,10 @@ {26AFCF1E-1287-48B8-A506-32B1E8A0DD0E} WaterMeterRegisters + + {8BEFD3AC-BB21-4B62-8D9A-CF8CBFD439EB} + LaaPackages.Features.Cordonel + {D0C859D9-D55E-4E85-AC50-0FF31B1CE50D} Logic.ProductionToProductMapper diff --git a/Common/CordonelAssemblyLine/Model/PickingModel.cs b/Common/CordonelAssemblyLine/Model/PickingModel.cs index 337331c8..d5c81a3b 100644 --- a/Common/CordonelAssemblyLine/Model/PickingModel.cs +++ b/Common/CordonelAssemblyLine/Model/PickingModel.cs @@ -1,4 +1,5 @@ -using Logic.ProductionToProductMapper.Cordonel; +using LaaPackages.Features.Cordonel.Models; +using Logic.ProductionToProductMapper.Cordonel; using Newtonsoft.Json; using System; using System.Collections.Generic; @@ -569,10 +570,10 @@ namespace CordonelAssemblyLine.Model meter.SetProcessState(DisplayCodes.PickingStarted); var ret = RunCheck(checkAppsIdVersion, frequency, meterSize, pressurePresent, meter); lblS08Color = _progressWaiting; + var sbMSG = new StringBuilder(); + if (ret) { - - if (!meter.WriteRegister("POWERMON_BatteryQuantity", 2, true, true)) { lblS08Text = "1"; @@ -582,55 +583,157 @@ namespace CordonelAssemblyLine.Model meter.WriteRegister("POWERMON_StoreConfiguration", 1, true); - - - var genesisStatus = new GenesisStatus(); + var requirements = new CordonelRequirements(); - // this calculates all life time values - if (!GenesisStatusHandler.BuildLifeTimeInformation(meter, genesisStatus, out _)) + if (GenesisStatusHandler.GetCordonelRequirementInfoFromDbByFANr(_order, requirements, out var error)) { - meter.WriteLog("Batterie nicht lesbar"); - lblS08Text = "Batterie nicht lesbar"; - lblS08Color = _progressError; - ret = false; - } - else - { - var sbMSG = new StringBuilder(); - sbMSG.AppendLine($"Pcb = {meter.PcbId}"); + genesisStatus.QuiescentCurrent_uA = requirements.QuiescentCurrent_uA; + genesisStatus.EstimatedProductionBatteryLoadPercent = requirements.EstimatedProductionBatteryLoadPercent; - sbMSG.AppendLine($"POWERMON_TotalUsedSeconds = {genesisStatus.ExceededLifeTime_s}"); - sbMSG.AppendLine($"POWERMON_TotalUsedCharge = {genesisStatus.DrainedBatteryLoad_uAs}"); - sbMSG.AppendLine($"POWERMON_BatteryQuantity = {genesisStatus.BatteryQuantity}"); - sbMSG.AppendLine($"POWERMON_BatteryMilliAHrRating = {genesisStatus.InitialBatteryLoad_mAh}"); - sbMSG.AppendLine(""); - sbMSG.AppendLine($"Remaining life time in years {genesisStatus.RemainingLifeTimeYears:F2}"); - sbMSG.AppendLine($"Totally drained battery load in % {genesisStatus.DrainedBatteryLoadPercent:F2}"); - if (genesisStatus.RemainingLifeTimeYears >= 21 || genesisStatus.DrainedBatteryLoadPercent <= 1) + if (GenesisStatusHandler.BuildLifeTimeInformation(meter, genesisStatus, out _)) { - lblS08Text = $"{genesisStatus.RemainingLifeTimeYears} Jahre"; + sbMSG.AppendLine($"Pcb = {meter.PcbId}"); + + sbMSG.AppendLine($"POWERMON_TotalUsedSeconds = {genesisStatus.ExceededLifeTime_s}"); + sbMSG.AppendLine($"POWERMON_TotalUsedCharge = {genesisStatus.DrainedBatteryLoad_uAs}"); + sbMSG.AppendLine($"POWERMON_BatteryQuantity = {genesisStatus.BatteryQuantity}"); + sbMSG.AppendLine($"POWERMON_BatteryMilliAHrRating = {genesisStatus.InitialBatteryLoad_mAh}"); + sbMSG.AppendLine(""); + sbMSG.AppendLine($"Remaining life time in years {genesisStatus.RemainingLifeTimeYears:F2}"); + sbMSG.AppendLine($"Totally drained battery load in % {genesisStatus.DrainedBatteryLoadPercent:F2}"); + + //restlaufzeit monate -RequiredLifeTimeYearsAssembly + + + var hasFehlern = false; + + // restlaufzeit monate - RequiredLifeTimeYearsAssembly + if (genesisStatus.RemainingLifeTimeYears < requirements.RequiredLifeTimeYearsAssembly) + { + lblS08Text = $"{nameof(genesisStatus.RemainingLifeTimeYears)}: " + + $"{genesisStatus.RemainingLifeTimeYears} < " + + $"{requirements.RequiredLifeTimeYearsAssembly}"; + lblS08Color = _progressError; + ret = false; + sbMSG.AppendLine($"{nameof(genesisStatus.RemainingLifeTimeYears)}: " + + $"{genesisStatus.RemainingLifeTimeYears} < " + + $"{requirements.RequiredLifeTimeYearsAssembly}"); + } + else sbMSG.AppendLine($"Restlaufzeit i.O."); + + + + + if (genesisStatus.AlternativeRequiredBatteryLoadPercent != null && + genesisStatus.AlternativeRequiredBatteryLoadPercent > requirements.MaxDrainedBatteryLoadPercentAssembly) + { + sbMSG.AppendLine($"{nameof(genesisStatus.AlternativeRequiredBatteryLoadPercent)}: " + + $"{genesisStatus.AlternativeRequiredBatteryLoadPercent} > " + + $"{requirements.MaxDrainedBatteryLoadPercentAssembly}"); + ret = false; + } + else sbMSG.AppendLine($"Alternative Batterieverbrauch Montage i.O."); + // max bat verbrauch - MaxDrainedBatteryLoadPercentAssembly + + if (genesisStatus.DrainedBatteryLoadPercent > requirements.MaxDrainedBatteryLoadPercentAssembly) + { + lblS08Text = $"{nameof(genesisStatus.DrainedBatteryLoadPercent)}: " + + $"{genesisStatus.DrainedBatteryLoadPercent} > " + + $"{requirements.MaxDrainedBatteryLoadPercentAssembly}"; + lblS08Color = _progressError; + ret = false; + sbMSG.AppendLine($"{nameof(genesisStatus.DrainedBatteryLoadPercent)}: " + + $"{genesisStatus.DrainedBatteryLoadPercent} > " + + $"{requirements.MaxDrainedBatteryLoadPercentAssembly}"); + } + else sbMSG.AppendLine($"Maximaler Batterieverbrauch Montage i.O."); + // lagerzeit - MaxStorageMonths + if (genesisStatus.StorageMonths > requirements.MaxStorageMonths) + { + lblS08Text = $"{nameof(genesisStatus.DrainedBatteryLoadPercent)}: " + + $"{genesisStatus.DrainedBatteryLoadPercent} > " + + $"{requirements.MaxDrainedBatteryLoadPercentAssembly}"; + lblS08Color = _progressError; + ret = false; + sbMSG.AppendLine($"{nameof(genesisStatus.StorageMonths)}: " + + $"{genesisStatus.StorageMonths} > " + + $"{requirements.MaxStorageMonths}"); + } + + else sbMSG.AppendLine($"Maximallagerzeit i.O."); + meter.WriteLog(sbMSG.ToString()); } + + + + + + + + + + + + + + + + + + + + + + + + + else { - lblS08Text = $"{genesisStatus.RemainingLifeTimeYears} Jahre"; + meter.WriteLog("Batterie nicht lesbar"); + lblS08Text = "Batterie nicht lesbar"; lblS08Color = _progressError; ret = false; } - if (_orderDetails.FrequencyIndicator == 0) - { - if ((342000000 + (genesisStatus.ExceededLifeTime_s * 77.7)) <= genesisStatus.DrainedBatteryLoad_uAs) - { - lblS08Text = $"UNT Limit überschritten"; - lblS08Color = _progressError; - ret = false; - } - } - meter.WriteLog(sbMSG.ToString()); + } + else + { + if (string.IsNullOrWhiteSpace(error)) error = "Fehler beim laden von Cordonel Freigaben"; + + + meter.WriteLog(error); + lblS08Text = error; + + + + + + + + + + + + + + + + + lblS08Color = _progressError; + ret = false; + } + + // this calculates all life time values } + if (!ret) + sbMSG.AppendLine($"Battery lifetime limits sind Übreschritten"); + else + sbMSG.AppendLine($"Battery lifetime limits sind OK"); + if (_skipProcessSteps == null || !_skipProcessSteps.SkipLUT) { diff --git a/Common/Hardware/Interfaces/Ports/SerialPorts/BaseSerialPort.cs b/Common/Hardware/Interfaces/Ports/SerialPorts/BaseSerialPort.cs index 6185afae..db7501b0 100644 --- a/Common/Hardware/Interfaces/Ports/SerialPorts/BaseSerialPort.cs +++ b/Common/Hardware/Interfaces/Ports/SerialPorts/BaseSerialPort.cs @@ -217,9 +217,7 @@ namespace Xylem.Common.Hardware.Interfaces.Ports.SerialPorts catch (Exception ex) { _byteDataLogger.Error(ex); - } - } @@ -228,7 +226,6 @@ namespace Xylem.Common.Hardware.Interfaces.Ports.SerialPorts { try { - //set receive interrupt threshold for immediate execution _serialPort.ReceivedBytesThreshold = 1; _serialPort.DataReceived += PhysicalDataReceived; @@ -259,6 +256,7 @@ namespace Xylem.Common.Hardware.Interfaces.Ports.SerialPorts throw new ApplicationException($"{Ident} {ex.Message}"); } } + /// /// Getting the base port /// diff --git a/Common/Hardware/WaterMeter/Genesis/GenesisCore/GenesisConfigReader.cs.bak b/Common/Hardware/WaterMeter/Genesis/GenesisCore/GenesisConfigReader.cs.bak deleted file mode 100644 index 518c6571..00000000 --- a/Common/Hardware/WaterMeter/Genesis/GenesisCore/GenesisConfigReader.cs.bak +++ /dev/null @@ -1,241 +0,0 @@ -namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore -{ - using Applications; - using Newtonsoft.Json; - using Newtonsoft.Json.Converters; - using Registers; - using Registers.DataTypes; - using Registers.Json; - using System; - using System.Collections.Generic; - using System.Globalization; - using System.IO; - using WaterMeterRegisters; - - /// - /// JSON filer reader for generation of register lists - /// - public class GenesisConfigurationReader - { - /// - /// Registers defined in configuration.json file - /// - public List ConfigRegistersDefinitions { get; } - = new List(); - - /// - /// Applications defined in configuration.json file - /// - public List ConfigApplicationDefinitions { get; } - = new List(); - - /// - /// Ctor - /// - public GenesisConfigurationReader() { } - - /// - /// Ctor - /// - /// the file path for configuration.json as interface description to the meter - public GenesisConfigurationReader(String configFilePath) - { - if (string.IsNullOrEmpty(configFilePath)) - { - throw new ApplicationException("JsonFileRegisterReader needs at least one file path"); - } - if (!File.Exists(configFilePath)) - { - throw new ApplicationException($" {configFilePath} doesn't exists"); - } - - BuildRegisterList(File.ReadAllText(configFilePath)); - } - - /// - /// Convert file content to register list - /// - /// - /// - /// - public void BuildRegisterList(String configurationJson) - { - IDictionary sections; - - try - { - sections = JsonConvert - .DeserializeObject>(configurationJson, SerializerSettings) - ?? new Dictionary(); - } - catch (Exception) - { - sections = new Dictionary(); - } - - foreach (var sectionKVP in sections) - { - var appId = sectionKVP.Value.Id; - var appName = sectionKVP.Key; - - ConfigApplicationDefinitions.Add(new ApplicationDefinition - { - AppId = appId, - AppName = appName - }); - - var section = sectionKVP.Value; - - var registers = section.Registers; - - if (registers is null) - { - continue; - } - - foreach (var registerKVP in registers) - { - var register = registerKVP.Value; - - if (register is null) - { - continue; - } - - var details = register.Details; - - if (details is null) - { - continue; - } - - var regId = register.Id; - - foreach (var detail in details) - { - var values = detail.Values; - - ConfigRegistersDefinitions.Add(new RegisterDefinition - { - AppAddress = appId, - AppName = appName, - DataType = GetType(detail.Type), - Default = values?.Default is Int64 d ? d : default(Int64?), - IsAvailable = default(Boolean), - Maximum = values?.Maximum is Int64 max ? max : default(Int64?), - Minimum = values?.Minimum is Int64 min ? min : default(Int64?), - RegAddressInApp = regId, - // RegisterAddress = new byte[] { appId, regId }, - RegisterDetail = detail, - RegisterName = registerKVP.Key, - RestoreCapability = new StaticType(detail.StaticType) - }); - } - } - } - } - - /// - /// Settings - /// - private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings - { - MetadataPropertyHandling = MetadataPropertyHandling.Ignore, - DateParseHandling = DateParseHandling.None, - Converters = - { - AccessConverter.Singleton, - new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } - }, - }; - - private static Type GetType(String value) - { - try - { - switch (value.ToLower()) - { - case "bool_t": return typeof(Boolean); - case "rpc": return typeof(Rpc); - case "string": return typeof(String); - case "uint32_t": return typeof(UInt32); - case "time_t": return typeof(TimeT); - case "status_t": return typeof(StatusT); - case "uint16_t": return typeof(UInt16); - case "uint8_t": return typeof(Byte); - case "enum8": return typeof(Enum8); - case "uint64_t": return typeof(UInt64); - case "uint96_t": return typeof(UInt96); - case "uint128_t": return typeof(UInt128); - case "int8_t": return typeof(SByte); - case "int32_t": return typeof(Int32); - case "int64_t": return typeof(Int64); - case "int16_t": return typeof(Int16); - default: throw new Exception($"Type {value} not recognized!"); - } - } - catch (Exception ex) - { - //throw ex; - return typeof(Boolean); - } - - } - } - - /// - /// - /// - public class AccessConverter : JsonConverter - { - /// - /// - /// - /// - /// - public override Boolean CanConvert(Type t) => t == typeof(Access) || t == typeof(Access?); - - /// - /// - /// - /// - /// - /// - /// - /// - public override Object ReadJson(JsonReader reader, Type t, Object existingValue, JsonSerializer serializer) - { - if (reader.TokenType == JsonToken.Null) - { - return null; - } - - var value = serializer.Deserialize(reader); - - return Enum.TryParse(value, true, out Access access) ? access : default(Access); - } - - /// - /// - /// - /// - /// - /// - public override void WriteJson(JsonWriter writer, Object untypedValue, JsonSerializer serializer) - { - if (untypedValue is Access access) - { - writer.WriteValue(access.ToString()); - } - else - { - throw new Exception("Cannot marshal type Lvl"); - } - } - - /// - /// - /// - public static readonly AccessConverter Singleton = new AccessConverter(); - } -} diff --git a/Common/Hardware/WaterMeter/Genesis/GenesisStatus/GenesisStatusHandler.cs b/Common/Hardware/WaterMeter/Genesis/GenesisStatus/GenesisStatusHandler.cs index 6490f1f8..c56ba52b 100644 --- a/Common/Hardware/WaterMeter/Genesis/GenesisStatus/GenesisStatusHandler.cs +++ b/Common/Hardware/WaterMeter/Genesis/GenesisStatus/GenesisStatusHandler.cs @@ -101,6 +101,78 @@ namespace Xylem.Common.Hardware.WaterMeter.Genesis.GenesisStatus return false; } + public static Boolean GetCordonelRequirementInfoFromDbByFANr(String fanr, CordonelRequirements prodRequirements, out string errorMsg) + { + errorMsg = ""; + if (null == prodRequirements || string.IsNullOrEmpty(fanr)) + { + return false; + } + + try + { + var url = ServiceUrls.GetCordonelRequirementByFANrInfoServiceUrl(fanr); + var response = LocalWebRequest.GetRequest(url, 30000, out var httpStatus); + if (httpStatus == HttpStatusCode.OK && !string.IsNullOrEmpty(response)) + { + var requirements = JsonConvert.DeserializeObject(response); + var type = typeof(CordonelRequirements); + foreach (var prop in type.GetProperties()) + { + if (prop.CanWrite) + prop.SetValue(prodRequirements, prop.GetValue(requirements, null), null); + } + + // For standard requirements the order number has to be set as those are neither PcbId based + // nor order number based + if (prodRequirements.ProductionOrderNr == null) + prodRequirements.ProductionOrderNr = prodRequirements.OuterProductionOrderNr; + return true; + } + } + catch (Exception e) + { + errorMsg = e.Message; + return false; + } + + return false; + } + + public static Boolean GetCordonelRequirementInfoFromDbByMeterSize(int size, CordonelRequirements prodRequirements, out string errorMsg) + { + errorMsg = ""; + + try + { + var url = ServiceUrls.GetCordonelRequirementByMeterSizeInfoServiceUrl(size); + var response = LocalWebRequest.GetRequest(url, 30000, out var httpStatus); + if (httpStatus == HttpStatusCode.OK && !string.IsNullOrEmpty(response)) + { + var requirements = JsonConvert.DeserializeObject(response); + var type = typeof(CordonelRequirements); + foreach (var prop in type.GetProperties()) + { + if (prop.CanWrite) + prop.SetValue(prodRequirements, prop.GetValue(requirements, null), null); + } + + // For standard requirements the order number has to be set as those are neither PcbId based + // nor order number based + if (prodRequirements.ProductionOrderNr == null) + prodRequirements.ProductionOrderNr = prodRequirements.OuterProductionOrderNr; + return true; + } + } + catch (Exception e) + { + errorMsg = e.Message; + return false; + } + + return false; + } + /// /// Get the calibration results for a meter from a test-bench calibration. /// diff --git a/Common/Hardware/WaterMeter/Genesis/Registers/RegisterConverter.cs.bak b/Common/Hardware/WaterMeter/Genesis/Registers/RegisterConverter.cs.bak deleted file mode 100644 index 76e866ef..00000000 --- a/Common/Hardware/WaterMeter/Genesis/Registers/RegisterConverter.cs.bak +++ /dev/null @@ -1,555 +0,0 @@ -using System; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using Xylem.Common.Hardware.WaterMeter.Genesis.Registers.DataTypes; - -namespace Xylem.Common.Hardware.WaterMeter.Genesis.Registers -{ - /// - /// Helper to convert genesis register values store in bytes to data types and back - /// - public static class RegisterConverter - { - /// - /// Convert single register from Genesis and return a message of the result. The value input is a byte array - /// with the LSB at the index 0 and the MSB at the highest index. A string is sorted with the first character - /// at index 0, this does not need to be reversed as it is readable by default. - /// The raw value is swapped byte-wise to get a human-readable value with MSB at leftmost and LSB at rightmost. - /// The message contains the register name, the swapped raw value and on the converted value. - /// - /// - /// the raw byte array is always % 4 0 padded for unused elements, the LSB is - /// on index 0 (little endian, LSB first) - /// message with register name, swapped raw value and converted value - /// - /// - Initial. - /// - /// - /// - Reworked. - /// - /// - /// - Avoid logging of encryption key. - /// - /// - /// - Hash password and encryption key with SHA256. - /// - public static String GetRegisterContentText(RegisterDefinition registerDefinition, Byte[] regRawByteArray) - { - String msg; - String registerName = "?"; - try - { - registerName = registerDefinition.GetIdent(); - // getting a result value as text of the data type e.g. UInt32 - var strValue = ConvertToText(regRawByteArray, registerDefinition.DataType); - // remove non-printable char of the converted result - var strValueResult = Regex.Replace(strValue, @"\p{C}+", string.Empty); - - // use hashed output being able to compare written and read back values - String strRawResult; - if (registerName.Contains("EncryptionKey") || registerName.Contains("Password")) - { - strRawResult = GetRegisterRawText(registerDefinition, regRawByteArray, encryptData:true); - msg = $"{registerName}: ({strRawResult})h"; - } - else - { - strRawResult = GetRegisterRawText(registerDefinition, regRawByteArray); - msg = $"{registerName}: ({strRawResult})h ({strValueResult})"; - } - } - catch (Exception) - { - throw new ApplicationException($"Cannot convert register {registerName}"); - } - - return msg; - } - - /// - /// Convert single register from Genesis and return a message of the result. The value input is a byte array - /// with the LSB at the index 0 and the MSB at the highest index. A string is sorted with the first character - /// at index 0, this does not need to be reversed as it is readable by default. - /// The raw value is swapped byte-wise to get a human-readable value with MSB at leftmost and LSB at rightmost. - /// The message contains the swapped raw value. - /// - /// - /// the raw byte array is always % 4 0 padded for unused elements, the LSB is - /// on index 0 (little endian, LSB first) - /// data encryption for data required SHA256 hash instead of clear text - /// message with swapped raw value - /// - /// - Initial. - /// - /// - /// - Hash password and encryption key with SHA256. - /// - public static String GetRegisterRawText(RegisterDefinition registerDefinition, Byte[] regRawByteArray, - Boolean encryptData = false) - { - String msg; - var strRawResult = "?"; - try - { - // inverse the raw value to get a readable byte order MSB left and LSB last right position - var tmpList = regRawByteArray.ToList(); - - // reverse the list if it is not a string or the UInt48, UInt72, UInt88,UInt96 or UInt128 which - // will be used as placeholder for a string - if (registerDefinition.DataType != typeof(String) && - registerDefinition.DataType != typeof(UInt48) && - registerDefinition.DataType != typeof(UInt72) && - registerDefinition.DataType != typeof(UInt88) && - registerDefinition.DataType != typeof(UInt96) && - registerDefinition.DataType != typeof(UInt128)) - { - tmpList.Reverse(); - } - - // use hashed output being able to compare written and read back values - if (encryptData) - { - var hash = SHA256.Create().ComputeHash(regRawByteArray); - strRawResult = BitConverter.ToString(hash.ToArray()); - msg = $"SHA256 - {strRawResult}"; - } - else - { - strRawResult = BitConverter.ToString(tmpList.ToArray()); - msg = $"{strRawResult}"; - } - } - catch (Exception) - { - msg = $"{strRawResult}"; - } - - return msg; - } - - /// - /// Preset the raw byte array with the default value. - /// - /// - /// - /// true if value could be set - /// - /// - Initial. - /// - public static Boolean SetToDefault(RegisterDefinition registerDefinition, out Byte[] regRawByteArray) - { - if (registerDefinition.Default.HasValue) - { - // will always return an Int64 value Byte[8] ! - regRawByteArray = ValueToByteArray(registerDefinition.Default); - return true; - } - - regRawByteArray = new Byte[] {0}; - return false; - } - - /// - /// Convert a value (T) into byte[] - /// - /// Type to convert from - /// value to convert - /// byte[] like it store in genesis meter - /// - /// - Init. - /// - /// - /// - Used to calculate time in UTC based on 01. Jan 2000 - /// and the given offset in seconds. - /// - public static Byte[] ValueToByteArray(T value) - { - var converted = new Byte[] { 0 }; - if (value == null) - return converted; - - if (value.GetType() == typeof(TimeT)) - { - var teaTime = value as TimeT; - if (teaTime != null) - { - // the value contains always the seconds since 01.Jan 2000 - var intValue = Convert.ToInt32(teaTime.SecondsSince2000); - return BitConverter.GetBytes(intValue); - } - } - - if (value is Boolean) - { - var tmp = Convert.ToBoolean(value); - return BitConverter.GetBytes(tmp); - } - - if (value is UInt16) - { - var tmp = Convert.ToUInt16(value); - return BitConverter.GetBytes(tmp); - } - - if (value is UInt32) - { - var tmp = Convert.ToUInt32(value); - return BitConverter.GetBytes(tmp); - } - - if (value is UInt64) - { - var tmp = Convert.ToUInt64(value); - return BitConverter.GetBytes(tmp); - } - - if (value is Int16) - { - var intValue = Convert.ToInt16(value); - return BitConverter.GetBytes(intValue); - } - - if (value is Int32) - { - var intValue = Convert.ToInt32(value); - return BitConverter.GetBytes(intValue); - } - - if (value is Int64) - { - var tmp = Convert.ToInt64(value); - return BitConverter.GetBytes(tmp); - } - - if (value is String) - { - return Encoding.ASCII.GetBytes(value.ToString()); - } - - if (value is Byte || value is Enum8) - { - converted[0] = Convert.ToByte(value); - } - else if (value is SByte) - { - return BitConverter.GetBytes(Convert.ToSByte(value)); - } - - else if (value is Byte[]) - { - return (Byte[])Convert.ChangeType(value, typeof(Byte[])); - } - else - { - throw new ApplicationException($"Data type {typeof(T)} not implemented"); - } - - return converted; - } - - /// - /// Get size of type - /// - /// - /// size in bytes - /// - /// - Init. - /// - public static Int32 SizeOf(RegisterDefinition registerDefinition) - { - var size = 4; - - if (registerDefinition.DataType == typeof(Boolean)) - { - size = sizeof(Boolean); - } - if (registerDefinition.DataType == typeof(Byte) || - registerDefinition.DataType == typeof(SByte) || - registerDefinition.DataType == typeof(Char) || - registerDefinition.DataType == typeof(Enum8)) - { - size = sizeof(Byte); - } - else if (registerDefinition.DataType == typeof(Int16) || - registerDefinition.DataType == typeof(UInt16)) - { - size = sizeof(Int16); - } - else if (registerDefinition.DataType == typeof(Int32) || - registerDefinition.DataType == typeof(UInt32) || - registerDefinition.DataType == typeof(TimeT)) - { - size = sizeof(Int32); - } - - else if (registerDefinition.DataType == typeof(Int64) || - registerDefinition.DataType == typeof(UInt64)) - { - size = sizeof(Int64); - } - - else if (registerDefinition.DataType == typeof(UInt48)) - { - // 48 Bits / 8 Bits/Byte - size = 6; - } - - else if (registerDefinition.DataType == typeof(UInt72)) - { - // 72 Bits / 8 Bits/Byte - size = 9; - } - - else if (registerDefinition.DataType == typeof(UInt88)) - { - // 88 Bits / 8 Bits/Byte - size = 11; - } - - else if (registerDefinition.DataType == typeof(UInt96)) - { - // 96 Bits / 8 Bits/Byte - size = 3 * 4; - } - - else if (registerDefinition.DataType == typeof(UInt128)) - { - // 128 Bits / 8 Bits/Byte - size = 4 * 4; - } - - else if (registerDefinition.DataType == typeof(String)) - { - // just some value - size = 6 * 4; - } - - return size; - } - - /// - /// Build the result of the array as text. - /// - /// byte value for conversion - /// type of the result - /// - /// - /// - Init. - /// - /// - /// - Used to calculate time in UTC based on 01. Jan 2000 - /// and the given offset in seconds. - /// - public static String ConvertToText(Byte[] rawByteArray, Type type) - { - try - { - if (type == typeof(Boolean)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - - if (type == typeof(TimeT)) - { - var teaTime = ByteArrayToValue(rawByteArray); - return teaTime.ToString(); - } - if (type == typeof(UInt16)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - if (type == typeof(UInt32)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - if (type == typeof(UInt64)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - if (type == typeof(Int16)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - if (type == typeof(Int32)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - if (type == typeof(Int64)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - if (type == typeof(Byte) || type == typeof(Enum8)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - if (type == typeof(UInt48)) - { - return ""; - } - if (type == typeof(UInt72)) - { - return ""; - } - if (type == typeof(UInt88)) - { - return ""; - } - if (type == typeof(UInt96)) - { - return ""; - } - if (type == typeof(UInt128)) - { - return ""; - } - if (type == typeof(SByte)) - { - return ByteArrayToValue(rawByteArray).ToString(); - } - - return ByteArrayToValue(rawByteArray); - } - catch (Exception) - { - return ""; - } - - } - - - /// - /// convert form byte (meter) to data type - /// - /// Type to cast in - /// byte value for conversion - /// converted value - /// - /// - Init. - /// - /// - /// - Used to calculate time in UTC based on 01. Jan 2000 - /// and the given offset in seconds. - /// - String removed from first zero in string until the end to avoid ghost signs! - /// - public static T ByteArrayToValue(Byte[] rawByteArray) - { - try - { - Object convertedObj; - var type = typeof(T); - - if (type == typeof(Boolean)) - { - convertedObj = BitConverter.ToBoolean(rawByteArray, 0); - } - else if (type == typeof(UInt16)) - { - convertedObj = BitConverter.ToUInt16(rawByteArray, 0); - } - else if (type == typeof(UInt32)) - { - convertedObj = BitConverter.ToUInt32(rawByteArray, 0); - } - else if (type == typeof(UInt64)) - { - convertedObj = BitConverter.ToUInt64(rawByteArray, 0); - } - else if (type == typeof(UInt48)) - { - return default(T); - } - else if (type == typeof(UInt72)) - { - return default(T); - } - else if (type == typeof(UInt88)) - { - return default(T); - } - else if (type == typeof(UInt96)) - { - return default(T); - } - else if (type == typeof(UInt128)) - { - return default(T); - } - else if (type == typeof(Int16)) - { - convertedObj = BitConverter.ToInt16(rawByteArray, 0); - } - else if (type == typeof(Int32)) - { - convertedObj = BitConverter.ToInt32(rawByteArray, 0); - } - else if (type == typeof(Int64)) - { - convertedObj = BitConverter.ToInt64(rawByteArray, 0); - } - else if (type == typeof(Byte) || type == typeof(Enum8)) - { - convertedObj = rawByteArray[0]; - } - else if (type == typeof(SByte)) - { - // set all others to 0 as only the LSB is of interest - for (var idx = 1; idx < rawByteArray.Length; idx++) - rawByteArray[idx] = 0; - convertedObj = Convert.ToSByte((SByte)rawByteArray[0]); - } - else if (type == typeof(Boolean)) - { - convertedObj = Convert.ToBoolean(rawByteArray[0]); - } - else if (type == typeof(String)) - { - // the value may contain zeros at the beginning of the value-record, these have to be removed - var zeroPaddingCounter = 0; - while (rawByteArray.Length > zeroPaddingCounter && rawByteArray[zeroPaddingCounter] == 0) - zeroPaddingCounter += 1; - var trimmedValue = new Byte[rawByteArray.Length - zeroPaddingCounter]; - Int32 i; - for (i = 0; i < rawByteArray.Length - zeroPaddingCounter; i++) - trimmedValue[i] = rawByteArray[i + zeroPaddingCounter]; - - // as a string is terminated with a zero all following elements after including the initial - // zero have to be removed. This is caused due to the 4 byte chunks which will be sent. - var validCharCtr = 0; - // find the first zero in the trimmed value array - while (trimmedValue.Length > validCharCtr && trimmedValue[validCharCtr] != 0) - validCharCtr += 1; - // reserve space for valid chr plus the trailing 0 which will be added if - var rawResult = new Byte[validCharCtr + 1]; - for (i = 0; i < validCharCtr; i++) - rawResult[i] = trimmedValue[i]; - if (validCharCtr < trimmedValue.Length) - { - rawResult[i] = 0; - convertedObj = Encoding.ASCII.GetString(rawResult); - } - else - { - convertedObj = Encoding.ASCII.GetString(trimmedValue); - } - } - else if (type == typeof(TimeT)) - { - // the value contains always the seconds since 01.Jan 2000 - convertedObj = new TimeT { SecondsSince2000 = ByteArrayToValue(rawByteArray) }; - } - else - { - throw new ApplicationException($"Data type {type} not implemented"); - } - - return (T)Convert.ChangeType(convertedObj, type); - } - catch (Exception) - { - return default(T); - } - } - } -} \ No newline at end of file diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/MagFluxConfig.csproj.bak b/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/MagFluxConfig.csproj.bak deleted file mode 100644 index 7df7d4b8..00000000 --- a/Common/Hardware/WaterMeter/MagFlux/MagFluxConfig/MagFluxConfig.csproj.bak +++ /dev/null @@ -1,71 +0,0 @@ - - - - - Debug - AnyCPU - {70398B99-B134-4BBD-968B-7399B70C3CE2} - Library - Properties - Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxConfig - Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxConfig - v4.8 - 512 - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll - - - ..\..\..\..\packages\NLog.5.2.2\lib\net46\NLog.dll - - - - - - - - - - - - - - - - - - - - - - - - {2E139F63-B6FE-4EA9-A098-85364FE9B26C} - PortCore - - - {63E0AC5E-B7C8-4363-A2FE-BE489E648FF0} - TransmitProtocol - - - - \ No newline at end of file diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxCore.csproj.bak b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxCore.csproj.bak deleted file mode 100644 index 74ec0df8..00000000 --- a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxCore.csproj.bak +++ /dev/null @@ -1,140 +0,0 @@ - - - - - Debug - AnyCPU - {B5DA260C-71CC-45CA-B79E-D1B376AF718C} - Library - Properties - Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore - Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore - v4.8 - 512 - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll - - - ..\..\..\..\packages\NLog.5.2.2\lib\net46\NLog.dll - - - - - - - - - - - - - - - - - - - - - - - - - {9eb1f659-6f73-4f65-bcab-4114fd94f5fc} - CommonCore.Configuration - - - {1b02c79e-0b19-43e2-8f6b-71ef0c786c97} - CommonCore - - - {94ca71f3-c5d7-4ec6-ba47-fa8eea3c9406} - ThreadWatcher - - - {6ccdb656-c676-4360-baba-c4596aad175d} - Measurements - - - {a33e3c6d-eaae-4a20-a0ee-f9e6922fd029} - SoftwareAccessHelper - - - {20f137fd-c25e-42b7-a68f-58c746475897} - Tools.JsonToXlsHelper - - - {4b88b0d3-e791-4774-9521-eabeacdc420e} - Logging - - - {2e139f63-b6fe-4ea9-a098-85364fe9b26c} - PortCore - - - {72037e89-4f63-4b3f-beff-4138e578ce99} - SerialPorts - - - {8BDD2789-96D4-43EA-AAD7-0F49D0347998} - ProtocolCore - - - {63e0ac5e-b7c8-4363-a2fe-be489e648ff0} - TransmitProtocol - - - {04201E95-90A0-4B73-A72F-379739B2A3AE} - GenesisCore - - - {8203abb8-38e5-472e-a742-33f38b7a74a6} - WaterMeterCore - - - {26afcf1e-1287-48b8-a506-32b1e8a0dd0e} - WaterMeterRegisters - - - {BA17D20E-0CEB-4B27-9772-2392BD750ED5} - DataPackages - - - {70398b99-b134-4bbd-968b-7399b70c3ce2} - MagFluxConfig - - - {00748F11-4B49-4D8B-93C4-4A11A210CCE2} - RequestProtocol - - - {d6b81c60-2763-4c4d-989f-90822f53b01a} - StreamingProtocol - - - - - - - - \ No newline at end of file diff --git a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxMeter.cs.bak b/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxMeter.cs.bak deleted file mode 100644 index 7d0f22e2..00000000 --- a/Common/Hardware/WaterMeter/MagFlux/MagFluxCore/MagFluxMeter.cs.bak +++ /dev/null @@ -1,1408 +0,0 @@ -using System; -using NLog; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using Newtonsoft.Json; -using Xylem.Common.CommonCore.Consts; -using Xylem.Common.Hardware.Interfaces.Ports.PortCore; -using Xylem.Common.Hardware.Interfaces.Ports.PortCore.EventArguments; -using Xylem.Common.Hardware.Interfaces.Ports.SerialPorts; -using Xylem.Common.Hardware.Interfaces.Protocols.ProtocolCore; -using Xylem.Common.Hardware.Interfaces.Protocols.ProtocolCore.EventArguments; -using Xylem.Common.Hardware.Interfaces.Protocols.TransmitProtocol; -using Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.DataTypes; -using Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol; -using Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.EventArguments; -using Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.MeasurementRecords; -using Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxConfig; -using Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore.Consts; -using Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol; -using Xylem.Common.Hardware.WaterMeter.WaterMeterCore; -using Xylem.Common.Hardware.WaterMeter.WaterMeterCore.Consts; -using Xylem.Common.Metrology.Measurements; -using Xylem.Common.Metrology.Measurements.Consts; -using Xylem.Common.Utils.Logging; - - -namespace Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore -{ - /// - /// - /// MagFlux meter is the core class for the MJK MagFlux water meter. - /// One meter always is always linked to two port, one for communication and one for LED streaming. - /// - public class MagFluxMeter : IMeter, IMeterEvents - { - #region Variables and Properties - - /// - /// Ident of request protocol - /// - private String RequestIdent - { - get; - set; - } - /// - /// Reminder for status bits - /// - private UInt32 _lastStatusBits; - /// - /// Mark the streaming catcher as active - /// - private Boolean _streamingCatcherIsActive; - - /// - /// Enable raw record logging, if set every incoming package will be logged - /// - private Boolean _enableRawDataLogging; - - /// - /// Simulated flow activity - /// - public Boolean SimulatedFlowIsActive - { - get; - private set; - } - /// - /// Empty pipe ignore - /// - public Boolean IgnoreEmptyPipeDetection - { - get; - private set; - } - /// - /// to reduce the IrdA communication in test bench, preparation will be done once (when SkipPreparationForTestBench is true) - /// - public Boolean SkipPreparationForTestBench - { - get; set; - } - /// - /// List of ongoing measurements, base- and calibration-measurements - /// - private List _listOfIMeasurement = new List(); - - /// - /// Quality watch mode can be used to decode intermediate records and check - /// for actual quality of the measurements. - /// - public Boolean QualityWatchMode - { - get; - set; - } - - /// - /// Represent FW version - /// - public String FwVersion - { - get; - private set; - } = "?"; - - /// - /// Represent meter size in mm - /// - public Int32 MeterSizeMm - { - get; - private set; - } - - /// - /// Represent FW version - /// - public String FwBuildDate - { - get; - private set; - } = "?"; - - /// - /// Represent FW GIT hash - /// - public String FwGitHash - { - get; - private set; - } = "?"; - - /// - /// Represent MagFlux API Version - /// - public String MagFluxRegisterApiVersion - { - get; - private set; - } = "?"; - - - /// - /// Represent sensor serial number - /// - public String SensorSerialNo - { - get; private set; - } - - /// - /// Average of the electrode in milli Volts - /// - public Single AverageElectrode_mV - { - get; private set; - } - - /// - /// Standard deviation of the electrode in milli Volts - /// - public Single StandardDeviationElectrode_mV - { - get; private set; - } - - /// - /// Represents Empty Pipe Detection control bits - /// Bit0="EPD disabled", 1="Enabled w. Flags only", 2="EPD enabled full" - /// - public Int32 EpdControlBits - { - get; private set; - } - - /// - /// Represent pcb calibration - /// - public Single BoardCalib - { - get; private set; - } - - /// - /// Represent pcb identification - /// - public String PcbId - { - get; private set; - } - - /// - /// Represent unique id - /// - public String UniqueId - { - get; private set; - } - - private String _currentActionText = ""; - /// - /// Hold the current process name e.g. FlowTest, Preadjustment for logging - /// - public String CurrentActionText - { - get => _currentActionText; - set - { - _currentActionText = value; - SetLogger(); - } - } - - ///// - ///// Add on ctor a password and it will be used for login in if no other password is set - ///// - //private String _password; - - /// - /// request port assignment/info - /// - private IPort RequestPort - { - get; - set; - } - - /// - /// request protocol assignment/info - /// - private RequestProtocol RequestProtocol; - - /// - /// streaming port assignment/info - /// - private IPort StreamingPort - { - get; - set; - } - - /// - /// streaming protocol assignment/info - /// - private StreamingProtocol StreamingProtocol; - - /// - public String SerialNumber - { - get; set; - } - - /// - /// do not use it to set ProcessStatus - /// if you want to change ProcessStatus of this genesis use - /// is just store for some routines - /// - private ProcessState _myProcessStatus; - - /// - /// if state is change - /// - /// will be invoked. - /// on some states other events will be invoke as well - public ProcessState ProcessStatus - { - get => _myProcessStatus; - - private set - { - if (_myProcessStatus == value) - { - return; - } - - _myProcessStatus = value; - Invoker(OnProcessStatusChanged); - switch (value) - { - case ProcessState.InitIsActive: - Invoker(OnInitCompleted); - break; - case ProcessState.MeasurementIsActive: - Invoker(OnMeasurementInitCompleted); - break; - case ProcessState.MeasurementIsDone: - Invoker(OnMeasurementCompleted); - break; - case ProcessState.CalibrationIsActive: - Invoker(OnCalibInitCompleted); - break; - case ProcessState.CalibrationIsDone: - Invoker(OnCalibCompleted); - break; - case ProcessState.QRefDone: - case ProcessState.WaitForQRef: - case ProcessState.WaitForCalibration: - case ProcessState.WaitForMeasurement: - case ProcessState.IsNotInit: - //no extra event needed - break; - default: - throw new OverflowException("MagFlux measurement unknown process status"); - } - } - } - - public Boolean IsLoggedOn - { - private set; - get; - } - - /// - public Int32 Slot - { - get; set; - } - - /// - public Int32 IntermediateUpdateTimeS - { - get; - set; - } = CommunicationConfig.MeasurementUpdateTimeS; - - - /// - /// Process configuration - /// - public ProcessConfig Configuration = new ProcessConfig(); - - /// - /// Transmit protocol access for underlie objects to change response timeout - /// - private ITransmitProtocol TransmitProtocol; - - //initially do not signal event - private readonly AutoResetEvent _onSyncKeepSessionThread = new AutoResetEvent(false); - private Thread _keepSessionThread; - private readonly CancellationTokenSource _keepSessionToken = new CancellationTokenSource(); - - private ILogger _logger; - //private ILogger _loggerRawData; - - #endregion - - #region Events - - event EventHandler IMeter.OnDisposeCompleted - { - add - { - // throw new NotImplementedException(); - } - - remove - { - // throw new NotImplementedException(); - } - } - //public event EventHandler HasInformationForCaller; - - /// - public event EventHandler OnCalibCompleted; - - /// - public event EventHandler OnErrorStatusChanged; - - /// - public event EventHandler OnProcessStatusChanged; - - /// - public event EventHandler OnCalibInitCompleted; - - /// - public event EventHandler OnInitCompleted; - - /// - public event EventHandler OnMeasurementInitCompleted; - - /// - public event EventHandler OnMeasurementCompleted; - - /// - /// Response received after request for record - /// - public event EventHandler OnRequestRecordReceived; - - /// - /// Streaming record is decoded - /// - public event EventHandler OnStreamingRecordDecoded; - - ///// - ///// call this if session is expired and you need an re-authorization - ///// - //public EventHandler AuthorizationRequired; - - /// - /// A helper to invoke events only if someone is listening, otherwise nothing will happen - /// - /// Event handler to call - /// Sender (can be null) - /// Event arguments (can be null) - private void Invoker(EventHandler handler, Object sender = null, EventArgs e = null) - { - if (handler != null) - { - if (sender == null) - { - sender = this; - } - - if (e == null) - { - e = new EventArgs(); - } - - handler.Invoke(sender, e); - } - // ReSharper disable once RedundantIfElseBlock - else - { - //nobody is listening - } - } - - /// - /// Track all incoming led record packages (Calibration and Flow) - /// - /// - /// - /// I should be - /// otherwise this method does nothing - /// - private void StreamingProtocol_ApplyDecodedRecord(Object sender, BaseDataEventArgs e) - { - var result = e.GetEventData(); - if (result is IMeasurementRecord measurementRecord) - { - if (measurementRecord is MagFluxRecord record) - { - if (!record.IsValid) - { - return; - } - - if (record.StatusBits != _lastStatusBits) - { - _lastStatusBits = record.StatusBits; - _logger.Debug($"{RequestIdent} {StateDef.GetStateInfosOfStateMask(record.StatusBits)}"); - } - } - - AddData(measurementRecord); - } - } - - /// - /// tracking request record processing - /// - /// - /// - private void RequestProtocol_ApplyDecodedRecord(Object sender, BaseDataEventArgs e) - { - if (e is RequestResponseDataEventArgs) - { - OnRequestRecordReceived?.Invoke(sender, (RequestResponseDataEventArgs)e); - } - } - - /// - /// Kick off the streaming catcher. - /// - public void StartStreamingCatcher() - { - if (_streamingCatcherIsActive) - { - return; - } - if (!(StreamingPort is LedSerialPort)) - { - throw new ApplicationException("No valid streaming port"); - } - - SyncStreamingBuffer(SyncMarkRecord.DecodeEveryPackage); - StreamingProtocol.OnRecordIsDecoded += StreamingCatcher_OnRawRecordReceived; - LogRawData(true); - _streamingCatcherIsActive = true; - } - - /// - /// Cyclic execution of catcher on incoming events. - /// - /// - /// - private void StreamingCatcher_OnRawRecordReceived(Object sender, BaseDataEventArgs e) - { - OnStreamingRecordDecoded?.Invoke(this, (MagFluxFlowDataEventArgs)e); - } - - /// - /// Stop the streaming catcher. - /// - /// - public void StopStreamingCatcher() - { - if (StreamingPort == null || !(StreamingPort is LedSerialPort)) - { - throw new ApplicationException("No valid streaming port"); - } - LogRawData(false); - StreamingProtocol.OnRecordIsDecoded -= StreamingCatcher_OnRawRecordReceived; - SyncStreamingBuffer(SyncMarkRecord.SkipDecoding); - _streamingCatcherIsActive = false; - } - - #endregion - - #region class handling - - /// - /// Ctor - default - /// - /// - /// - Initial - /// - public MagFluxMeter() - { - } - - /// - public void Dispose() - { - WriteLog("Start to dispose"); - - StreamingProtocol.OnRecordIsDecoded -= StreamingProtocol_ApplyDecodedRecord; - RequestProtocol.OnRecordIsDecoded -= RequestProtocol_ApplyDecodedRecord; - - LogRawData(false); - LogManager.Flush(); - //isPart of Logout - //StopKeepSession(); - - //Cancel receive tokens - _keepSessionToken?.Cancel(); - - try - { - Logout(); - } - catch (Exception) - { - // ignored - } - - - //Run thread again to notice CancellationToken has changed - _onSyncKeepSessionThread?.Set(); - - //this timeout counter is being used for dispose only - var timeoutCounter = 100; - if (_keepSessionThread != null) - { - while (_keepSessionThread.ThreadState != ThreadState.Stopped && timeoutCounter > 0) - { - Thread.Sleep(1); - timeoutCounter -= 1; - } - - if (_keepSessionThread.ThreadState != ThreadState.Stopped) - { - //if thread is still running try to abort - // try to avoid abort (takes age to run and is not safe) - _keepSessionThread.Abort(); - } - } - - _keepSessionThread = null; - - RequestPort?.Dispose(); - StreamingPort?.Dispose(); - - RequestProtocol?.Dispose(); - StreamingProtocol?.Dispose(); - WriteLog("Dispose is finished"); - } - - - ///// - ///// Ctor - ///// - ///// Slot number for test-bench - ///// for request Port - ///// for streaming Port - ///// don´t send CRC error or telegrams with error flag to caller - ///// - ///// If you have a password for highest access level you need, if you don't want to access the meter - ///// (just read led record) than you can leave it null - ///// - ///// - ///// - Initial - ///// - //public MagFluxMeter(Int32 slot, PortConfig? requestPort, PortConfig? streamingPort, - // Boolean ignoreCorruptedData = true, String password = null) - //{ - // _logger = NLogHelper.CreateOrGetMultiLogger($"Slot:{slot}", "Slot", "Meter", "MeterBase", "MeterBase"); - // SetupMagFluxMeter(slot, requestPort, streamingPort, ignoreCorruptedData, password); - //} - - #endregion - - #region MagFlux handling - /// - /// just internal setup. called on ctor or from vb6 setup function - /// - /// Slot Number for test-bench - /// for RFID/UART/IrDA Port - /// for LED Port - /// don´t send CRC error or telegrams with error flag to caller - /// - /// If you have a password for highest access level you need, if you don't want to access the meter - /// (just read led record) than you can leave it nullS - /// - private void SetupMagFluxMeter(Int32 slot, PortConfig? requestPort, PortConfig? streamingPort, - Boolean ignoreCorruptedData = true, String password = "") - { - Slot = slot; - //_password = password; - - if (requestPort != null) - { - if (requestPort.Value.Type == "Xylem.Common.Hardware.Interfaces.Ports.SerialPorts.UartSerialPort") - { - RequestIdent = $"Slot:{Slot}, Port:{requestPort.Value.PortName}, Protocol:Request, Type:UART -"; - - RequestProtocol = new RequestProtocol(RequestIdent); - TransmitProtocol = new UartTransmitProtocol(requestPort.Value.PortName); - //RequestProtocol.SetTransmitProtocol(TransmitProtocol); - - // request port is needed to assign the port name from file, else it is not used - // as the IMagFluxRequestProtocol implements the port handling and communication - RequestPort = new UartSerialPort(RequestIdent, requestPort.Value.GetSerialPort(), - TransmitProtocol.GetTransmitPortSettings()); - } - } - - if (streamingPort != null) - { - var ledTransmit = new LedTransmitProtocol(streamingPort.Value.PortName); - - var streamingIdent = $"Slot:{Slot}, Port:{streamingPort.Value.PortName}, Protocol:Streaming, Type:LED -"; - - StreamingPort = new LedSerialPort(streamingIdent, streamingPort.Value.GetSerialPort(), - ledTransmit.GetTransmitPortSettings()); - StreamingProtocol = new StreamingProtocol(streamingIdent, ignoreCorruptedData); - } - Configuration = new ProcessConfig(ProgramConfig.ConfigFileName); - - SetLogger(); - WriteLog("Setup done"); - } - - /// - /// - /// Start Event listening, has to be called after - /// - public void ConnectMeter() - { - if (RequestPort != null && RequestPort.GetPortName() != BaseSerialPort.PortNotAssigned) - { - if (RequestProtocol.Connect(RequestPort.GetPortName())) - { - WriteLog("RequestPort and RequestProtocol linked"); - RequestProtocol.OnRecordIsDecoded += RequestProtocol_ApplyDecodedRecord; - RequestProtocol.CloseConnection(); - } - else - { - WriteLog("RequestPort Connection failed"); - } - } - if (StreamingPort != null && StreamingPort.GetPortName() != BaseSerialPort.PortNotAssigned) - { - LinkPortToProtocol(StreamingPort, StreamingProtocol); - WriteLog("StreamingPort and StreamingProtocol linked"); - StreamingProtocol.OnRecordIsDecoded += StreamingProtocol_ApplyDecodedRecord; - } - - WriteLog("Connected and communication started"); - } - - /// - /// Add a port to working queue - /// - /// On should one once added in runtime - /// - private static void LinkPortToProtocol(IPort port, IProtocol protocol) - { - //for streaming mode only - if (port == null) - { - return; - } - - port.OnRawRecordReceived += delegate (Object o, BasePortDataEventArgs rawMsg) - { - protocol.FillDecodingBuffer(rawMsg); - }; - try - { - if (!port.IsOpen()) - { - port.Open(); - } - } - catch (Exception ex) - { - throw new ApplicationException($"Cannot Open Comport. Check TaskManager for other Genesis relevant programs and close them. Also check if the comport is valid! { Environment.NewLine }{ ex.Message}"); - } - - protocol.OnRecordReadyToSend += delegate (Object o, BasePortDataEventArgs dataToSend) - { - var data = (List)dataToSend.GetData(); - port.PortWrite(data.ToArray()); - }; - } - - /// - /// Synchronization of the record for the streaming interface - /// - /// - /// - private void SyncStreamingBuffer(SyncMarkRecord markRecord) - { - if (StreamingPort == null) - { - throw new ApplicationException("Synchronization not possible due to undefined streaming port"); - } - - StreamingPort.SynchronizeReceiveBuffer(markRecord); - } - - private void RequestProtocol_AuthorizationGrant(Object sender, EventArgs e) - { - WriteLog("Authorization succeeded"); - } - - public void SetupFromConfigFile(Int32 slot, Boolean ignoreCorruptedData = true) - { - SetupFromConfigFile(slot, ignoreCorruptedData, true, true); - } - - - /// - /// Copy list of flow results to and kick off the - /// writing of calibrations to MagFlux. - /// - /// List of flow results - public void WriteCalibrationTestBench(List results) - { - if (RequestProtocol == null) return; - var calibrationsCmPerH = new List(); - var calibrationCmPerH = new Calibration(); - foreach (var result in results) - { - calibrationCmPerH.refFlowRate = (Single)result.MeasuredRefFlowQmPerH; - calibrationCmPerH.dutFlowRate = (Single)result.MeasuredDutFlowQmPerH; - calibrationsCmPerH.Add(calibrationCmPerH); - } - WriteLog("Test bench calibration values received"); - - WriteCalibration(calibrationsCmPerH); - ReadCalibration(out _); - - - } - - /// - void IMeter.SetupFromConfigFile(Int32 slot, Boolean ignoreCorruptedData, Boolean useRequest, Boolean useStreaming) - { - SetupFromConfigFile(slot, ignoreCorruptedData); - } - /// - /// Setup water meter from configuration file: - /// -slot, - /// -streaming protocol, - /// -streaming port - /// -request port - /// - /// - /// - /// - /// - /// - private void SetupFromConfigFile(Int32 slot, Boolean ignoreCorruptedData, Boolean useRequest, Boolean useStreaming) - { - Slot = slot; - var configFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), nameof(MagFlux), ProgramConfig.SerialConfigFileName); - - if (!File.Exists(configFile)) - { - configFile = Path.Combine(ProgramConfig.SerialConfigFileName); - if (!File.Exists(configFile)) - { - throw new ApplicationException($"Configuration file {configFile} not found "); - } - } - var tr = new StreamReader(configFile); - var slotConfigList = JsonConvert.DeserializeObject(tr.ReadToEnd()); - - if (slotConfigList != null) - { - var slotConfig = slotConfigList.FirstOrDefault(t => t.Slot == slot); - - if (slotConfig == null) - { - throw new ApplicationException($"Slot:{slot} - File " + - $"{ProgramConfig.SerialConfigFileName} does not contain valid configuration"); - } - if (!useRequest) - { - SetupMagFluxMeter(slot, null, slotConfig.Streaming, ignoreCorruptedData); - } - else if (!useStreaming) - { - SetupMagFluxMeter(slot, slotConfig.Request, null, ignoreCorruptedData); - } - else - { - SetupMagFluxMeter(slot, slotConfig.Request, slotConfig.Streaming, ignoreCorruptedData); - } - } - - WriteLog("Configuration loaded"); - } - - /// - public Boolean Logout() - { - RequestProtocol.CloseConnection(); - IsLoggedOn = false; - return true; - } - - /// - /// - /// - Unique Id introduced, - /// - Sensor Serial number mapped as PcbId. - /// - /// - /// -Introduced readout of calibration values. - /// - public Boolean Login() - { - if (RequestProtocol == null) - return false; - - if (!RequestProtocol.Connect(RequestPort.GetPortName())) - return IsLoggedOn; - - IsLoggedOn = true; - if (RequestProtocol.GetFirmwareVersion(out var fwVersion)) - { - FwVersion = fwVersion; - } - if (RequestProtocol.GetFwBuildDate(out var fwBuildDate)) - { - FwBuildDate = fwBuildDate; - } - if (RequestProtocol.GetMeterSizeMm(out var meterSizeMm)) - { - MeterSizeMm = meterSizeMm; - } - if (RequestProtocol.GetFwGitHash(out var gitHash)) - { - FwGitHash = gitHash; - } - if (RequestProtocol.GetApiRegisterVersion(out var apiRegisterVersion)) - { - MagFluxRegisterApiVersion = apiRegisterVersion; - } - if (RequestProtocol.GetUniqueId(out var uniqueId)) - { - UniqueId = uniqueId; - } - if (RequestProtocol.GetSensorSerialNo(out var sensorSerialNo)) - { - SensorSerialNo = sensorSerialNo; - } - if (RequestProtocol.GetPcbId(out var pcbId)) - { - PcbId = pcbId; - } - if (RequestProtocol.GetElectrodeBoardCorrectionFactor(out var boardCalib)) - { - BoardCalib = boardCalib; - } - if (RequestProtocol.GetEmptyPipeControl(out var epd_cntl_bits)) - { - EpdControlBits = epd_cntl_bits; - } - if (RequestProtocol.GetStdDev_Electrode_mV(out var u_mV)) - { - StandardDeviationElectrode_mV = u_mV; - } - if (RequestProtocol.GetAverage_Electrode_mV(out u_mV)) - { - AverageElectrode_mV = u_mV; - } - - SimulatedFlowIsActive = RequestProtocol.IsSimulatedFlowActive(); - IgnoreEmptyPipeDetection = RequestProtocol.GetIgnoreFailOnEmptyPipeOnHealthy(); - - RequestProtocol.GetCalibrationPoints(out _); - StreamingProtocol.SetDecodingMask(SensorSerialNo, uniqueId); - - return IsLoggedOn; - } - - /// - public Boolean Login(String password, Boolean runImmediately = true, Boolean skipReadMeterFwAndAssignRegisters = false) - { - return true; - } - - /// - public void InitMeasurement() - { - WriteLog("Init measurement"); - PreMeasurement(); - } - - private void PreMeasurement() - { - if (!SkipPreparationForTestBench) - { - SkipPreparationForTestBench = true; - } - else - { - WriteLog("Wait on measurement start"); - } - ProcessStatus = ProcessState.WaitForMeasurement; - } - - /// - public void StartMeasurement() - { - _listOfIMeasurement = new List - { - new BaseMeasurement(Slot, typeof(MagFluxRecord), IntermediateUpdateTimeS) - }; - - foreach (var measurement in _listOfIMeasurement) - { - measurement.OnActionStateHasChanged += Measurement_ActionStateHasChanged; - } - - WriteLog("Start measurement"); - - ProcessStatus = ProcessState.MeasurementIsActive; - _listOfIMeasurement.ForEach(m => m.MeasurementState = MeasurementStates.IsWaitingForStartData); - SyncStreamingBuffer(SyncMarkRecord.SyncStart); - } - - /// - public void StopMeasurement() - { - WriteLog("Stop measurement"); - ProcessStatus = ProcessState.MeasurementIsDone; - _listOfIMeasurement.ForEach(m => m.MeasurementState = MeasurementStates.IsWaitingForEndData); - SyncStreamingBuffer(SyncMarkRecord.SyncEnd); - } - - private void Measurement_ActionStateHasChanged(Object sender, EventArgs e) - { - SyncStreamingBuffer(SyncMarkRecord.DecodeIntermediate); - } - - /// - public MeasurementResults GetMainMeasurementResult(Double? refVolume, Double? refTimeS, - Boolean intermediateMeasurement = false, MeasurementDirection dir = MeasurementDirection.TakeBoth) - { - if (!intermediateMeasurement && GetMeasurementState(0) != MeasurementStates.IsCompleted) - { - throw new ApplicationException("Measurement is not completed"); - } - return GetAllMeasurementResults(refVolume, refTimeS, intermediateMeasurement, 0,dir).First(); - } - - /// - public List GetAllMeasurementResults(Double? refVolume, Double? refTimeS, Boolean intermediateMeasurement = false, - Int32? channel = null, MeasurementDirection dir = MeasurementDirection.TakeBoth) - { - if (!intermediateMeasurement && GetMeasurementState(channel) != MeasurementStates.IsCompleted) - { - throw new ApplicationException("Measurement is not completed"); - } - var mainMeasurement = _listOfIMeasurement.FirstOrDefault(m => m.GetType() == typeof(MagFluxRecord)); - - if (mainMeasurement == null) - { - throw new ApplicationException("Can not find an ongoing measurement"); - } - mainMeasurement.FlowDirectionforCalculatingVol = dir; - - var results = new List(); - var mainResult = intermediateMeasurement - ? mainMeasurement.GetIntermediateMeasurementResult(refVolume, refTimeS) - : mainMeasurement.GetFinalMeasurementResult(refVolume, refTimeS); - results.Add(mainResult); - _logger.Debug($"Slot:{Slot}, Channel:{mainMeasurement.GetChannel()} - MeasuredTime({mainResult.DutTimeS}s), " + - $"MeasuredVolume({mainResult.DutVolumeCm}Qm)"); - - foreach (var otherMeasurement in _listOfIMeasurement.Where(m => m.GetType() != typeof(MagFluxRecord))) - { - try - { - var otherResults = intermediateMeasurement - ? otherMeasurement.GetIntermediateMeasurementResult(refVolume, refTimeS) - : otherMeasurement.GetFinalMeasurementResult(refVolume, refTimeS); - _logger.Debug($"Slot:{Slot}, Channel:{otherMeasurement.GetChannel()} - ChannelTime({otherResults.DutTimeS}s), " + - $"ChannelVolume({otherResults.DutVolumeCm}Qm)"); - results.Add(otherResults); - } - catch (Exception ex) - { - _logger.Warn($"Slot:{Slot}, No Results for channel:{otherMeasurement.GetChannel()} Ex: {ex.Message}"); - if (channel == null) - { - throw new ApplicationException($"Can not read result from channel:{otherMeasurement.GetChannel() } Ex: {ex.Message}"); - } - } - } - - return results; - } - - /// - public MeasurementStates GetMeasurementState(Int32? onlyChannelNr = null) - { - WriteLog("Get measurement state"); - if (!_listOfIMeasurement.Any()) - { - return MeasurementStates.NotStarted; - } - - if (onlyChannelNr.HasValue) - { - var measurement = _listOfIMeasurement.First(f => f.GetChannel() == onlyChannelNr.Value); - return measurement.GetMeasurementState(); - } - return _listOfIMeasurement.Min(m => m.MeasurementState); - } - - /// - public Boolean RequestIntermediateMeasurementState(Int32? onlyChannelNr = null) - { - WriteLog("Get measurement state"); - if (!_listOfIMeasurement.Any()) - { - return false; - } - Boolean? ret = null; - foreach (var item in _listOfIMeasurement) - { - if (!onlyChannelNr.HasValue || item.GetChannel() == onlyChannelNr.Value) - { - var measurement = _listOfIMeasurement.First(f => onlyChannelNr != null && f.GetChannel() == onlyChannelNr.Value); - if ((measurement.MeasurementState == MeasurementStates.IsRunning - || measurement.MeasurementState == MeasurementStates.IsWaitingForIntermediateData)) - { - measurement.RequestIntermediateRecord(); - if (!ret.HasValue) - { - ret = true; - } - } - else - { - ret = false; - } - } - } - return ret ?? false; - } - - - /// > - public String GetPcbId() - { - if (!string.IsNullOrEmpty(PcbId) && !string.Equals("?", PcbId)) - { - return PcbId; - } - var pcbId = PcbId; - RequestProtocol?.GetPcbId(out pcbId); - PcbId = pcbId; - return pcbId; - } - /// - /// Get empty pipe control bits MagFlux - /// - public Boolean GetEmptyPipeControl() - { - var retVal = RequestProtocol.GetEmptyPipeControl(out var epd_cntl_bits); - if (retVal) - { - EpdControlBits = epd_cntl_bits; - } - - return retVal; - } - /// - /// Write calibration values to MagFlux - /// - public void WriteCalibration(List calibrationsCmPerH) - { - RequestProtocol?.SetCalibrationPoints(calibrationsCmPerH); - //RequestProtocol?.CloseConnection(); - } - /// - /// Read calibration values to MagFlux - /// - public void ReadCalibration(out List calibrationsCmPerH) - { - calibrationsCmPerH = null; - RequestProtocol?.GetCalibrationPoints(out calibrationsCmPerH); - //RequestProtocol?.CloseConnection(); - } - - /// - /// Average Electrode measurement used for Device calibration verification - /// - /// Average Electrode [mV] - /// true on okay or false on error - public Boolean GetAverage_Electrode_mV(out Single u_mV) - { - u_mV = 0; - var retVal = RequestProtocol.GetAverage_Electrode_mV(out u_mV); - AverageElectrode_mV = u_mV; - return retVal; - } - - /// - /// Standard deviation electrode measurement used for Device calibration verification - /// Note: update will only happen after x seconds, depending on filter config in device - /// - /// Average Electrode [mV] - /// true on okay or false on error - public Boolean GetStdDev_Electrode_mV(out Single u_mV) - { - u_mV = 0; - var retVal = RequestProtocol.GetStdDev_Electrode_mV(out u_mV); - StandardDeviationElectrode_mV = u_mV; - return retVal; - } - - /// - /// Ignore Empty pipe flag on Healthy, because it is not yet working correct - /// Note: Not 100% secure all test is working during empty pipe, metrology board firmware may not allow running during detection of empty pipe - /// - /// - /// true on okay or false on error - public Boolean SetIgnoreFailOnEmptyPipeOnHealthy(Boolean ignoreEmptyPipeStatus) - { - var retVal = RequestProtocol.SetIgnoreFailOnEmptyPipeOnHealthy(ignoreEmptyPipeStatus); - if (retVal) - IgnoreEmptyPipeDetection = ignoreEmptyPipeStatus; - return retVal; - } - - /// - /// Set PCB settings and PCB calibrations to default. - /// - public Boolean SetPCBToDemoDefaults() - { - if (RequestProtocol == null) - return false; - var retVal = RequestProtocol.SetPCBToDemoDefaults(); - //RequestProtocol?.CloseConnection(); - return retVal; - } - - /// - /// Set a new meter size to MagFlux - /// - public Boolean SetMeterSizeMm(UInt16 meterSize_mm) - { - if (RequestProtocol == null) - return false; - var retVal = RequestProtocol.SetMeterSizeMm(meterSize_mm); - //RequestProtocol?.CloseConnection(); - return retVal; - } - - /// - /// Set a new sensor serial number to MagFlux - /// - public Boolean SetSensorSerialNo(UInt32 sensorSerialNo) - { - if (RequestProtocol == null) - return false; - var retVal = RequestProtocol.SetSensorSerialNo(sensorSerialNo); - //RequestProtocol?.CloseConnection(); - return retVal; - } - - /// - public void InitCalibration() - { - if (RequestProtocol == null) - return; - if (RequestProtocol.PrepareDeviceForCalibration()) - PreMeasurement(); - //RequestProtocol?.CloseConnection(); - } - - /// - public void StartCalibration() - { - StartMeasurement(); - } - - /// - public void StopCalibration() - { - StopMeasurement(); - //RequestProtocol?.CloseConnection(); - } - - /// - public MeasurementStates GetCalibrationState() - { - return GetMeasurementState(); - } - - /// - public void BuildAndCheckCalibFactorsAllChannels(Double refVolumeCm, Double? refTimeS = null, - Double reqDeviationPercent = 0, Double maxCalibFactorTolerancePercent = 0) - { - throw new NotImplementedException(); - } - - /// - public void SetCalibFactorsAllChannels(Boolean justLog = false) - { - throw new NotImplementedException(); - } - - /// - public void SetLcdText(Boolean release, Byte[] textInHex) - { - throw new NotImplementedException(); - } - - /// - public void SetProcessState(DisplayCodes newState, Boolean webRequest = true) - { - throw new NotImplementedException(); - } - - /// - public DisplayCodes GetLastProcessState() - { - throw new NotImplementedException(); - } - - /// - public void WriteLog(String text) - { - _logger.Trace($"Slot:{Slot} - {text}"); - } - - /// - public void LogRawData(Boolean on) - { - _enableRawDataLogging = on; - //if (_enableRawDataLogging) - //{ - // if (_loggerRawData == null) - // { - // _loggerRawData = NLogHelper.CreateOrGetMultiLogger( - // StreamingPort.GetPortName(), "", "LedRawData", "TargetLedRawDataBase", "LedRawDataBase"); - - // } - //} - if (StreamingPort is LedSerialPort port) - { - port.RecordStreamingRawData = _enableRawDataLogging; - } - } - - /// - public Boolean CheckStateAfterMeasurement() - { - throw new NotImplementedException(); - } - - /// - public void DisposeMeter() - { - Dispose(); - } - - private void AddData(IMeasurementRecord newRecord) - { - - foreach (var measurement in _listOfIMeasurement) - { - if (measurement.GetType() != newRecord.GetType()) - { - continue; - } - - if (measurement.GetChannel() == newRecord.GetChannel()) - { - measurement.AddData(newRecord); - } - } - - // when every measurement has state IsRunning or every measurement has state IsCompleted, the streaming buffer set to skip decoding - if (_listOfIMeasurement.All(m => m.MeasurementState == MeasurementStates.IsRunning) - || _listOfIMeasurement.All(m => m.MeasurementState == MeasurementStates.IsCompleted)) - { - SyncStreamingBuffer(QualityWatchMode - ? SyncMarkRecord.DecodeIntermediateQuality - : SyncMarkRecord.SkipDecoding); - } - - } - #endregion - - #region logging - private void SetLogger() - { - if (_logger != null) - { - LogManager.Flush(); - } - // the id is a combination of UniqueId stored in PcbId and SensorSN (SensorId) - var id = !string.IsNullOrEmpty(PcbId) ? $"PCBID{PcbId}" : "?"; - id += !string.IsNullOrEmpty(SerialNumber) ? $"_SN{SerialNumber}" : "?"; - var fileName = $"MagFluxRawData_Slot_{Slot}"; - - if (string.IsNullOrEmpty(CurrentActionText)) - { - _logger = NLogHelper.CreateOrGetMultiLogger($"Slot:{Slot}", $"", "Meter", "MeterBase", "MeterBase"); - if (RequestProtocol != null) - { - var pathName = NLogHelper.GetPath(_logger); - var path = Path.GetDirectoryName(pathName); - RequestProtocol.SetLogLocation(path, fileName); - } - } - else - { - _logger = NLogHelper.CreateOrGetMultiLogger($"Slot:{Slot}_{id}_{CurrentActionText}", "Slot", "Meter", "MeterBase", "MeterBase"); - if (RequestProtocol != null) - { - var pathName = NLogHelper.GetPath(_logger); - var path = Path.GetDirectoryName(pathName); - RequestProtocol.SetLogLocation(path, fileName); - } - - //TODO check with roland - if (StreamingPort is LedSerialPort) - { - var streamingIdent = $"LedRawData_Slot_{Slot}_{id}_{CurrentActionText}"; - - ((LedSerialPort)StreamingPort).Ident = streamingIdent; - ((LedSerialPort)StreamingPort).RefreshLogger(); - - - //if (!string.IsNullOrEmpty(SerialNumber) && CurrentActionText.Contains("PG")) - //{ - - // //var pathMain = NLogHelper.GetPath(_logger); - // //var pathRaw = NLogHelper.GetPath(((LedSerialPort)StreamingPort).GetRawLogger()); - - // //var basePath = Path.GetDirectoryName(pathMain); - - // //var testRunString = CurrentActionText.Replace("PG", ""); - // //var lastChat = pathMain.LastIndexOf('\\'); - // //pathMain = pathMain.Substring(lastChat + 1); - // //pathRaw = Path.GetFileName(pathRaw); - - // //var tmpUrl = $"http://10.49.40.25/MeterProcessState/api/TestBench/SetMeterLogPathInfo?SerialNumber={SerialNumber}&TestRunId={testRunString}&BasePath={basePath}&MainLogName={pathMain}&LEDName={pathRaw}"; - // //_logger.Debug($"Request Url: { tmpUrl}"); - // ////ToDO: Update to service URl - // //LocalWebRequest.GetRequest(tmpUrl); - //} - } - } - } - - public void TestBenchDispose() - { - //nothing to do - } - #endregion - } -} diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.cs.bak b/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.cs.bak deleted file mode 100644 index 03d190de..00000000 --- a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.cs.bak +++ /dev/null @@ -1,673 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using NLog; -using XYLEM; -using Xylem.Common.Hardware.Interfaces.Ports.PortCore.EventArguments; -using Xylem.Common.Hardware.Interfaces.Protocols.ProtocolCore; -using Xylem.Common.Hardware.Interfaces.Protocols.ProtocolCore.EventArguments; -using Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.DataTypes; -using Xylem.Common.Utils.Logging; - -namespace Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol -{ - /// - /// Wrapper for MagFlux request protocol implemented in - /// - public class RequestProtocol : BaseProtocol - { - private readonly String _ident; - private readonly ILogger _logger; - private IMagFluxRequestProtocol _magFluxRequestProtocol; - private IMagFluxAPI _magFluxApi; - - // calibration point in cubic meters per hour - private List _calibPointsCmPerH; - - /// - /// - /// - MagFluxApi - /// - public RequestProtocol(String ident) : base(ident) - { - _ident = ident; - _magFluxApi = new MagFluxAPI(); - _calibPointsCmPerH = new List(); - _logger = NLogHelper.CreateOrGetMultiLogger(_ident, "", "RequestProtocol", "MeterBase", - "MeterBase"); - } - - /// > - /// - /// - MagFluxApi - /// - public override void Dispose() - { - _calibPointsCmPerH.Clear(); - _calibPointsCmPerH = null; - CloseConnection(); - _magFluxRequestProtocol = null; - _magFluxApi = null; - base.Dispose(); - } - - /// - public override event EventHandler OnRecordReadyToSend; - - /// - public override event EventHandler OnRecordIsDecoded; - - protected override void DecodeRecord(IPortDataEventArgs data) - { - throw new NotImplementedException(); - } - - /// - /// Wrapper to connect MagFlux - /// - /// - /// - /// - /// - Initial - /// - /// - /// - MagFluxApi - /// - /// - /// - Avoid re-opening if connection is already done - /// - public Boolean Connect(String portName) - { - if (_magFluxApi == null) - return false; - if (_magFluxRequestProtocol != null && _magFluxRequestProtocol.IsConnected()) - { - _logger.Info($"{_ident} Connection already established to {portName}"); - return true; - } - - _magFluxRequestProtocol = _magFluxApi.Connect(portName); - if (_magFluxRequestProtocol == null) - { - _logger.Error($"{_ident} Connection to {portName} failed! Object reference returned null"); - return false; - } - - Thread.Sleep(100); - var retVal = _magFluxRequestProtocol.IsConnected(); - if (retVal) - { - _logger.Info($"{_ident} New connection established to {portName}"); - } - else - { - _logger.Error($"{_ident} Connection to {portName} failed!"); - } - - return retVal; - } - - public String GetComCounters() - { - throw new NotImplementedException(); - } - - /// - /// Wrapper to set the log location for MagFlux direct raw output - /// - /// location of raw logging - /// file name based on the UniqueId - /// - /// - /// - Initial - /// - public Boolean SetLogLocation(String path, String fileName) - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.SetLogLocation(path, fileName); - if (string.IsNullOrEmpty(fileName)) - fileName = "?"; - _logger.Debug(retVal ? - $"{_ident} Logging set to: {path}\\{fileName}" : - $"{_ident} Logging path setup failed!"); - return retVal; - } - - public void OpenLogFile() - { - throw new NotImplementedException(); - } - - /// - /// Wrapper to set experimental boards to defaults regarding board serial number - /// and board calibration values - /// - /// - /// - /// - Initial - /// - public Boolean SetPCBToDemoDefaults() - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.SetPCBToDemoDefaults(); - _logger.Debug(retVal ? - $"{_ident} Successfully set PCB settings and PCB calibrations to default" : - $"{_ident} PCB settings and PCB calibrations setup to default failed!"); - return retVal; - } - - /// - /// Wrapper to get the simulated flow setting - /// - /// - /// - /// - Initial - /// - public Boolean IsSimulatedFlowActive() - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.IsSimulatedFlowActive(); - _logger.Debug($"{_ident} Simulated flow active read back returns: {retVal}"); - return retVal; - } - - /// - /// Wrapper to set the simulated flow setting - /// - /// true to ignore state - /// - /// - /// - Initial - /// - public Boolean SetSimulatedFlowActive(Boolean on) - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.SetSimulatedFlowActive(on); - _logger.Debug(retVal ? - $"{_ident} Simulated flow active set to: {on}" : - $"{_ident} Simulated flow active setup failed!"); - return retVal; - } - - /// - /// Wrapper to get the ignore empty pipe mode status - /// - /// - /// - /// - Initial - /// - public Boolean GetIgnoreFailOnEmptyPipeOnHealthy() - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetIgnoreFailOnEmptyPipeOnHealthy(); - _logger.Debug($"{_ident} Ignore empty pipe status read back returns: {retVal}"); - return retVal; - } - - /// - /// Wrapper to set the ignore empty pipe mode - /// - /// true to ignore state - /// - /// - /// - Initial - /// - public Boolean SetIgnoreFailOnEmptyPipeOnHealthy(Boolean on) - { - if (_magFluxRequestProtocol == null) - return false; - _magFluxRequestProtocol.SetIgnoreFailOnEmptyPipeOnHealthy(on); - var retVal = _magFluxRequestProtocol.GetIgnoreFailOnEmptyPipeOnHealthy(); - _logger.Debug(retVal == on ? - $"{_ident} Ignore empty pipe status adjusted to: {on}" : - $"{_ident} Ignore empty pipe status setup failed!"); - return retVal == on; - } - - /// - /// Wrapper to get the empty pipe bits - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetEmptyPipeControl(out Int32 epd_cntl_bits) - { - epd_cntl_bits = 0; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetEmptyPipeControl(out epd_cntl_bits); - _logger.Debug(retVal ? - $"{_ident} Empty pipe control bits: 0x{epd_cntl_bits:X4}" : - $"{_ident} Empty pipe control bits request failed!"); - return retVal; - } - - /// - /// Wrapper to get the standard deviation value of the electrode in milli Volts - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetStdDev_Electrode_mV(out Single u_mV) - { - u_mV = 0; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetStdDev_Electrode_mV(out u_mV); - _logger.Debug(retVal ? - $"{_ident} Standard deviation of electrode: {u_mV:F6} mV" : - $"{_ident} Standard deviation of electrode request failed!"); - return retVal; - } - /// - /// Wrapper to get the standard deviation value of the electrode in milli Volts - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetAverage_Electrode_mV(out Single u_mV) - { - u_mV = 0; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetAverage_Electrode_mV(out u_mV); - _logger.Debug(retVal ? - $"{_ident} Average of electrode: {u_mV:F6} mV" : - $"{_ident} Average of electrode request failed!"); - return retVal; - } - - /// - /// Wrapper to get the board calibration value - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetElectrodeBoardCorrectionFactor(out Single value_out) - { - value_out = 0f; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetElectrodeBoardCorrectionFactor(out value_out); - _logger.Debug(retVal ? - $"{_ident} Board calibration: {value_out:F4}" : - $"{_ident} SensorSerialNo request failed!"); - return retVal; - } - - /// - /// Wrapper to get the sensor serial number - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetSensorSerialNo(out String sensorSerialNo) - { - sensorSerialNo = "?"; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetSensorSerialNo(out sensorSerialNo); - _logger.Debug(retVal ? - $"{_ident} SensorSerialNo: {sensorSerialNo}" : - $"{_ident} SensorSerialNo request failed!"); - return retVal; - } - - /// - /// Wrapper to get the PcbId - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetPcbId(out String pcbId) - { - pcbId = "?"; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetBoardSerialNo(out pcbId); - _logger.Debug(retVal ? - $"{_ident} PcbId: {pcbId}" : - $"{_ident} PcbId request failed!"); - return retVal; - } - - /// - /// Wrapper to set the sensor serial number - /// - /// - /// - /// - /// - Initial - /// - public Boolean SetSensorSerialNo(UInt32 sensorSerialNo) - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.SetSensorSerialNo(sensorSerialNo); - _logger.Debug(retVal ? - $"{_ident} Set SensorSerialNo: {sensorSerialNo}" : - $"{_ident} Set SensorSerialNo request failed!"); - return retVal; - } - - /// - /// Wrapper to get unique id referenced as PCBID - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetUniqueId(out String pcbId) - { - pcbId = "?"; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetUniqueId(out pcbId); - _logger.Debug(retVal ? - $"{_ident} UniqueId: {pcbId}" : - $"{_ident} UniqueId request failed!"); - return retVal; - } - - /// - /// Wrapper to get FW version of MagFlux - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetFirmwareVersion(out String fwVersion) - { - fwVersion = "?"; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetFirmwareVersion(out fwVersion); - _logger.Debug(retVal ? - $"{_ident} FW Version: {fwVersion}" : - $"{_ident} FW Version request failed!"); - return retVal; - } - - /// - /// Wrapper to get FW Build Date - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetFwBuildDate(out String fwBuildDate) - { - fwBuildDate = "?"; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetFwBuildDate(out fwBuildDate); - _logger.Debug(retVal ? - $"{_ident} FW Build Date: {fwBuildDate}" : - $"{_ident} FW Build Date request failed!"); - return retVal; - } - - /// - /// Wrapper to get FW GIT hash of MagFlux - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetFwGitHash(out String fwGitHash) - { - fwGitHash = "?"; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetFwGitHash(out fwGitHash); - _logger.Debug(retVal ? - $"{_ident} FW GIT Hash: {fwGitHash}" : - $"{_ident} FW GIT Hash request failed!"); - return retVal; - } - - /// - /// Wrapper to get API register version of MagFlux - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetApiRegisterVersion(out String apiRegisterVersion) - { - apiRegisterVersion = "?"; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetAPIRegisterVersion(out apiRegisterVersion); - _logger.Debug(retVal ? - $"{_ident} MagFlux API Register Version: {apiRegisterVersion}" : - $"{_ident} MagFlux API Register Version request failed!"); - return retVal; - } - - public Boolean GetFlowRate_lps(out Single value_out) - { - throw new NotImplementedException(); - } - - /// - /// Wrapper to get meter size in mm - /// - /// - /// - /// - /// - Initial - /// - public Boolean GetMeterSizeMm(out Int32 meterSize) - { - meterSize = 0; - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.GetDn_mm(out meterSize); - _logger.Debug(retVal ? - $"{_ident} MeterSize DN: {meterSize}" : - $"{_ident} MeterSize request failed!"); - return retVal; - } - - /// - /// Wrapper to set meter size in mm - /// - /// - /// - /// - /// - Initial - /// - public Boolean SetMeterSizeMm(UInt16 meterSize) - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.SetDn_mm(meterSize); - _logger.Debug(retVal ? - $"{_ident} Set MeterSize DN: {meterSize}" : - $"{_ident} Set MeterSize failed!"); - return retVal; - } - - public Boolean GetDeviceHealthy() - { - throw new NotImplementedException(); - } - - public Boolean GetDeviceErrorMessages(out List status_list_out) - { - throw new NotImplementedException(); - } - - public Boolean PrepareDeviceForCalibration() - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.PrepareDeviceForCalibration(); - _logger.Debug(retVal ? - $"{_ident} MagFlux successfully prepared for calibration" : - $"{_ident} MagFlux preparation for calibration failed!"); - return retVal; - } - - public Boolean AbortDeviceForCalibration() - { - if (_magFluxRequestProtocol == null) - return false; - var retVal = _magFluxRequestProtocol.AbortDeviceForCalibration(); - _logger.Debug(retVal ? - $"{_ident} MagFlux calibration successfully aborted" : - $"{_ident} MagFlux abortion of calibration failed!"); - return retVal; - } - - /// - /// Wrapper to get the calibration points from MagFlux: - /// - Here the conversion from to to - /// will take place. - /// - /// - /// - /// - /// - Initial - /// - /// - /// - Output in cubic meters per hour. - /// - public Boolean GetCalibrationPoints(out List calibPointsCmPerH) - { - calibPointsCmPerH = new List(); - if (_magFluxRequestProtocol == null) - return false; - - var retVal = _magFluxRequestProtocol.GetCalibrationPoints(out var calibrations); - _logger.Debug(retVal ? - $"{_ident} MagFlux calibration successfully read:\n{calibrations}" : - $"{_ident} MagFlux calibration read failed!"); - - if (!retVal) - return false; - - // extract the single calibration points from container as ref and DUT in liters per second - var calibPoints = calibrations?.calibrations?.ToList(); - if (calibPoints == null) - return false; - - var calibConverter = new Calibration(); - _calibPointsCmPerH?.Clear(); - - foreach (var cp in calibPoints) - { - // convert flow rate from liters per second to cubic meters per hour - calibConverter.refFlowRate = cp.ReferenceFlowRate_lps * 3.6f; - calibConverter.dutFlowRate = cp.ReportedFlowRate_lps * 3.6f; - _calibPointsCmPerH?.Add(calibConverter); - } - - calibPointsCmPerH = _calibPointsCmPerH; - return true; - } - - /// - /// Wrapper to set the calibration points from MagFlux: - /// - Calibration points have to be sorted ascending by request from MJK - /// - Here the conversion from to - /// will take place. - /// - /// - /// - /// - /// - Initial - /// - /// - /// - Input in cubic meters per hour, - /// - Remove multiple 0;0 calibrations as these are unused points. - /// - public Boolean SetCalibrationPoints(List calibPointsCmPerH) - { - if (_magFluxRequestProtocol == null || calibPointsCmPerH == null) - return false; - - // remove zeros as this are possibly empty (unused) fields - var removedZeros = calibPointsCmPerH.Where(x => x.dutFlowRate != 0 || x.refFlowRate != 0); - var calibrations = new List(); - calibrations.AddRange(removedZeros); - if (calibrations.All(x => x.refFlowRate != 0)) - { - calibrations.Add(new Calibration { dutFlowRate = 0, refFlowRate = 0 }); - } - - // order calibrations ascending as required by MJK - var orderedCalibrations = calibrations.OrderBy(x => x.refFlowRate); - - _calibPointsCmPerH.Clear(); - _calibPointsCmPerH.AddRange(orderedCalibrations); - - var calibPoints = new List(); - foreach (var cp in _calibPointsCmPerH) - { - // convert flow rate to liters per second from cubic meters per hour - var calibConverter = new CalibrationPoint - { - ReferenceFlowRate_lps = cp.refFlowRate / 3.6f, - ReportedFlowRate_lps = cp.dutFlowRate / 3.6f - }; - calibPoints.Add(calibConverter); - } - var cbs = new CalibrationPoints(calibPoints, calibPoints.Count); - var retVal = _magFluxRequestProtocol.SetCalibrationPoints(cbs); - _logger.Debug(retVal ? - $"{_ident} MagFlux calibration successfully set:\n{cbs}" : - $"{_ident} MagFlux calibration setup failed!"); - return retVal; - } - - - /// - /// Wrapper to close the connection to the MagFlux - /// - /// - /// - /// - Initial - /// - /// - /// - Corrected logic, if !IsConnected = connection is closed - /// - public Boolean CloseConnection() - { - if (_magFluxRequestProtocol == null) - return false; - MagFluxAPI.CloseAllConnections(); - - Thread.Sleep(100); - var retVal = _magFluxRequestProtocol.IsConnected(); - _logger.Info(!retVal ? - $"{_ident} Connection is closed" : - $"{_ident} Close connection request failed!"); - return retVal; - } - } -} diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.csproj.bak b/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.csproj.bak deleted file mode 100644 index 53469aa6..00000000 --- a/Common/Hardware/WaterMeter/MagFlux/Protocols/RequestProtocol/RequestProtocol.csproj.bak +++ /dev/null @@ -1,83 +0,0 @@ - - - - - Debug - AnyCPU - {00748F11-4B49-4D8B-93C4-4A11A210CCE2} - Library - Properties - Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol - Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.RequestProtocol - v4.8 - 512 - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\MagFluxApi\magflux_api.dll - - - ..\..\..\..\..\packages\NLog.5.2.2\lib\net46\NLog.dll - - - ..\..\MagFluxApi\shared_code.dll - - - - - - - - - - - - - - - - - - - - - - {4B88B0D3-E791-4774-9521-EABEACDC420E} - Logging - - - {2E139F63-B6FE-4EA9-A098-85364FE9B26C} - PortCore - - - {8BDD2789-96D4-43EA-AAD7-0F49D0347998} - ProtocolCore - - - {BA17D20E-0CEB-4B27-9772-2392BD750ED5} - DataPackages - - - - - - - \ No newline at end of file diff --git a/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingProtocol.csproj.bak b/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingProtocol.csproj.bak deleted file mode 100644 index fd1cdc8e..00000000 --- a/Common/Hardware/WaterMeter/MagFlux/Protocols/StreamingProtocol/StreamingProtocol.csproj.bak +++ /dev/null @@ -1,83 +0,0 @@ - - - - - Debug - AnyCPU - {D6B81C60-2763-4C4D-989F-90822F53B01A} - Library - Properties - Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol - Xylem.Common.Hardware.WaterMeter.MagFlux.Protocols.StreamingProtocol - v4.8 - 512 - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\..\packages\NLog.5.2.2\lib\net46\NLog.dll - - - - - - - - - - - - - - - - - - - - {1B02C79E-0B19-43E2-8F6B-71EF0C786C97} - CommonCore - - - {6CCDB656-C676-4360-BABA-C4596AAD175D} - Measurements - - - {91DEF0C0-AA4F-40AE-8F18-CB717FDE7E7F} - Crc16Ccitt - - - {2E139F63-B6FE-4EA9-A098-85364FE9B26C} - PortCore - - - {8BDD2789-96D4-43EA-AAD7-0F49D0347998} - ProtocolCore - - - {BA17D20E-0CEB-4B27-9772-2392BD750ED5} - DataPackages - - - - - - - \ No newline at end of file diff --git a/Common/Hardware/WaterMeter/WaterMeterCore/IMeter.cs.bak b/Common/Hardware/WaterMeter/WaterMeterCore/IMeter.cs.bak deleted file mode 100644 index 72ca84b0..00000000 --- a/Common/Hardware/WaterMeter/WaterMeterCore/IMeter.cs.bak +++ /dev/null @@ -1,287 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using Xylem.Common.Hardware.WaterMeter.WaterMeterCore.Consts; -using Xylem.Common.Metrology.Measurements; -using Xylem.Common.Metrology.Measurements.Consts; - -namespace Xylem.Common.Hardware.WaterMeter.WaterMeterCore -{ - - /// - /// - /// IMeter is the highest level interface between a meter with direct communication to a test bench. - /// has general things like calibration, measurement and set up routines. - /// no specific meter stuff in here! - /// it is always disposable - /// - [Guid("7BD20046-DF8C-44A6-8F6B-687FAA26FA71") - , ComVisible(true) - , InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] - - public interface IMeter : IDisposable - { - #region events - - /// - /// occurs when ProcessState has changed - /// - event EventHandler OnProcessStatusChanged; - - /// - /// occurs when ErrorState has changed - /// - event EventHandler OnErrorStatusChanged; - - /// - /// occurs when Init is completed - /// - event EventHandler OnInitCompleted; - - /// - /// occurs when the initialization for Measurement is completed - /// - event EventHandler OnMeasurementInitCompleted; - - /// - /// occurs when the Measurement is completed - /// - event EventHandler OnMeasurementCompleted; - - /// - /// occurs when the initialization for calibration is completed - /// - event EventHandler OnCalibInitCompleted; - - /// - /// occurs when the calibration is completed - /// - event EventHandler OnCalibCompleted; - - /// - /// occurs when meter gets disposed - /// - event EventHandler OnDisposeCompleted; - #endregion - - #region properties - /// - /// unique meter identification - /// - String SerialNumber { get; set; } - - /// - /// read-only to see current Process state - /// - ProcessState ProcessStatus { get; } - - /// - /// the current slot in test-bench - /// - Int32 Slot { get; set; } - - /// - /// Setup of intermediate update time for measurement updates and overflow detections, - /// has to be calculated depending on flow-rate and nominal diameter (DN) - /// - Int32 IntermediateUpdateTimeS { get; set; } - /// - /// Skip the test bench preparation process - /// - Boolean SkipPreparationForTestBench { get; set; } - /// - /// Set the current action test - /// - String CurrentActionText { get; set; } - #endregion - - #region method - - /// - /// Read the PcbId from IMeter, if device has no readable PcbId simulate one - /// - /// - String GetPcbId(); - - /// - /// Open Com ports, try some communication, login - /// - void ConnectMeter(); - - /// - /// Setup up meter from config file. just a workaround for vb6 calls. please do not use if your working with .net - /// - /// Slot Number for Test bench - /// don´t send CRC error or telegrams with error flag to caller - /// - /// - void SetupFromConfigFile(Int32 slot, Boolean ignoreCorruptedData = true, Boolean useRequest = true, Boolean useStreaming = true); - - - - /// - /// Logout from device - /// - Boolean Logout(); - - /// - /// Start Login with password service - /// - Boolean Login(); - - /// - /// Start Login with out password service and a fixed password - /// - /// password for login - /// execute immediately - /// skip app readout and register generation to speed up - /// the initial connection process - Boolean Login(String password, Boolean runImmediately = true, Boolean skipReadMeterFwAndAssignRegisters = false); - - /// - /// set up measurement parameter and set meter into test-mode - /// - void InitMeasurement(); - - /// - /// Starting a Measurement - /// Meter must be initialized - /// Start to receive record from meter and decode this record into MeasurementRecord - /// - /// - [ComVisible(false)] - void StartMeasurement(); - - /// - /// Meter must have a active measurement - /// Stop receive record from meter and decode record - /// - void StopMeasurement(); - - /// - /// - simplify the measurement results handling - /// - getting the main measurement of the entire device (combination of all paths) - /// - add MeasurementResult - /// - remove all other methods - /// - /// - /// After a completed measurement , you can grab - /// - /// Calculated results - MeasurementResults GetMainMeasurementResult(Double? refVolume, Double? refTimeS, Boolean intermediateMeasurement = false, MeasurementDirection dir = MeasurementDirection.TakeBoth); - - - /// - /// The first measurement is ALWAYS a FlowTestRecord. - /// - List GetAllMeasurementResults(Double? refVolume, Double? refTimeS, - Boolean intermediateMeasurement = false, Int32? channel = null, MeasurementDirection dir = MeasurementDirection.TakeBoth); - - - - /// - /// get current state of the running measurement - /// - /// leave empty for an aggregate state for all measurements or pass the channel number to check - /// - MeasurementStates GetMeasurementState(Int32? onlyChannelNr = null ); - - /// - /// Request for intermediate measurement state. - /// - /// - /// - Boolean RequestIntermediateMeasurementState(Int32? onlyChannelNr = null); - - /// - /// set up calibration parameter (calibration factor to default) and set meter into calibration mode - /// - void InitCalibration(); - - /// - /// Starting a Calibration - /// Meter must be initialized - /// Start to receive record from meter, decode and store this record - /// no available - /// To finish calibration process run - /// - [ComVisible(false)] - void StartCalibration(); - - /// - /// Meter must have a active for calibration - /// Stop receive record from meter, decode and store record - /// record will not calculate or store - /// - void StopCalibration(); - - /// - /// Get current state of the running calibration - /// - /// - MeasurementStates GetCalibrationState(); - - /// - /// Calculate calibration factor for static and flying start / stop - /// Results kept internal and not being saved to meter. - /// if you want to store them on meter use - /// - /// the reference volume is essential for calculation of calibration factor - /// the reference time is needed for flying start/stop - /// the required deviation to set the scale apart from 0 - /// override the default max calibration factor tolerance - void BuildAndCheckCalibFactorsAllChannels(Double refVolumeCm, Double? refTimeS = null, Double reqDeviationPercent = 0.0, Double maxCalibFactorTolerancePercent = 0.0); - - /// - /// Save calculated calibration on meter if no calibration results available an exception occurred - /// - void SetCalibFactorsAllChannels(Boolean justLog = false); - - /// - /// To control the LCD from meter for status information etc. - /// - /// if set to true the meter will show his normal screen, if set to false the next parameter will shown in display - /// test shown in LCD in byte array as hex value (0x33,0xFF shows 33FF on screen) - void SetLcdText(Boolean release, Byte[] textInHex); - - - /// - /// Sets Display text and update production database - /// - /// New ProductionState - /// web logging required per default true, for offline usage set to false - void SetProcessState(DisplayCodes newState, Boolean webRequest = true); - - /// - /// Get last Process State - /// - DisplayCodes GetLastProcessState(); - - /// - /// Add external text to internal log file handling - /// - /// text to log - void WriteLog(String text); - - /// - /// Enable/Disable Raw record Logging - /// - /// True = Write Raw record into log/ false = Stop write raw record into log - void LogRawData(Boolean on); - - /// - /// Check if the meter has any errors that can occur on a measurement - /// the error reason has find out in the log files - /// - /// false = everything is good, detect at least one error - Boolean CheckStateAfterMeasurement(); - - #endregion - - /// - /// Clear all object set up on runtime - /// - void DisposeMeter(); - void TestBenchDispose(); - } -} \ No newline at end of file diff --git a/Common/Production/ProductionUiCordonel/App.config b/Common/Production/ProductionUiCordonel/App.config index e85f7788..c940b21c 100644 --- a/Common/Production/ProductionUiCordonel/App.config +++ b/Common/Production/ProductionUiCordonel/App.config @@ -34,11 +34,11 @@ - - - - - + + + + + diff --git a/Common/Production/ProductionUiCordonel/App.xaml.cs b/Common/Production/ProductionUiCordonel/App.xaml.cs index 5fff457b..c143505d 100644 --- a/Common/Production/ProductionUiCordonel/App.xaml.cs +++ b/Common/Production/ProductionUiCordonel/App.xaml.cs @@ -1,6 +1,8 @@ using System; using System.Configuration; using System.Windows; +using Xylem.Common.Production.ProductionUiCordonel.ProductionProcesses.EolProcesses; +using Xylem.Common.Production.ProductionUiCordonel.ProductionProcesses.PickingProcesses; namespace Xylem.Common.Production.ProductionUiCordonel { @@ -11,24 +13,29 @@ namespace Xylem.Common.Production.ProductionUiCordonel { private void Application_Startup(Object sender, StartupEventArgs e) { - switch (ConfigurationManager.AppSettings[$"Mode"]) + switch (ConfigurationManager.AppSettings["Mode"]) { case "1": - - var mainWindow = new FinalTest(); - mainWindow.Show(); + var ProductionWindow = new ProductionWindow( + ProductionUiCordonel.Properties.Resources.StrEolSoftwareNameVersion, + "ProductionUiCordonel", new EolProcessStateDef()); + ProductionWindow.Show(); break; - //case "2": - // var Picking = new Picking(); - // Picking.Show(); - // break; + + case "2": + ProductionWindow = new ProductionWindow( + ProductionUiCordonel.Properties.Resources.StrPickingSoftwareNameVersion, + "PickingUiCordonel", new PickingProcessStateDef()); + ProductionWindow.Show(); + break; + default: - var mainWindowDef = new FinalTest(); - mainWindowDef.Show(); + ProductionWindow = new ProductionWindow( + ProductionUiCordonel.Properties.Resources.StrEolSoftwareNameVersion, + "ProductionUiCordonel", new EolProcessStateDef()); + ProductionWindow.Show(); break; } - - } } } diff --git a/Common/Production/ProductionUiCordonel/MainWindow.xaml b/Common/Production/ProductionUiCordonel/MainWindow.xaml deleted file mode 100644 index e878071f..00000000 --- a/Common/Production/ProductionUiCordonel/MainWindow.xaml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Common/Production/ProductionUiCordonel/MainWindow.xaml.cs b/Common/Production/ProductionUiCordonel/MainWindow.xaml.cs deleted file mode 100644 index a96dcba9..00000000 --- a/Common/Production/ProductionUiCordonel/MainWindow.xaml.cs +++ /dev/null @@ -1,451 +0,0 @@ -using System; -using System.ComponentModel; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading.Tasks; -using System.Timers; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Threading; -using Newtonsoft.Json; -using Xylem.Common.CommonCore.Configuration; -using Xylem.Common.CommonCore.Consts; -using Xylem.Common.Hardware.Interfaces.Ports.PortCore; -using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore; -using Xylem.Common.Hardware.WaterMeter.WaterMeterCore; -using Xylem.Common.Logic.SoftwareAccessHelper; -using Xylem.Common.Production.ProductionUiCordonel.Model; - -namespace Xylem.Common.Production.ProductionUiCordonel -{ - //public class QuantityToBackgroundConverter : IValueConverter - //{ - // public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - // { - // var dc = DisplayCodes.None; - - // if (DisplayCodes.TryParse(value.ToString(), out dc)) - // { - // string hex = ""; - // int intValue; - // if (int.TryParse(value.ToString(), out intValue)) - // { - // hex = intValue.ToString("X"); - // } - // return $"{dc} ({hex})"; - // } - // else - // { - // return "?"; - // } - - - // } - - // public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - // { - // throw new NotImplementedException(); - // } - //} - - /// - /// Interaction logic for MainWindow.xaml - /// - public partial class MainWindow - { - private Timer tmrAutoDetect; - - public EventHandler OnPcbIdDetect; - - private Int32 intervalWithoutDetect = 1000; - private Int32 intervalWithDetect = 10000; - private String _currentPcbID; - - - public PickingViewModel PickingData = new PickingViewModel(); - - public String CurrentPcbID - { - set - { - if (_currentPcbID != value && !(string.IsNullOrEmpty(_currentPcbID) && value == null)) - { - - if (_currentPcbID != value) - { - - if (!string.IsNullOrEmpty(_currentPcbID) && string.IsNullOrEmpty(value)) - { - _currentPcbID = value; - updateUi(lblPcbID, _currentPcbID); - - - } - else - { - _currentPcbID = value; - updateUi(lblPcbID, _currentPcbID); - - if (!string.IsNullOrEmpty(_currentPcbID)) - { - GetPcbMapping(_currentPcbID); - } - } - } - OnPcbIdDetect?.Invoke(CurrentPcbID, EventArgs.Empty); - } - - } - get => _currentPcbID; - } - - public enum uiState - { - not_connected, - connected - } - - private uiState _currentState; - public uiState CurrentState - { - set - { - _currentState = value; - updateUi(lblState, _currentState.ToString()); - } - get => _currentState; - } - - private String _lastMsg; - public String LastMsg - { - set - { - _lastMsg = value; - updateUi(lblMessage, _lastMsg); - } - get => _lastMsg; - } - - public MainWindow() - { - try - { - if (true) - { - - } - InitializeComponent(); - - } - catch (Exception ex) - { - - MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace); - } - - } - public ApplicationSettings Settings { get; set; } - private void Window_Initialized(Object sender, EventArgs e) - { - var configfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - nameof(Hardware.WaterMeter.Genesis), ProgramConfig.SerialConfigFileName); - - if (!File.Exists(configfile)) - { - throw new ApplicationException($"Configuration file {configfile} not found "); - } - var tr = new StreamReader(configfile); - var meterConfigList = JsonConvert.DeserializeObject(tr.ReadToEnd()); - - cbxSlotBox.Items.Clear(); - foreach (var item in meterConfigList.OrderBy(s => s.Slot)) - { - cbxSlotBox.Items.Add(item.Slot); - } - - cbxSlotBox.SelectedIndex = 0; - tmrAutoDetect = new Timer(intervalWithoutDetect); - tmrAutoDetect.Elapsed += TmrAutoDetect_Elapsed; - tmrAutoDetect.Enabled = false; - - - Settings = new ApplicationSettings("ProductionUiConfig.json"); - - - useSetting(true); - } - - private void TmrAutoDetect_Elapsed(Object sender, ElapsedEventArgs e) - { - tmrAutoDetect.Enabled = false; - var hasDetect = Detect(true, 1); - if (hasDetect) - { - tmrAutoDetect.Interval = intervalWithDetect; - } - else - { - tmrAutoDetect.Interval = intervalWithoutDetect; - } - tmrAutoDetect.Enabled = Settings.AutoDetect; - } - - - private void BtnConnect_Click(Object sender, RoutedEventArgs e) - { - var hasDetect = Detect(false, (Int32)cbxSlotBox.SelectedValue); - - Settings.Slot = (Int32)cbxSlotBox.SelectedValue; - storeSetting(); - } - - private void updateUi(ContentControl c, String content) - { - c.Dispatcher.Invoke(DispatcherPriority.Normal, - new Action(() => { c.Content = content; })); - } - private void updateUi(TextBox c, String content) - { - c.Dispatcher.Invoke(DispatcherPriority.Normal, - new Action(() => { c.Text = content; })); - } - private void updateUi(TextBlock c, String content) - { - c.Dispatcher.Invoke(DispatcherPriority.Normal, - new Action(() => { c.Text = content; })); - } - - private MeterBatch CurrentBatch; - private IGenesisMeter _currentMeter; - private Boolean detectIsLocked; - - private IGenesisMeter CurrentMeter - { - get => _currentMeter; - set - { - _currentMeter = value; - if (ucFinalRadioTest != null) - { - if (_currentMeter?.PcbId != null) - { - // ucFinalRadioTest.GenesisMeter = value; - } - else - { - // ucFinalRadioTest.GenesisMeter = null; - } - - } - } - } - - private Boolean Detect(Boolean ignoreErrors, Int32 slot) - { - if (!detectIsLocked) - { - LastMsg = "Start Detect"; - Boolean hasDetect = false; - if (string.IsNullOrEmpty(CurrentPcbID) || CurrentMeter == null) - { - var mb = new MeterBatch(); - var tryMeter = new GenesisMeter(); - try - { - tryMeter.SetupFromConfigFile(slot); - mb.AddMeter(tryMeter); - tryMeter.Logout(); - LastMsg = "Try to get PcbID"; - CurrentPcbID = tryMeter.GetPcbId(); - - hasDetect = !string.IsNullOrEmpty(CurrentPcbID); - CurrentBatch = mb; - CurrentMeter = tryMeter; - if (hasDetect) - { - LastMsg = $"New PcbID detected {CurrentPcbID}"; - - CurrentMeter.Login(); - } - else - { - LastMsg = "No Meter found"; - DisposeAllConnections(); - } - - } - catch (Exception e) - { - if (!ignoreErrors) - { - MessageBox.Show($"Error occur.{ Environment.NewLine} {e.Message}"); - } - - } - - } - else - { - LastMsg = "Check if Meter is still connected"; - var ret = CurrentMeter.GetPcbId(); - if (string.IsNullOrEmpty(ret) || ret != CurrentPcbID) - { - LastMsg = "Meter connection lost"; - hasDetect = false; - DisposeAllConnections(); - - CurrentPcbID = ""; - } - else - { - LastMsg = "Meter is still connected"; - hasDetect = true; - } - } - return hasDetect; - } - - LastMsg = "Meter is still connected (locked)"; - return true; - } - - - - private void Window_Closing(Object sender, CancelEventArgs e) - { - DisposeAllConnections(); - } - - private void DisposeAllConnections() - { - - if (CurrentBatch != null) - { - CurrentBatch.RemoveAllMeters(); - if (CurrentMeter != null) - { - CurrentMeter.Dispose(); - } - CurrentBatch.Dispose(); - } - PickingData.Empty(); - - } - - - - - private void GetPcbMapping(String pcbID) - { - if (string.IsNullOrEmpty(pcbID)) - { - return; - } - var url = $"{ServiceUrls.MarriageServiceUrl()}GetSerialNumberAndOrderNumber?PcbId={pcbID}&withRadioAdress=true"; - - Task.Run(() => - { - try - { - var responseJson = LocalWebRequest.GetRequest(url); - var a = JsonConvert.DeserializeObject(responseJson); - - - if (ucFinalRadioTest != null) - { - var tmpInt = 0; - int.TryParse(a[1], out tmpInt); - // ucFinalRadioTest.OrderNumber = tmpInt; - - tmpInt = 0; - if (a.Length > 2) - { - int.TryParse(a[2], out tmpInt); - - } - - //ucFinalRadioTest.RadioAddress = tmpInt; - // ucFinalRadioTest.SerialNumber = a[0] + "/" + a[3]; - - } - - - } - catch (Exception ex) - { - if (ex is WebException) - { - MessageBox.Show($"Error on Store: {Environment.NewLine} { ((WebException)ex).Message}"); - } - - MessageBox.Show(ex.Message); - } - }); - } - - - - - - - - private void Button_Click(Object sender, RoutedEventArgs e) - { - - } - - private void UcFinalRadioTest_OnLockMeter(Object sender, EventArgs e) - { - detectIsLocked = true; - - } - - private void UcFinalRadioTestOnOnReleaseMeter(Object sender, EventArgs e) - { - detectIsLocked = false; - //ucFinalRadioTest.SetUpBlank(false); - } - - - private void BtnSwitchAutoDetect_Click(Object sender, RoutedEventArgs e) - { - Settings.AutoDetect = !Settings.AutoDetect; - storeSetting(); - useSetting(); - } - - private void CbxSlotBox_SelectionChanged(Object sender, SelectionChangedEventArgs e) - { - - } - private void storeSetting() - { - Settings.Update("ProductionUiConfig.json"); - } - - - - private void useSetting(Boolean setSlot = false) - { - tmrAutoDetect.Enabled = Settings.AutoDetect; - tblkAutodetectState.Text = "Off"; - if (Settings.AutoDetect) - { - tblkAutodetectState.Text = "On"; - } - if (setSlot) - { - cbxSlotBox.SelectedValue = Settings.Slot; - } - } - - private void StackPanel_SizeChanged(Object sender, SizeChangedEventArgs e) - { - ucFinalRadioTest.Height = e.NewSize.Height; - - } - - } -} diff --git a/Common/Production/ProductionUiCordonel/MultiMode.xaml b/Common/Production/ProductionUiCordonel/MultiMode.xaml deleted file mode 100644 index 3e3fd0a6..00000000 --- a/Common/Production/ProductionUiCordonel/MultiMode.xaml +++ /dev/null @@ -1,152 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/Common/Production/ProductionUiCordonel/MultiMode.xaml.cs b/Common/Production/ProductionUiCordonel/MultiMode.xaml.cs deleted file mode 100644 index 8a7b6e0d..00000000 --- a/Common/Production/ProductionUiCordonel/MultiMode.xaml.cs +++ /dev/null @@ -1,206 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; -using Xylem.Common.Production.ProductionUiCordonel.Model; - -namespace Xylem.Common.Production.ProductionUiCordonel -{ - /// - /// Interaktionslogik für MultiMode.xaml - /// - public partial class MultiMode : Window - { - //#region Raw Input API - - //[DllImport("User32.dll")] - //extern static uint GetRawInputDeviceList(IntPtr pRawInputDeviceList, ref uint uiNumDevices, uint cbSize); - - //[DllImport("User32.dll")] - //extern static uint GetRawInputDeviceInfo(IntPtr hDevice, uint uiCommand, IntPtr pData, ref uint pcbSize); - - //[DllImport("User32.dll")] - //extern static bool RegisterRawInputDevices(RAWINPUTDEVICE[] pRawInputDevice, uint uiNumDevices, uint cbSize); - - //[DllImport("User32.dll")] - //extern static uint GetRawInputData(IntPtr hRawInput, uint uiCommand, IntPtr pData, ref uint pcbSize, uint cbSizeHeader); - - //#endregion - - MultiModeMasterViewModel multiModeMasterViewModel = new MultiModeMasterViewModel(); - - private List Childs = new List(); - - public ApplicationSettings AppSettings { get; private set; } - //class RawInputDevice : InputDevice - //{ - // public override IInputElement Target => throw new NotImplementedException(); - - // public override PresentationSource ActiveSource => throw new NotImplementedException(); - //} - public MultiMode() - { - - DataContext = multiModeMasterViewModel; - - InitializeComponent(); - Topmost = false; - } - private void keyUp(Object sender, KeyEventArgs e) - { - - } - public void SetBaseFocus() - { - //foreach (var item in Childs) - //{ - // item.Key.Activate(); - //} - //this.Activate(); - //txtBarcodeInput.Focus(); - - } - - - private MultiModeChild addChild(IMultiModeChildViewModel model) - { - var a = new MultiModeChild(model); - - a.Show(); - return a; - } - CancellationTokenSource cts; - - private void Window_Loaded(Object sender, RoutedEventArgs e) - { - cts = new CancellationTokenSource(); - AppSettings = new ApplicationSettings("MultiProductionUiConfig.json"); - multiModeMasterViewModel.StartPicking(cts); - //var trigger = new List(); - - //if (AppSettings.ChildForms == null || !AppSettings.ChildForms.Any()) - //{ - // AppSettings.ChildForms = new List(); - - // AppSettings.ChildForms.Add(new ApplicationSettings.MultiFormChilds() { Name = "Picking", Slot = 1, ViewModelType = typeof(PickingMultiModeViewModel), StartPos = null, Visisble = true, TextPort = "COM11" }); - // AppSettings.ChildForms.Add(new ApplicationSettings.MultiFormChilds() { Name = "PressureHE", Slot = 3, ViewModelType = typeof(PressureMultiModeViewModel), StartPos = null, Visisble = true, TextPort = null }); - // AppSettings.ChildForms.Add(new ApplicationSettings.MultiFormChilds() { Name = "PressureHY", Slot = 1, ViewModelType = typeof(PressureMultiModeViewModel), StartPos = null, Visisble = true, TextPort = null }); - // AppSettings.ChildForms.Add(new ApplicationSettings.MultiFormChilds() { Name = "Marriage", Slot = 4, ViewModelType = typeof(MarriageMultiModeViewModel), StartPos = null, Visisble = true, TextPort = "COM1" }); - // AppSettings.Update("MultiProductionUiConfig.json"); - //} - - - ////AppSettings.ChildForms.ForEach(c => trigger.Add(c.TextPort.ToString())); - - //cts = new CancellationTokenSource(); - - //foreach (var item in AppSettings.ChildForms) - //{ - // if (item.Visisble) - // { - - - // IMultiModeChildViewModel mdl = null; - // if (item.ViewModelType == typeof(PickingMultiModeViewModel)) - // { - // mdl = new PickingMultiModeViewModel(item.Name, item.Slot, trigger, AppSettings.StationId); - // } - // else if (item.ViewModelType == typeof(PressureMultiModeViewModel)) - // { - // mdl = new PressureMultiModeViewModel(item.Name, item.Slot, trigger, AppSettings.StationId); - // } - // else if (item.ViewModelType == typeof(MarriageMultiModeViewModel)) - // { - // mdl = new MarriageMultiModeViewModel(item.Name, item.Slot, trigger, AppSettings.StationId); - // } - // if (mdl == null) - // { - // throw new ApplicationException("Bad configuration or old software"); - // } - // var child = addChild(mdl); - - // child.StartTextInputListener(item.TextPort, cts.Token); - - // if (item.StartPos != null) - // { - // child.WindowStartupLocation = WindowStartupLocation.Manual; - // child.Top = item.StartPos.Top; - // child.Left = item.StartPos.Left; - // child.Height = item.StartPos.Height; - // child.Width = item.StartPos.Width; - // child.UseDefaultPos = false; - // } - // child.PosChanged += delegate (object val, EventArgs a) - // { - // if (val is MultiModeChild mmc) - // { - // if (mmc.ViewModel is BaseMultiModeChildViewModel baseChild) - // { - // var aasd = AppSettings.ChildForms.FirstOrDefault(c => c.Name == baseChild.ChildName); - // aasd.StartPos = new ApplicationSettings.Pos() { Height = mmc.Height, Left = mmc.Left, Top = mmc.Top, Width = mmc.Width }; - - // AppSettings.Update("MultiProductionUiConfig.json"); - // } - // } - - // }; - - - // child.Show(); - - // Childs.Add(child); - - // } - - //} - - - - //SetBaseFocus(); - } - - private void delegeChild_PosChange(Object sender, EventArgs e) - { - throw new NotImplementedException(); - } - - private void TxtBarcodeInput_TextChanged(Object sender, TextChangedEventArgs e) - { - //if (sender is TextBox text) - //{ - // if (text.Text.ToLower().Contains("clear")) - // { - // text.Text = string.Empty; - // } - // else if (text.Text.Contains(System.Environment.NewLine)) - // { - // foreach (var dispatchChild in Childs.Where(x => x.Value == text.Text[0])) - // { - // dispatchChild.Key.InputText(text.Text.Substring(1, text.Text.Length - 1).Trim()); - // } - - // text.Text = ""; - // SetBaseFocus(); - // } - - //} - - } - - private void Window_Closed(Object sender, EventArgs e) - { - - cts.Cancel(); - - - foreach (var item in Childs) - { - item.Dispose(); - - item.Close(); - } - } - } -} diff --git a/Common/Production/ProductionUiCordonel/MultiModeChild.xaml b/Common/Production/ProductionUiCordonel/MultiModeChild.xaml deleted file mode 100644 index 5b560b2f..00000000 --- a/Common/Production/ProductionUiCordonel/MultiModeChild.xaml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - -