From 2b3eb5f10a234a2af1a38abba4a23d28c7fa73ec Mon Sep 17 00:00:00 2001 From: Michal Buzik Date: Sun, 15 Feb 2026 22:45:13 +0100 Subject: [PATCH] Refactor iPerl communication services: replace legacy calibration and configuration methods with `OptoHeadTest` functionality, streamline diagnostic LED state handling, and clean up unused code. --- .../CommCompletedEventArgs.cs | 2 +- .../IperlHatProtocol/IperlHatFrameBuilder.cs | 10 +- .../IperlHatProtocol/IperlHatFrameParser.cs | 18 +- ...stants.cs => IperlHatProtocolConstants.cs} | 2 +- .../C4/IperlHatProtocol/IperlHatResponse.cs | 61 +- .../C4/diagnosticLed/DiagnosticLedState.cs | 7 +- .../C4/hexLogger/IpelHatCommandDecoder.cs | 4 +- .../C4/hexLogger/IperlHatLogger.cs | 2 +- .../C4/protocolCommons/ProtocolStatuses.cs | 5 +- .../communication/OptoHeadTest.cs | 215 ++- .../communication/RadioService.cs | 182 ++- .../communication/Utils/SerialDriver.cs | 6 +- .../iPerlCommunicationForm.cs | 1235 ++++++++--------- .../iPerlCommunicationParams.cs | 2 +- .../iPerlHead/ConfigStruct.cs | 303 ++-- .../iPerlCommunication/iPerlHead/IperlHead.cs | 2 +- .../iPerlHead/IperlHeadTestCtrl.cs | 8 +- .../iPerlHead/SimulationServices.cs | 28 +- TBF/TBF.csproj | 10 +- 19 files changed, 1154 insertions(+), 948 deletions(-) rename TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/{Constants.cs => IperlHatProtocolConstants.cs} (91%) diff --git a/TBF/Rig/TestMethods/iPerlCommunication/CommCompletedEventArgs.cs b/TBF/Rig/TestMethods/iPerlCommunication/CommCompletedEventArgs.cs index c23bb0a47..b0bec23db 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/CommCompletedEventArgs.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/CommCompletedEventArgs.cs @@ -31,7 +31,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication ThreadId, WMNr0, (Ihead != null) ? Ihead.Name : "null", - Wm.WMPosition, + (Wm != null) ? Wm.WMPosition : -1, (CommMessage != null) ? CommMessage : "null", CommErr); } diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatFrameBuilder.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatFrameBuilder.cs index b7535b9a7..078d526f4 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatFrameBuilder.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatFrameBuilder.cs @@ -14,7 +14,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtoc public IperlHatFrameBuilder RequestResponse(bool enabled) { - _direction = enabled ? TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Write : TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Read; + _direction = enabled ? TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Write : TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Read; return this; } @@ -57,7 +57,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtoc public IperlHatFrameBuilder SetVersionCommand() { _commandBytes.Add((byte)ProtocolCommand.Question); - _payload.AddRange(TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Version); + _payload.AddRange(TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Version); return this; } @@ -110,19 +110,19 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtoc return new IperlHatFrame( - TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Start, + TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start, _direction, length, _commandBytes.ToArray(), _payload.ToArray(), - TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.End); + TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End); } public byte[] BuildBytes() { IperlHatFrame frame = BuildFrame(); - if (frame.CommandInformation.Length > 0 && frame.CommandInformation[0] == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Question) + if (frame.CommandInformation.Length > 0 && frame.CommandInformation[0] == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question) { var bytes = new List { diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatFrameParser.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatFrameParser.cs index 59d2ef724..e57dafadd 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatFrameParser.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatFrameParser.cs @@ -16,28 +16,28 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtoc - if (data[0] != TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Start) + if (data[0] != TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start) { //if version parse version - if (data[0] == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Question) + if (data[0] == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question) { //Define Question answer - var prefix = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Question }; - var end = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.End }; + var prefix = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question }; + var end = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End }; if (IsPrefixValid(data, prefix, end)) { //whole payload may be like "vers: Harry T:B800, V:06.06.01, FW:190215, 7ECE, B1.6.01, HW:4, Serial:0" - prefix = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Question }; + prefix = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question }; byte[] payloadVersion = ExtractPayloadUsePrefix(data, prefix, end); - return new IperlHatResponse(TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Question, payloadVersion.Length > 0 ? TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.StatusOk : TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.StatusNok, payloadVersion); + return new IperlHatResponse(TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question, payloadVersion.Length > 0 ? TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusOk : TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusNok, payloadVersion); } } throw new FormatException("Invalid START byte."); } - if (data[1] != TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Read) + if (data[1] != TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Read) throw new FormatException("Frame is no Response."); byte length = data[2]; @@ -47,8 +47,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtoc byte direction = data[1]; byte status = data[3]; - var prefixCommand = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Start,direction,length,status }; - var endCommand = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.End }; + var prefixCommand = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start,direction,length,status }; + var endCommand = new List{ TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End }; byte[] payload = ExtractPayloadUsePrefix(data,prefixCommand,endCommand); diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/Constants.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatProtocolConstants.cs similarity index 91% rename from TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/Constants.cs rename to TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatProtocolConstants.cs index 3d06977ea..4e055e384 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/Constants.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatProtocolConstants.cs @@ -1,6 +1,6 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol { - public static class Constants + public static class IperlHatProtocolConstants { public const byte Start = 0x53; //'S' public const byte Write = 0x57; // 'W' diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatResponse.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatResponse.cs index d60214966..b1ca70750 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatResponse.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/IperlHatProtocol/IperlHatResponse.cs @@ -8,7 +8,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtoc private byte Status { get; } public byte[] Payload { get; } - public bool IsOk => Status == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.StatusOk; + public bool IsOk => Status == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.StatusOk; public IperlHatResponse(byte control, byte status, byte[] payload) { @@ -16,7 +16,66 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.IperlHatProtoc Status = status; Payload = payload ?? Array.Empty(); } + + public int GetResponse(ref bool isInt) + { + if (Payload.Length > 0 && Payload.Length <= 1) + { + isInt = true; + return Payload[0]; + } + + isInt = false; + return 0xFD; + } + public T GetResponse(out bool ok) where T : struct + { + ok = false; + + // we expect exactly 1 byte payload + if (Payload == null || Payload.Length != 1) + return default; + + byte raw = Payload[0]; + + Type t = typeof(T); + + // ----- BYTE ----- + if (t == typeof(byte)) + { + ok = true; + return (T)(object)raw; + } + + // ----- INT ----- + if (t == typeof(int)) + { + ok = true; + return (T)(object)(int)raw; + } + + // ----- USHORT ----- + if (t == typeof(ushort)) + { + ok = true; + return (T)(object)(ushort)raw; + } + + // ----- ENUM ----- + if (t.IsEnum) + { + // check if value exists in enum + if (!Enum.IsDefined(t, raw)) + return default; + + ok = true; + return (T)Enum.ToObject(t, raw); + } + + // unsupported type + return default; + } public string GetAsciiPayload() { diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/diagnosticLed/DiagnosticLedState.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/diagnosticLed/DiagnosticLedState.cs index cc958fac0..033b93658 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/diagnosticLed/DiagnosticLedState.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/diagnosticLed/DiagnosticLedState.cs @@ -90,6 +90,11 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed /// electrode voltage noise, and ADC offset learning status. /// /// - State7 = 0x07 + State7 = 0x07, + + /// + /// Unknown state. + /// + StatusUnknown = 0xFF, } } diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/hexLogger/IpelHatCommandDecoder.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/hexLogger/IpelHatCommandDecoder.cs index 2a7545fb0..65bed0d29 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/hexLogger/IpelHatCommandDecoder.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/hexLogger/IpelHatCommandDecoder.cs @@ -9,10 +9,10 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger public static string DescribeDirection(byte direction) { - if (direction == IperlHatProtocol.Constants.Write) + if (direction == IperlHatProtocol.IperlHatProtocolConstants.Write) return "(WRITE - OUTGOING)"; - if (direction == IperlHatProtocol.Constants.Read) + if (direction == IperlHatProtocol.IperlHatProtocolConstants.Read) return "(READ - INCOMING)"; return "INVALID CONTROL BITS (unsupported pattern)"; diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/hexLogger/IperlHatLogger.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/hexLogger/IperlHatLogger.cs index bfc1a7a99..63724f3ae 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/hexLogger/IperlHatLogger.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/hexLogger/IperlHatLogger.cs @@ -10,7 +10,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger if (frame == null || frame.Length < 5) return "Invalid frame"; - if (frame[2] == IperlHatProtocol.Constants.Question) + if (frame[2] == IperlHatProtocol.IperlHatProtocolConstants.Question) { return "TX Frame\n" + diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/protocolCommons/ProtocolStatuses.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/protocolCommons/ProtocolStatuses.cs index d6c4aa334..e4c014548 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/protocolCommons/ProtocolStatuses.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/C4/protocolCommons/ProtocolStatuses.cs @@ -4,7 +4,10 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommon { Idle = 0x01, Active = 0x02, - Inactive = 0x03, + EndOfLife = 0x03, + MeterTest = 0x04, + MeterTestEMF = 0x05, + Unknown = 0x00 } } \ No newline at end of file diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/OptoHeadTest.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/OptoHeadTest.cs index c44b51354..ae462c04d 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/OptoHeadTest.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/OptoHeadTest.cs @@ -2,6 +2,7 @@ using System; using System.IO.Ports; using Common; using log4net; +using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed; using TBF.Rig.TestMethods.iPerlCommunication.communication.Utils; using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead; @@ -26,14 +27,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication } - public void CloseConnection() + private void CloseConnection() { if (serialDriver != null) serialDriver.CloseConnection(); } - public static string ReadRequest_PCB(IperlHead iHead) + public static string ReadRequest_PCB(ref IperlHead iHead) { if (iHead.DebugLevel == DebugMode.Simulate) { @@ -48,7 +49,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication serialDriver = BuildConnection(iHead); RadioService headService = new RadioService(serialDriver); - string serialNo = headService.ReadRequest_PCB(iHead); + string serialNo = headService.ReadRequest_PCB(ref iHead); return serialNo; } } @@ -60,14 +61,67 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication return ""; } - public static string SetTestMode(IperlHead iHead) + /// + /// Set Test mode + /// + /// + /// + public static bool SetTestMode(ref IperlHead iHead) + { + bool activityModeActive = SetActivityMode_Active(iHead); + bool optActiveMode = SetOptTestMode(ref iHead); + + + return (optActiveMode && activityModeActive); + } + + /// + /// Set Active mode + /// + /// + /// + public static bool SetActiveMode(ref IperlHead iHead) + { + bool optActiveMode = SetOptActiveMode(iHead); + bool activityModeIdle = SetActivityMode_Idle(iHead); + + return (optActiveMode && activityModeIdle); + } + + /// + /// Set Test mode - string response + /// + /// + /// + /// + public static string SetTestMode(ref IperlHead iHead, ref bool isTestModeSuccessful) { if (iHead.DebugLevel == DebugMode.Simulate) { + isTestModeSuccessful = true; return "-OK Simulated response-"; } - + try + { + isTestModeSuccessful = SetTestMode(ref iHead); + return isTestModeSuccessful ? "Set Test Mode - OK" : "Set Test Mode - FAILED"; + }catch (Exception ex) + { + return "Set Test Mode - Exception"; + } + } + + + + /// + /// Set Optical -> Test mode + /// + /// + /// + /// + private static bool SetOptTestMode(ref IperlHead iHead) + { try { if (iHead != null) @@ -76,25 +130,50 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication serialDriver = BuildConnection(iHead); RadioService headService = new RadioService(serialDriver); - string answer = headService.SetTestMode(iHead); - return answer; + var optTestMode = headService.SetOptTestMode(iHead); + iHead.ConfigStruct.OpthoStatusMode = optTestMode ? DiagnosticLedState.State4 : DiagnosticLedState.StatusUnknown; + return optTestMode; } } catch (Exception ex) { - return (ex.Message.ToString()); + throw ex; } - - return ""; + return false; } - public static string SetActiveMode(IperlHead iHead) + /// + /// Set Active mode - string response + /// + /// + /// + /// + public static string SetActiveMode(ref IperlHead iHead, ref bool isTestModeSuccessful) { if (iHead.DebugLevel == DebugMode.Simulate) { + isTestModeSuccessful = true; return "-OK Simulated response-"; } + try + { + isTestModeSuccessful = SetActiveMode(ref iHead); + return isTestModeSuccessful ? "Set Active Mode - OK" : "Set Active Mode - FAILED"; + } + catch (Exception ex) + { + return "Set Active Mode - Exception"; + } + } + /// + /// Set Optical -> Active mode + /// + /// + /// + /// + private static bool SetOptActiveMode(IperlHead iHead) + { try { if (iHead != null) @@ -103,21 +182,127 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication serialDriver = BuildConnection(iHead); RadioService headService = new RadioService(serialDriver); - string answer = headService.SetActiveMode(iHead); - return answer; + return headService.SetOptActiveMode(iHead); } } catch (Exception ex) { - return (ex.Message.ToString()); + throw ex; } - return ""; + return false; + } + + /// + /// Set activity mode to active + /// + /// + /// + /// + private static bool SetActivityMode_Active(IperlHead iHead) + { + try + { + if (iHead != null) + { + if (serialDriver == null) + serialDriver = BuildConnection(iHead); + + RadioService headService = new RadioService(serialDriver); + return headService.SetActivityMode_Active(iHead); + } + } + catch (Exception ex) + { + throw ex; + } + + return false; + } + + /// + /// Set activity mode to idle + /// + /// + /// + /// + private static bool SetActivityMode_Idle(IperlHead iHead) + { + try + { + if (iHead != null) + { + if (serialDriver == null) + serialDriver = BuildConnection(iHead); + + RadioService headService = new RadioService(serialDriver); + return headService.SetActivityMode_Idle(iHead); + } + } + catch (Exception ex) + { + throw ex; + } + + return false; } + public void Dispose() { CloseConnection(); } + + /// + /// Read configuration from iHead + /// DiagnosticLedState is not readable, mus only be set! + /// + /// + /// + /// + public static bool ReadConfiguration(ref IperlHead iHead, DiagnosticLedState ledState ) + { + if (iHead.DebugLevel == DebugMode.Simulate) + { + return true; + } + + try + { + + if (iHead != null) + { + iHead.ConfigStruct = new ConfigStruct(); + + if (serialDriver == null) + serialDriver = BuildConnection(iHead); + + RadioService headService = new RadioService(serialDriver); + iHead.ConfigStruct.PCBNumberString = headService.ReadRequest_PCB(ref iHead); + iHead.ConfigStruct.StatusMode = headService.GetActivityStatusMode(iHead); + if (ledState != DiagnosticLedState.StatusUnknown) // do set + { + iHead.ConfigStruct.OpthoStatusMode = headService.SetOptoStatusMode(iHead, ledState); + } + else + { + iHead.ConfigStruct.OpthoStatusMode = DiagnosticLedState.StatusUnknown; + } + + iHead.ConfigStruct.Version = headService.GetVersion(iHead); + + return true; + } + + else + { + return false; + } + } + catch (Exception ex) + { + return false; + } + } } } \ No newline at end of file diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/RadioService.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/RadioService.cs index 219ebb6ce..b1e3affe2 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/RadioService.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/RadioService.cs @@ -18,7 +18,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication this.serialDriver = serialDriver; } - public string ReadRequest_PCB(IperlHead iHead) + public string ReadRequest_PCB(ref IperlHead iHead) { if (!serialDriver.IsOpen()) { @@ -40,13 +40,161 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication IperlHatResponse decoded = parser.Parse(rawData); if (decoded.IsOk) { - return decoded.GetAsciiPayload(); + string asciiPayload = decoded.GetAsciiPayload(); + if (iHead.ConfigStruct != null) // store mechanism + { + iHead.ConfigStruct.PCBNumberString = asciiPayload; + } + return asciiPayload; } return null; } + + public ProtocolStatuses GetActivityStatusMode(IperlHead iHead) + { + if (!serialDriver.IsOpen()) + serialDriver.Open(); - public string SetTestMode(IperlHead iHead) + var request = new IperlHatFrameBuilder() + .RequestResponse(true) + .AddCommand(ProtocolCommand.ViewState) + .BuildBytes(); + + byte[] rawData = serialDriver.SendAndWait(request, 10000); + if (rawData == null) + return ProtocolStatuses.Unknown; + + var parser = new IperlHatFrameParser(); + IperlHatResponse decoded = parser.Parse(rawData); + + if (!decoded.IsOk) + return ProtocolStatuses.Unknown; + + ProtocolStatuses statusMode = decoded.GetResponse(out bool isOK); + + if (!isOK) + return ProtocolStatuses.Unknown; // wrong payload + + return statusMode; + } + + public DiagnosticLedState SetOptoStatusMode(IperlHead iHead, DiagnosticLedState opthoStatusMode) + { + if (!serialDriver.IsOpen()) + serialDriver.Open(); + + var request = new IperlHatFrameBuilder() + .RequestResponse(true) + .AddDeviceCommand(ProtocolDeviceSubCommand.SetDiagnosticLEDState) + .AddPayload(opthoStatusMode) + .BuildBytes(); + + byte[] rawData = serialDriver.SendAndWait(request, 10000); + if (rawData == null) + return DiagnosticLedState.StatusUnknown; + + var parser = new IperlHatFrameParser(); + IperlHatResponse decoded = parser.Parse(rawData); + + // if is response ok - it set it correctly + if (!decoded.IsOk) + return DiagnosticLedState.StatusUnknown; + + return opthoStatusMode; + } + + + private static ushort SafeIntToUShort(int value) + { + if (value < ushort.MinValue || value > ushort.MaxValue) + return 0xFD; // your error code + + return (ushort)value; + } + + + public string GetVersion(IperlHead iHead) + { + if (!serialDriver.IsOpen()) + { + serialDriver.Open(); + } + + byte[] request = new IperlHatFrameBuilder() + .RequestResponse(true) + .AddCommand(ProtocolCommand.Question) + .AddPayload(IperlHatProtocolConstants.Version) + .BuildBytes(); + + + byte[] rawData = serialDriver.SendAndWait(request, 10000); + if (rawData == null) + return ""; + + // parse rawData + var parser = new IperlHatFrameParser(); + IperlHatResponse decoded = parser.Parse(rawData); + if (decoded.IsOk) + { + return decoded.GetAsciiPayload(); + } + + return ""; + } + + + public bool SetActivityMode_Active(IperlHead iHead) + { + if (!serialDriver.IsOpen()) + { + serialDriver.Open(); + } + + //Set LED to state 4 + byte[] request = new IperlHatFrameBuilder() + .RequestResponse(true) + .AddCommand(ProtocolCommand.SetState) + .AddSubCommand(ProtocolStatuses.Active) // Active + .BuildBytes(); + + byte[] rawData = serialDriver.SendAndWait(request, 2000); + if (rawData == null) + return false; + + + // parse rawData + var parser = new IperlHatFrameParser(); + IperlHatResponse decoded = parser.Parse(rawData); + return decoded.IsOk; + } + + public bool SetActivityMode_Idle(IperlHead iHead) + { + if (!serialDriver.IsOpen()) + { + serialDriver.Open(); + } + + //Set Activity State Idle + byte[] request = new IperlHatFrameBuilder() + .RequestResponse(true) + .AddCommand(ProtocolCommand.SetState) + .AddSubCommand(ProtocolStatuses.Idle) + .BuildBytes(); + + byte[] rawData = serialDriver.SendAndWait(request, 2000); + if (rawData == null) + return false; + + + // parse rawData + var parser = new IperlHatFrameParser(); + IperlHatResponse decoded = parser.Parse(rawData); + return decoded.IsOk; + } + + public bool SetOptTestMode(IperlHead iHead) { if (!serialDriver.IsOpen()) { @@ -60,23 +208,13 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication byte[] rawData = serialDriver.SendAndWait(request, 1000); if (rawData == null) - return null; + return false; // parse rawData var parser = new IperlHatFrameParser(); IperlHatResponse decoded = parser.Parse(rawData); - if (decoded.IsOk) - { - - - //correct or incorrect response - //okResponse, errorResponse - - return "Set Test Mode - OK"; - } - - return "Set Test Mode - FAILED"; + return decoded.IsOk; } @@ -85,7 +223,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication /// /// /// - public string SetActiveMode(IperlHead iHead) + public bool SetOptActiveMode(IperlHead iHead) { if (!serialDriver.IsOpen()) { @@ -97,21 +235,15 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication .AddDiagnosticLedState(DiagnosticLedState.StateOFF) .BuildBytes(); - byte[] rawData = serialDriver.SendAndWait(request, 1000); + byte[] rawData = serialDriver.SendAndWait(request, 2000); if (rawData == null) - return null; + return false; // parse rawData var parser = new IperlHatFrameParser(); IperlHatResponse decoded = parser.Parse(rawData); - if (decoded.IsOk) - { - - return "Set Active Mode - OK"; - } - - return "Set Active Mode - FAILED"; + return decoded.IsOk; } } } \ No newline at end of file diff --git a/TBF/Rig/TestMethods/iPerlCommunication/communication/Utils/SerialDriver.cs b/TBF/Rig/TestMethods/iPerlCommunication/communication/Utils/SerialDriver.cs index cd0e5bb1d..fa29f3ea1 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/communication/Utils/SerialDriver.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/communication/Utils/SerialDriver.cs @@ -204,13 +204,13 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.Utils byte readByte = (byte)_serialPort.ReadByte(); //I have START - if (readByte == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Start) + if (readByte == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Start) { iWordCounter++; isStart = true; } // I have QUESTION - if (readByte == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.Question) + if (readByte == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.Question) { iWordCounter++; isQuestion = true; @@ -236,7 +236,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.communication.Utils break; } //if we read END - if (isQuestion && readByte == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.Constants.End) + if (isQuestion && readByte == TestMethods.iPerlCommunication.communication.C4.IperlHatProtocol.IperlHatProtocolConstants.End) { break; } diff --git a/TBF/Rig/TestMethods/iPerlCommunication/iPerlCommunicationForm.cs b/TBF/Rig/TestMethods/iPerlCommunication/iPerlCommunicationForm.cs index d258eb99e..4fa754c8e 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/iPerlCommunicationForm.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/iPerlCommunicationForm.cs @@ -20,6 +20,9 @@ using TBF.Rig.TestMethods.iPerlCommunication.iPerlHead; using Results.Entities; using static Sensus.iPerl.NfcHandler.MCI_Protocol; using System.Threading.Tasks; +using TBF.Rig.TestMethods.iPerlCommunication.communication; +using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed; +using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons; namespace TBF.Rig.TestMethods.iPerlCommunication { @@ -117,7 +120,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication if (iperlHead.DebugLevel != DebugMode.Normal) // Simulation { - return SimulationServices.ReadRequest(cfg, iperlHead, messageID, offset, length, out buffer); + throw new Exception("ReadRequestPort() is not supported in simulation mode."); + //return SimulationServices.ReadRequest(cfg, iperlHead, messageID, offset, length, out buffer); } if (iperlHead.CommInterface == CommunicationInterface.NFC) // NFC Interface @@ -711,41 +715,6 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// else if (wm == null) error = CommErr.CommFailed; else if (currentActivity.ToLower().Contains(ReadConfigurationStr.ToLower())) error = ReadConfiguration(ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == ReadCalibrationStr.ToLower()) error = ReadCalibration(ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == ReadCalibrationV4Str.ToLower()) error = ReadCalibrationV4(ihead, wm, ref resultStr); - else if (currentActivity.ToLower().Contains(WriteCalibrationFactorStr.ToLower())) error = WriteCalibrationFactor(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower().Contains(WriteCalibrationV4FactorsStr.ToLower())) error = WriteCalibrationV4Factors(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == NormalizeCalibrationFactorStr.ToLower()) error = NormalizeCalibrationFactor(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == NormalizeCalibrationV4FactorsStr.ToLower()) error = NormalizeCalibrationV4Factors(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == ReadQ2CorrectionStr.ToLower()) error = ReadQ2Correction(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == ResetQ2CorrectionStr.ToLower()) error = ResetQ2Correction(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == WriteDefaultQ2CorrectionsStr.ToLower()) error = WriteDefaultQ2Corrections(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == InitOrReadQ2CorrectionsStr.ToLower()) error = InitOrReadQ2Corrections(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == WriteQ2CorrectionStr.ToLower()) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Standard, null); - else if (currentActivity.ToLower() == WriteQ2CorrectionAltStr.ToLower()) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Dewa, null); - else if (currentActivity.ToLower().Contains(WriteQ2CorrectionGreeceStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Greece, currentActivity.Substring(WriteQ2CorrectionGreeceStr.Length).Trim()); - else if (currentActivity.ToLower().Contains(WriteQ2CorrectionRLStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.RL, currentActivity.Substring(WriteQ2CorrectionRLStr.Length).Trim()); - else if (currentActivity.ToLower().Contains(WriteQ2CorrectionLRStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.LR, currentActivity.Substring(WriteQ2CorrectionLRStr.Length).Trim()); - else if (currentActivity.ToLower() == WriteQ2CorrectionIncl05Str.ToLower()) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Standard_incl_05, null); - else if (currentActivity.ToLower() == WriteQ2CorrectionPlusIncl05Str.ToLower()) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Standard_plus_incl_05, null); - else if (currentActivity.ToLower() == WriteQ2CorrectionAltIncl05Str.ToLower()) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Dewa_incl_05, null); - else if (currentActivity.ToLower() == WriteQ2CorrectionPlusAltIncl05Str.ToLower()) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Dewa_plus_incl_05, null); - else if (currentActivity.ToLower().Contains(WriteQ2CorrectionGreeceIncl05Str.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Greece_incl_05, currentActivity.Substring(WriteQ2CorrectionGreeceIncl05Str.Length).Trim()); - else if (currentActivity.ToLower().Contains(WriteQ2CorrectionRLIncl05Str.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.RL_incl_05, currentActivity.Substring(WriteQ2CorrectionRLIncl05Str.Length).Trim()); - else if (currentActivity.ToLower().Contains(WriteQ2CorrectionLRIncl05Str.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.LR_incl_05, currentActivity.Substring(WriteQ2CorrectionLRIncl05Str.Length).Trim()); - else if (currentActivity.ToLower().Contains(UpdateBothQ2FactorsTestRLOnlyStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.UpdateBothQ2FactorsTestRLDir, null); - else if (currentActivity.ToLower().Contains(UpdateBothQ2FactorsTestLROnlyStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.UpdateBothQ2FactorsTestLRDir, null); - else if (currentActivity.ToLower().Contains(UpdateQ2CorrectionsStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.Update, currentActivity.Substring(UpdateQ2CorrectionsStr.Length).Trim()); - else if (currentActivity.ToLower().Contains(ConditnlUpdateQ2CorrectionsStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.ConditionalUpdate, currentActivity.Substring(ConditnlUpdateQ2CorrectionsStr.Length).Trim()); - else if (currentActivity.ToLower().Contains(ConditnlUpdateQ2CorrRLStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.ConditionalUpdateRL, currentActivity.Substring(ConditnlUpdateQ2CorrRLStr.Length).Trim()); - else if (currentActivity.ToLower().Contains(ConditnlUpdateQ2CorrLRStr.ToLower())) error = CalculateAndWriteQ2Corrections(threadID, ihead, wm, currentTest, ref resultStr, Q2CorrType.ConditionalUpdateLR, currentActivity.Substring(ConditnlUpdateQ2CorrLRStr.Length).Trim()); - else if (currentActivity.ToLower() == Reset2HzCorrectionStr.ToLower()) error = Reset2HzCorrection(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == Write2HzCorrectionStr.ToLower()) error = Write2HzCorrection(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == GetDefaultQ2CorrectionsStr.ToLower()) error = GetQ2PreCorrectionsFormRest(threadID, ihead, wm, ref resultStr); - else if (currentActivity.ToLower() == DewaReworkRLStr.ToLower()) error = DewaRework(ihead, wm, FlowDir.R_L, ref resultStr); - else if (currentActivity.ToLower() == DewaReworkLRStr.ToLower()) error = DewaRework(ihead, wm, FlowDir.L_R, ref resultStr); - else if (currentActivity.ToLower().Contains(StartTestingSealedMetersStr.ToLower())) error = StartTestingSealedMeter(ihead, wm, ref resultStr); - else if (currentActivity.ToLower().Contains(EndTestingSealedMetersStr.ToLower())) error = EndTestingSealedMeter(ihead, wm, ref resultStr); else if (currentActivity.ToLower().Contains(SimulateCmd.ToLower())) error = Simulate(ihead, wm, ref resultStr); #endif else @@ -847,6 +816,9 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// true on success static CommErr ReadConfiguration(IperlHead ihead, WaterMeter wm, ref string resultStr) { + // TODO BUMI in clasic case we need to read most of data - see ConfigStruct + + /// /// The activity is "Read configuration" (this enables the watermeter, resets error flag) /// or "Read configuration if enabled" (this keeps the error flag). @@ -858,18 +830,18 @@ namespace TBF.Rig.TestMethods.iPerlCommunication if (ihead.CommFailed) return CommErr.CommFailed; + //zeroing ihead.ConfigStruct = null; /// Clear previous ConfigStruct, avoid reuse of (not anymore valid) PCB Number CommErr error = CommErr.Read; int readRetVal = 0; /// Read configuration - byte[] config = null; - readRetVal = ReadRequestPort(ihead, MessageID.Configuration, StructName.Configuration, 0, ConfigStruct.Length, out config); - if (readRetVal == 0) + + if (OptoHeadTest.ReadConfiguration(ref ihead, DiagnosticLedState.StatusUnknown)) { error = CommErr.None; - ihead.ConfigStruct = ConfigStruct.FromByteArray(config); + ihead.ConfigStruct = new ConfigStruct(); //.FromByteArray(config); resultStr = ihead.ConfigStruct.ToString(1); } @@ -889,21 +861,27 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// true on success static CommErr SetTestMode(int threadId, IperlHead ihead, ref string resultStr) { + if (ihead.ConfigStruct == null) + { + log.Debug("ConfigStruct is null - created new in SetTestMode()"); + ihead.ConfigStruct = new ConfigStruct(); + } if (ihead.CommFailed || ihead.ConfigStruct == null) return CommErr.CommFailed; - Byte testModeConfig = 0xA0; /// Default value + //I will do communication to meter now + + DiagnosticLedState testModeConfig = DiagnosticLedState.State4; /// Default value /// - if (multiTestParams[currentActivityStep].Activity.Length > SetTestModeStr.Length) + + //string testModeConfigStr = multiTestParams[currentActivityStep].Activity.Substring(SetTestModeStr.Length + 1); + if (OptoHeadTest.SetTestMode(ref ihead)) { - string testModeConfigStr = multiTestParams[currentActivityStep].Activity.Substring(SetTestModeStr.Length + 1); - UInt16 byteVal; - if (UInt16.TryParse(testModeConfigStr, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out byteVal) && byteVal <= 255) - { - testModeConfig = (Byte)byteVal; /// Update with specified value - } + log.Debug("test mode activated now"); + testModeConfig = ihead.ConfigStruct.OpthoStatusMode; } + - if (ihead.ConfigStruct.MeterState == MeterState.Test && ihead.ConfigStruct.TestModeConfig == testModeConfig) + if (ihead.ConfigStruct.MeterState == ProtocolStatuses.Active/*Test*/ && ihead.ConfigStruct.TestModeConfig == testModeConfig) { /// Already in the correct test mode resultStr = "Already " + ihead.ConfigStruct.ToString(1); @@ -912,67 +890,25 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// Communication necessary CommErr error = CommErr.None; - - if (error==CommErr.None && (ihead.ConfigStruct.TestModeConfig != testModeConfig) && (ihead.ConfigStruct.MeterState != MeterState.Active)) - { - /// Switch to Active mode in order to change TestModeConfig - error = CommErr.CmdActive; - byte[] cmd = new byte[1] { (byte)Command.SetActiveMode }; - if (0 == WriteRequestPort(ihead, MessageID.Command, StructName.Command, 0, 1, cmd)) - { - error = CommErr.None; - } - - /// Delay min. 250 ms - Thread.Sleep(Math.Max(250, cfg.DelayBetweenRetries)); - } - - if (error == CommErr.None && (ihead.ConfigStruct.TestModeConfig != testModeConfig)) - { - /// Change the TestModeConfig if necessary - error = CommErr.Write; - byte[] tstMdCfg = new byte[1] { testModeConfig }; - if (0 == WriteRequestPort(ihead, MessageID.Configuration, StructName.Configuration, 21, 1, tstMdCfg)) - { - ihead.ConfigStruct.Update(21, tstMdCfg); - error = CommErr.None; - } - - /// Delay min. 250 ms - Thread.Sleep(Math.Max(250, cfg.DelayBetweenRetries)); - } - - if (error == CommErr.None) - { - /// Switch to test mode - error = CommErr.CmdTest; - byte[] cmd = new byte[1] { (byte)Command.SetTestMode }; - if (0 == WriteRequestPort(ihead, MessageID.Command, StructName.Command, 0, 1, cmd)) - { - error = CommErr.None; - } - - /// Delay min. 250 ms - Thread.Sleep(Math.Max(250, cfg.DelayBetweenRetries)); - } - + /// Now the meter should be in the Test mode ... verify if (error == CommErr.None) { /// Verify the configuration Thread.Sleep(2000); // RFID: 1000 ms is enough, NFC needs min 2000 ms error = CommErr.Verify; - byte[] config = null; - int retVal = ReadRequestPort(ihead, MessageID.Configuration, StructName.Configuration, 0, ConfigStruct.Length, out config); - if (0 == retVal) + + //TODO BUMI use read config + if (OptoHeadTest.ReadConfiguration(ref ihead, DiagnosticLedState.State4)) { - ihead.ConfigStruct = ConfigStruct.FromByteArray(config); - if ((ihead.ConfigStruct.MeterState == MeterState.Test) && (ihead.ConfigStruct.TestModeConfig == testModeConfig)) + if ((ihead.ConfigStruct.MeterState == ProtocolStatuses.Active) && + (ihead.ConfigStruct.TestModeConfig == testModeConfig)) { error = CommErr.None; resultStr = ihead.ConfigStruct.ToString(1); } } + } return error; @@ -991,33 +927,13 @@ namespace TBF.Rig.TestMethods.iPerlCommunication CommErr error = CommErr.CmdActive; /// Switch to active mode - byte[] cmd = new byte[1] { (byte)Command.SetActiveMode }; - if (0 == WriteRequestPort(ihead, MessageID.Command, StructName.Command, 0, 1, cmd)) + + if (OptoHeadTest.SetActiveMode(ref ihead)) { error = CommErr.None; } -#if VERIFY_ACTIVE_MODE - if (error == CommErr.None) - { - error = CommErr.Verify; - /// Read configuration - byte[] cfg_0_3 = null; - if (ihead.ConfigStruct == null) - { - if (0 == ReadRequestPort(threadId, ihead, MessageID.Configuration, 0, 4, out cfg_0_3)) - { - ihead.ConfigStruct.Update(0, cfg_0_3); - if (ihead.ConfigStruct.MeterState == MeterState.Active) - { - error = CommErr.None; - resultStr = ihead.ConfigStruct.ToString(1); - } - } - } - } -#else if (error == CommErr.None) { if (ihead.ConfigStruct == null) @@ -1025,7 +941,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication else resultStr = ihead.ConfigStruct.ToString(1); } -#endif + return error; } @@ -1037,32 +953,32 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// Water meter object /// String passed to caller /// true on success - static CommErr ReadCalibration(IperlHead ihead, WaterMeter wm, ref string resultStr) - { - if (ihead.CommFailed) return CommErr.CommFailed; - - CommErr error = CommErr.Read; - int readRetVal = 0; - - /// Read calibration - byte[] calib = null; - readRetVal = ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 0, CalibrationStruct.Length, out calib); - if (readRetVal == 0) - { - ihead.CalibrationStruct = CalibrationStruct.FromByteArray(calib); - - if (wm.OrigCalibFactor == 0) - { - wm.OrigCalibFactor = ihead.CalibrationStruct.Calibration; - wm.FWVersion = ihead.CalibrationStruct.FWVersionStr(); - } - - resultStr = ihead.CalibrationStruct.ToString(); - error = ihead.VerifyIPerlType() ? CommErr.None : CommErr.WrongIPerlType; - } - - return error + Math.Max(0, Math.Min(readRetVal, 4)); - } + // static CommErr ReadCalibration(IperlHead ihead, WaterMeter wm, ref string resultStr) + // { + // if (ihead.CommFailed) return CommErr.CommFailed; + // + // CommErr error = CommErr.Read; + // int readRetVal = 0; + // + // /// Read calibration + // byte[] calib = null; + // readRetVal = ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 0, CalibrationStruct.Length, out calib); + // if (readRetVal == 0) + // { + // ihead.CalibrationStruct = CalibrationStruct.FromByteArray(calib); + // + // if (wm.OrigCalibFactor == 0) + // { + // wm.OrigCalibFactor = ihead.CalibrationStruct.Calibration; + // wm.FWVersion = ihead.CalibrationStruct.FWVersionStr(); + // } + // + // resultStr = ihead.CalibrationStruct.ToString(); + // error = ihead.VerifyIPerlType() ? CommErr.None : CommErr.WrongIPerlType; + // } + // + // return error + Math.Max(0, Math.Min(readRetVal, 4)); + // } /// @@ -1071,33 +987,33 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// Water meter object /// String passed to caller /// true on success - static CommErr ReadCalibrationV4(IperlHead ihead, WaterMeter wm, ref string resultStr) - { - if (ihead.CommFailed) return CommErr.CommFailed; - - CommErr error = CommErr.Read; - int readRetVal = 0; - - /// Read calibration - byte[] calib = null; - readRetVal = ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 0, CalibrationStructV4.Length, out calib); - if (readRetVal == 0) - { - ihead.CalibrationStructV4 = CalibrationStructV4.FromByteArray(calib); - - if ((wm.OrigCalibFactor == 0) && (wm.OrigCalibFactorLNA == 0)) - { - wm.OrigCalibFactor = ihead.CalibrationStructV4.Calibration; - wm.OrigCalibFactorLNA = ihead.CalibrationStructV4.CalibrationLNA; - wm.FWVersion = ihead.CalibrationStructV4.FWVersionStr(); - } - - resultStr = ihead.CalibrationStructV4.ToString(); - error = ihead.VerifyIPerlType() ? CommErr.None : CommErr.WrongIPerlType; - } - - return error + Math.Max(0, Math.Min(readRetVal, 4)); - } + // static CommErr ReadCalibrationV4(IperlHead ihead, WaterMeter wm, ref string resultStr) + // { + // if (ihead.CommFailed) return CommErr.CommFailed; + // + // CommErr error = CommErr.Read; + // int readRetVal = 0; + // + // /// Read calibration + // byte[] calib = null; + // readRetVal = ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 0, CalibrationStructV4.Length, out calib); + // if (readRetVal == 0) + // { + // ihead.CalibrationStructV4 = CalibrationStructV4.FromByteArray(calib); + // + // if ((wm.OrigCalibFactor == 0) && (wm.OrigCalibFactorLNA == 0)) + // { + // wm.OrigCalibFactor = ihead.CalibrationStructV4.Calibration; + // wm.OrigCalibFactorLNA = ihead.CalibrationStructV4.CalibrationLNA; + // wm.FWVersion = ihead.CalibrationStructV4.FWVersionStr(); + // } + // + // resultStr = ihead.CalibrationStructV4.ToString(); + // error = ihead.VerifyIPerlType() ? CommErr.None : CommErr.WrongIPerlType; + // } + // + // return error + Math.Max(0, Math.Min(readRetVal, 4)); + // } /// @@ -1109,130 +1025,130 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// Water meter object /// String passed to caller /// true on success - static CommErr WriteCalibrationFactor(int threadId, IperlHead ihead, WaterMeter wm, ref string resultStr) - { - if (ihead.CommFailed || (ihead.CalibrationStruct == null)) return CommErr.CommFailed; - - /// - /// Parse calibration factor (1 argument) or calibration factor limits (2 arguments) - /// - UInt16 newCalibFactor = 0; - if (multiTestParams[currentActivityStep].Activity.Length > WriteCalibrationFactorStr.Length) - { - UInt16 factorLimitLo; - UInt16 factorLimitHi; - UInt16 val; - - string calibFactrorStr = multiTestParams[currentActivityStep].Activity.Substring(WriteCalibrationFactorStr.Length + 1); - string[] arguments = calibFactrorStr.Split(new char[] { ' ' }); - - if (arguments.Length >= 2 && - UInt16.TryParse(arguments[0], out factorLimitLo) && factorLimitLo > 0 && - UInt16.TryParse(arguments[1], out factorLimitHi) && factorLimitHi > 0) - { - /// - /// Lower and upper limits for the calibration factor are specified as iPerlCommunication activity arguments - /// - if (ihead.LastTestResult == null || !ihead.LastTestResult.TestDone) return CommErr.MissingTest; - - newCalibFactor = ihead.CalculateNewCalibFactor(ihead.LastTestResult, ihead.CalibFactor, factorLimitLo, factorLimitHi); - } - else if (arguments.Length == 1 && UInt16.TryParse(arguments[0], out val) && val > 0) - { - /// - /// Calibration factor value is specified as an iPerlCommunication activity argument - /// - newCalibFactor = val; /// Update with specified value - } - else if (arguments.Length == 1 && wm.GetTestData(arguments[0]) != null) - { - /// - /// Adjustment test name is specified as an iPerlCommunication activity argument - /// - Results.Entities.TestData adjustTestData = wm.GetTestData(arguments[0]); - Results.Entities.MeterTestRslt adjustTestRslt; - if (adjustTestData == null) - { - return CommErr.MissingTest; - } - else if (adjustTestData.Repeats == 1) - { - /// Find a test result if Repeats == 1 - adjustTestRslt = wm.GetMeterTestRslt(arguments[0]); - - if (adjustTestRslt == null || !adjustTestRslt.TestDone) return CommErr.MissingTest; - } - else - { - /// Calculate a summarized test result if Repeats > 1 - adjustTestRslt = new Results.Entities.MeterTestRslt(); - for (int i = 1; i <= adjustTestData.Repeats; i++) - { - Results.Entities.MeterTestRslt oneMTR = wm.GetMeterTestRslt(Utils.TestTitle(adjustTestData, i)); - if (oneMTR == null || !oneMTR.TestDone) return CommErr.MissingTest; - - adjustTestRslt.VolumeMeter += oneMTR.VolumeMeter; - adjustTestRslt.VolumeRef += oneMTR.VolumeRef; - } - } - - newCalibFactor = ihead.CalculateNewCalibFactor(adjustTestRslt, ihead.CalibFactor, ihead.FactorLimitLo, ihead.FactorLimitHi); - } - else - { - /// - /// Otherwise the last test is supposed to be an adjustment test - /// - if (ihead.LastTestResult == null || !ihead.LastTestResult.TestDone) return CommErr.MissingTest; - - newCalibFactor = ihead.CalculateNewCalibFactor(ihead.LastTestResult, ihead.CalibFactor, ihead.FactorLimitLo, ihead.FactorLimitHi); - } - } - else - { - /// - /// No iPerlCommunication activity arguments --> The last test is supposed to be an adjustment test - /// - if (ihead.LastTestResult == null || !ihead.LastTestResult.TestDone) return CommErr.MissingTest; - - newCalibFactor = ihead.CalculateNewCalibFactor(ihead.LastTestResult, ihead.CalibFactor, ihead.FactorLimitLo, ihead.FactorLimitHi); - } - - if (newCalibFactor == 0) return CommErr.OutOfRange; - - /// - /// Start communication with iPerl - /// - CommErr error; - byte[] data = new byte[2] { (byte)(newCalibFactor & 0x00FF), (byte)((newCalibFactor >> 8) & 0x00FF) }; - /// - /// Write the new calibration factor (up to cfg.MaxCommRetries tims) - /// - error = CommErr.Write; - if (0 == WriteRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 2, 2, data)) - { - /// - /// Read and verify the calibration factor - /// - error = CommErr.ReadAfterWrite; - byte[] calib_2_3 = null; - if (0 == ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 2, 2, out calib_2_3)) - { - error = CommErr.Verify; - if (calib_2_3 != null && calib_2_3.Length == 2 && data[0] == calib_2_3[0] && data[1] == calib_2_3[1]) - { - error = CommErr.None; - ihead.CalibrationStruct.Update(data, 2); - wm.CalibFactor = newCalibFactor; - resultStr = ihead.CalibrationStruct.ToString(); - } - } - } - - ihead.CalibrationStruct.Update(data, 2); - - return error; - } + // static CommErr WriteCalibrationFactor(int threadId, IperlHead ihead, WaterMeter wm, ref string resultStr) + // { + // if (ihead.CommFailed || (ihead.CalibrationStruct == null)) return CommErr.CommFailed; + // + // /// + // /// Parse calibration factor (1 argument) or calibration factor limits (2 arguments) + // /// + // UInt16 newCalibFactor = 0; + // if (multiTestParams[currentActivityStep].Activity.Length > WriteCalibrationFactorStr.Length) + // { + // UInt16 factorLimitLo; + // UInt16 factorLimitHi; + // UInt16 val; + // + // string calibFactrorStr = multiTestParams[currentActivityStep].Activity.Substring(WriteCalibrationFactorStr.Length + 1); + // string[] arguments = calibFactrorStr.Split(new char[] { ' ' }); + // + // if (arguments.Length >= 2 && + // UInt16.TryParse(arguments[0], out factorLimitLo) && factorLimitLo > 0 && + // UInt16.TryParse(arguments[1], out factorLimitHi) && factorLimitHi > 0) + // { + // /// + // /// Lower and upper limits for the calibration factor are specified as iPerlCommunication activity arguments + // /// + // if (ihead.LastTestResult == null || !ihead.LastTestResult.TestDone) return CommErr.MissingTest; + // + // newCalibFactor = ihead.CalculateNewCalibFactor(ihead.LastTestResult, ihead.CalibFactor, factorLimitLo, factorLimitHi); + // } + // else if (arguments.Length == 1 && UInt16.TryParse(arguments[0], out val) && val > 0) + // { + // /// + // /// Calibration factor value is specified as an iPerlCommunication activity argument + // /// + // newCalibFactor = val; /// Update with specified value + // } + // else if (arguments.Length == 1 && wm.GetTestData(arguments[0]) != null) + // { + // /// + // /// Adjustment test name is specified as an iPerlCommunication activity argument + // /// + // Results.Entities.TestData adjustTestData = wm.GetTestData(arguments[0]); + // Results.Entities.MeterTestRslt adjustTestRslt; + // if (adjustTestData == null) + // { + // return CommErr.MissingTest; + // } + // else if (adjustTestData.Repeats == 1) + // { + // /// Find a test result if Repeats == 1 + // adjustTestRslt = wm.GetMeterTestRslt(arguments[0]); + // + // if (adjustTestRslt == null || !adjustTestRslt.TestDone) return CommErr.MissingTest; + // } + // else + // { + // /// Calculate a summarized test result if Repeats > 1 + // adjustTestRslt = new Results.Entities.MeterTestRslt(); + // for (int i = 1; i <= adjustTestData.Repeats; i++) + // { + // Results.Entities.MeterTestRslt oneMTR = wm.GetMeterTestRslt(Utils.TestTitle(adjustTestData, i)); + // if (oneMTR == null || !oneMTR.TestDone) return CommErr.MissingTest; + // + // adjustTestRslt.VolumeMeter += oneMTR.VolumeMeter; + // adjustTestRslt.VolumeRef += oneMTR.VolumeRef; + // } + // } + // + // newCalibFactor = ihead.CalculateNewCalibFactor(adjustTestRslt, ihead.CalibFactor, ihead.FactorLimitLo, ihead.FactorLimitHi); + // } + // else + // { + // /// + // /// Otherwise the last test is supposed to be an adjustment test + // /// + // if (ihead.LastTestResult == null || !ihead.LastTestResult.TestDone) return CommErr.MissingTest; + // + // newCalibFactor = ihead.CalculateNewCalibFactor(ihead.LastTestResult, ihead.CalibFactor, ihead.FactorLimitLo, ihead.FactorLimitHi); + // } + // } + // else + // { + // /// + // /// No iPerlCommunication activity arguments --> The last test is supposed to be an adjustment test + // /// + // if (ihead.LastTestResult == null || !ihead.LastTestResult.TestDone) return CommErr.MissingTest; + // + // newCalibFactor = ihead.CalculateNewCalibFactor(ihead.LastTestResult, ihead.CalibFactor, ihead.FactorLimitLo, ihead.FactorLimitHi); + // } + // + // if (newCalibFactor == 0) return CommErr.OutOfRange; + // + // /// + // /// Start communication with iPerl + // /// + // CommErr error; + // byte[] data = new byte[2] { (byte)(newCalibFactor & 0x00FF), (byte)((newCalibFactor >> 8) & 0x00FF) }; + // /// + // /// Write the new calibration factor (up to cfg.MaxCommRetries tims) + // /// + // error = CommErr.Write; + // if (0 == WriteRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 2, 2, data)) + // { + // /// + // /// Read and verify the calibration factor + // /// + // error = CommErr.ReadAfterWrite; + // byte[] calib_2_3 = null; + // if (0 == ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 2, 2, out calib_2_3)) + // { + // error = CommErr.Verify; + // if (calib_2_3 != null && calib_2_3.Length == 2 && data[0] == calib_2_3[0] && data[1] == calib_2_3[1]) + // { + // error = CommErr.None; + // ihead.CalibrationStruct.Update(data, 2); + // wm.CalibFactor = newCalibFactor; + // resultStr = ihead.CalibrationStruct.ToString(); + // } + // } + // } + // + // ihead.CalibrationStruct.Update(data, 2); + // + // return error; + // } /// @@ -1244,159 +1160,159 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// Water meter object /// String passed to caller /// true on success - static CommErr WriteCalibrationV4Factors(int threadId, IperlHead ihead, WaterMeter wm, ref string resultStr) - { - if (ihead.CommFailed || (ihead.CalibrationStructV4 == null)) return CommErr.CommFailed; - - /// - /// Parse calibration factor (1 argument) or calibration factor limits (2 arguments) - /// - UInt16 newCalibFactor = 0; - UInt16 newCalibFactorLNA = 0; - if (multiTestParams[currentActivityStep].Activity.Length > WriteCalibrationV4FactorsStr.Length) - { - UInt16 factorLimitLo = 0; - UInt16 factorLimitHi = 0; - UInt16 lnaFactorLimitLo = 0; - UInt16 lnaFactorLimitHi = 0; - Results.Entities.TestData adjustTestData = null; - Results.Entities.TestData lnaAdjustTestData = null; - Results.Entities.MeterTestRslt adjustTestRslt = null; - Results.Entities.MeterTestRslt lnaAdjustTestRslt = null; - - string calibFactrorStr = multiTestParams[currentActivityStep].Activity.Substring(WriteCalibrationV4FactorsStr.Length + 1); - string[] arguments = calibFactrorStr.Split(new char[] { ' ' }); - - if (arguments.Length == 6) - { - if (!wm.TryGetTestData(arguments[0], out adjustTestData) || - !UInt16.TryParse(arguments[1], out factorLimitLo) || factorLimitLo <= 0 && - !UInt16.TryParse(arguments[2], out factorLimitHi) || factorLimitHi <= 0 && - !wm.TryGetTestData(arguments[3], out lnaAdjustTestData) || - !UInt16.TryParse(arguments[4], out lnaFactorLimitLo) || lnaFactorLimitLo <= 0 && - !UInt16.TryParse(arguments[5], out lnaFactorLimitHi) || lnaFactorLimitHi <= 0) - { - return CommErr.WrongArguments; - } - else - { - adjustTestRslt = GetAverageTestRslt(wm, adjustTestData); - lnaAdjustTestRslt = GetAverageTestRslt(wm, lnaAdjustTestData); - - if ((adjustTestRslt == null) || (lnaAdjustTestRslt == null)) - { - return CommErr.MissingTest; - } - - newCalibFactor = ihead.CalculateNewCalibFactor(adjustTestRslt, ihead.CalibFactor, factorLimitLo, factorLimitHi); - newCalibFactorLNA = ihead.CalculateNewCalibFactor(lnaAdjustTestRslt, ihead.CalibFactorLNA, lnaFactorLimitLo, lnaFactorLimitHi); - } - } - else if (arguments.Length == 4) - { - if (!wm.TryGetTestData(arguments[0], out adjustTestData) || - !wm.TryGetTestData(arguments[1], out lnaAdjustTestData) || - !UInt16.TryParse(arguments[2], out lnaFactorLimitLo) || lnaFactorLimitLo <= 0 && - !UInt16.TryParse(arguments[3], out lnaFactorLimitHi) || lnaFactorLimitHi <= 0) - { - return CommErr.WrongArguments; - } - else - { - factorLimitLo = ihead.FactorLimitLo; - factorLimitHi = ihead.FactorLimitHi; - - adjustTestRslt = GetAverageTestRslt(wm, adjustTestData); - lnaAdjustTestRslt = GetAverageTestRslt(wm, lnaAdjustTestData); - - if ((adjustTestRslt == null) || (lnaAdjustTestRslt == null)) - { - return CommErr.MissingTest; - } - - newCalibFactor = ihead.CalculateNewCalibFactor(adjustTestRslt, ihead.CalibFactor, factorLimitLo, factorLimitHi); - newCalibFactorLNA = ihead.CalculateNewCalibFactor(lnaAdjustTestRslt, ihead.CalibFactorLNA, lnaFactorLimitLo, lnaFactorLimitHi); - } - } - else if (arguments.Length == 2) - { - if (!wm.TryGetTestData(arguments[0], out adjustTestData) || - !wm.TryGetTestData(arguments[1], out lnaAdjustTestData)) - { - return CommErr.WrongArguments; - } - else - { - factorLimitLo = ihead.FactorLimitLo; - factorLimitHi = ihead.FactorLimitHi; - lnaFactorLimitLo = ihead.FactorLimitLo; - lnaFactorLimitHi = ihead.FactorLimitHi; - - adjustTestRslt = GetAverageTestRslt(wm, adjustTestData); - lnaAdjustTestRslt = GetAverageTestRslt(wm, lnaAdjustTestData); - - if ((adjustTestRslt == null) || (lnaAdjustTestRslt == null)) - { - return CommErr.MissingTest; - } - - newCalibFactor = ihead.CalculateNewCalibFactor(adjustTestRslt, ihead.CalibFactor, factorLimitLo, factorLimitHi); - newCalibFactorLNA = ihead.CalculateNewCalibFactor(lnaAdjustTestRslt, ihead.CalibFactorLNA, lnaFactorLimitLo, lnaFactorLimitHi); - } - } - else - { - return CommErr.WrongArguments; - } - } - else - { - return CommErr.WrongArguments; - } - - if (newCalibFactor == 0 || newCalibFactorLNA == 0) return CommErr.OutOfRange; - - /// - /// Start communication with iPerl - /// - CommErr error; - byte[] data = new byte[2] { (byte)(newCalibFactor & 0x00FF), (byte)((newCalibFactor >> 8) & 0x00FF) }; - byte[] dataLNA = new byte[2] { (byte)(newCalibFactorLNA & 0x00FF), (byte)((newCalibFactorLNA >> 8) & 0x00FF) }; - /// - /// Write the new calibration factor (up to cfg.MaxCommRetries tims) - /// - error = CommErr.Write; - if (0 == WriteRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 2, 2, data) && - 0 == WriteRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 34, 2, dataLNA)) - { - /// - /// Read and verify the calibration factor - /// - error = CommErr.ReadAfterWrite; - byte[] calib_2_3 = null; - byte[] calib_34_35 = null; - if (0 == ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 2, 2, out calib_2_3) && - 0 == ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 34, 2, out calib_34_35)) - { - error = CommErr.Verify; - if (calib_2_3 != null && calib_2_3.Length == 2 && data[0] == calib_2_3[0] && data[1] == calib_2_3[1] && - calib_34_35 != null && calib_34_35.Length == 2 && dataLNA[0] == calib_34_35[0] && dataLNA[1] == calib_34_35[1]) - { - error = CommErr.None; - ihead.CalibrationStructV4.Update(data, 2); - ihead.CalibrationStructV4.Update(dataLNA, 34); - wm.CalibFactor = newCalibFactor; - wm.CalibFactorLNA = newCalibFactorLNA; - resultStr = ihead.CalibrationStructV4.ToString(); - } - } - } - - ihead.CalibrationStructV4.Update(data, 2); - ihead.CalibrationStructV4.Update(dataLNA, 34); - - return error; - } + // static CommErr WriteCalibrationV4Factors(int threadId, IperlHead ihead, WaterMeter wm, ref string resultStr) + // { + // if (ihead.CommFailed || (ihead.CalibrationStructV4 == null)) return CommErr.CommFailed; + // + // /// + // /// Parse calibration factor (1 argument) or calibration factor limits (2 arguments) + // /// + // UInt16 newCalibFactor = 0; + // UInt16 newCalibFactorLNA = 0; + // if (multiTestParams[currentActivityStep].Activity.Length > WriteCalibrationV4FactorsStr.Length) + // { + // UInt16 factorLimitLo = 0; + // UInt16 factorLimitHi = 0; + // UInt16 lnaFactorLimitLo = 0; + // UInt16 lnaFactorLimitHi = 0; + // Results.Entities.TestData adjustTestData = null; + // Results.Entities.TestData lnaAdjustTestData = null; + // Results.Entities.MeterTestRslt adjustTestRslt = null; + // Results.Entities.MeterTestRslt lnaAdjustTestRslt = null; + // + // string calibFactrorStr = multiTestParams[currentActivityStep].Activity.Substring(WriteCalibrationV4FactorsStr.Length + 1); + // string[] arguments = calibFactrorStr.Split(new char[] { ' ' }); + // + // if (arguments.Length == 6) + // { + // if (!wm.TryGetTestData(arguments[0], out adjustTestData) || + // !UInt16.TryParse(arguments[1], out factorLimitLo) || factorLimitLo <= 0 && + // !UInt16.TryParse(arguments[2], out factorLimitHi) || factorLimitHi <= 0 && + // !wm.TryGetTestData(arguments[3], out lnaAdjustTestData) || + // !UInt16.TryParse(arguments[4], out lnaFactorLimitLo) || lnaFactorLimitLo <= 0 && + // !UInt16.TryParse(arguments[5], out lnaFactorLimitHi) || lnaFactorLimitHi <= 0) + // { + // return CommErr.WrongArguments; + // } + // else + // { + // adjustTestRslt = GetAverageTestRslt(wm, adjustTestData); + // lnaAdjustTestRslt = GetAverageTestRslt(wm, lnaAdjustTestData); + // + // if ((adjustTestRslt == null) || (lnaAdjustTestRslt == null)) + // { + // return CommErr.MissingTest; + // } + // + // newCalibFactor = ihead.CalculateNewCalibFactor(adjustTestRslt, ihead.CalibFactor, factorLimitLo, factorLimitHi); + // newCalibFactorLNA = ihead.CalculateNewCalibFactor(lnaAdjustTestRslt, ihead.CalibFactorLNA, lnaFactorLimitLo, lnaFactorLimitHi); + // } + // } + // else if (arguments.Length == 4) + // { + // if (!wm.TryGetTestData(arguments[0], out adjustTestData) || + // !wm.TryGetTestData(arguments[1], out lnaAdjustTestData) || + // !UInt16.TryParse(arguments[2], out lnaFactorLimitLo) || lnaFactorLimitLo <= 0 && + // !UInt16.TryParse(arguments[3], out lnaFactorLimitHi) || lnaFactorLimitHi <= 0) + // { + // return CommErr.WrongArguments; + // } + // else + // { + // factorLimitLo = ihead.FactorLimitLo; + // factorLimitHi = ihead.FactorLimitHi; + // + // adjustTestRslt = GetAverageTestRslt(wm, adjustTestData); + // lnaAdjustTestRslt = GetAverageTestRslt(wm, lnaAdjustTestData); + // + // if ((adjustTestRslt == null) || (lnaAdjustTestRslt == null)) + // { + // return CommErr.MissingTest; + // } + // + // newCalibFactor = ihead.CalculateNewCalibFactor(adjustTestRslt, ihead.CalibFactor, factorLimitLo, factorLimitHi); + // newCalibFactorLNA = ihead.CalculateNewCalibFactor(lnaAdjustTestRslt, ihead.CalibFactorLNA, lnaFactorLimitLo, lnaFactorLimitHi); + // } + // } + // else if (arguments.Length == 2) + // { + // if (!wm.TryGetTestData(arguments[0], out adjustTestData) || + // !wm.TryGetTestData(arguments[1], out lnaAdjustTestData)) + // { + // return CommErr.WrongArguments; + // } + // else + // { + // factorLimitLo = ihead.FactorLimitLo; + // factorLimitHi = ihead.FactorLimitHi; + // lnaFactorLimitLo = ihead.FactorLimitLo; + // lnaFactorLimitHi = ihead.FactorLimitHi; + // + // adjustTestRslt = GetAverageTestRslt(wm, adjustTestData); + // lnaAdjustTestRslt = GetAverageTestRslt(wm, lnaAdjustTestData); + // + // if ((adjustTestRslt == null) || (lnaAdjustTestRslt == null)) + // { + // return CommErr.MissingTest; + // } + // + // newCalibFactor = ihead.CalculateNewCalibFactor(adjustTestRslt, ihead.CalibFactor, factorLimitLo, factorLimitHi); + // newCalibFactorLNA = ihead.CalculateNewCalibFactor(lnaAdjustTestRslt, ihead.CalibFactorLNA, lnaFactorLimitLo, lnaFactorLimitHi); + // } + // } + // else + // { + // return CommErr.WrongArguments; + // } + // } + // else + // { + // return CommErr.WrongArguments; + // } + // + // if (newCalibFactor == 0 || newCalibFactorLNA == 0) return CommErr.OutOfRange; + // + // /// + // /// Start communication with iPerl + // /// + // CommErr error; + // byte[] data = new byte[2] { (byte)(newCalibFactor & 0x00FF), (byte)((newCalibFactor >> 8) & 0x00FF) }; + // byte[] dataLNA = new byte[2] { (byte)(newCalibFactorLNA & 0x00FF), (byte)((newCalibFactorLNA >> 8) & 0x00FF) }; + // /// + // /// Write the new calibration factor (up to cfg.MaxCommRetries tims) + // /// + // error = CommErr.Write; + // if (0 == WriteRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 2, 2, data) && + // 0 == WriteRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 34, 2, dataLNA)) + // { + // /// + // /// Read and verify the calibration factor + // /// + // error = CommErr.ReadAfterWrite; + // byte[] calib_2_3 = null; + // byte[] calib_34_35 = null; + // if (0 == ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 2, 2, out calib_2_3) && + // 0 == ReadRequestPort(ihead, MessageID.Calibration, StructName.Calibration, 34, 2, out calib_34_35)) + // { + // error = CommErr.Verify; + // if (calib_2_3 != null && calib_2_3.Length == 2 && data[0] == calib_2_3[0] && data[1] == calib_2_3[1] && + // calib_34_35 != null && calib_34_35.Length == 2 && dataLNA[0] == calib_34_35[0] && dataLNA[1] == calib_34_35[1]) + // { + // error = CommErr.None; + // ihead.CalibrationStructV4.Update(data, 2); + // ihead.CalibrationStructV4.Update(dataLNA, 34); + // wm.CalibFactor = newCalibFactor; + // wm.CalibFactorLNA = newCalibFactorLNA; + // resultStr = ihead.CalibrationStructV4.ToString(); + // } + // } + // } + // + // ihead.CalibrationStructV4.Update(data, 2); + // ihead.CalibrationStructV4.Update(dataLNA, 34); + // + // return error; + // } /// @@ -2263,80 +2179,80 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// Arrow direction /// String passed to caller /// true on success - static CommErr DewaRework(IperlHead ihead, WaterMeter wm, FlowDir flowDir, ref string resultStr) - { - if (ihead.CommFailed) return CommErr.CommFailed; - - byte arrow = (flowDir == FlowDir.L_R) ? (byte)1 : (byte)2; /// L-R is reverse flow (=1), R-L is forward flow (=2)(default) - - List dataToBeWritten = new List - { - new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 33:0x19A1, new byte[] { (byte)0xA5 }, "Open Sealing"), // ????? - new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 5:0x1985, new byte[] { arrow }, "Arrow"), - new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 28:0x199C, new byte[5], "Clear S/N"), - new iPerlDataWrite(MessageID.Configuration, StructName.Configuration, 0x0015, new byte[] { (byte)0xA0 }, "Test mode config = A0"), - new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 14:0x198E, new byte[] { (byte)(2510 & 0xFF), (byte)((2510 >> 8) & 0xFF) }, "Receipt mean current") - }; - - // check meter status: 1-Idle, 2-Active, 3-Test, 4-End Of Life - if (0 == ReadRequestPort(ihead, MessageID.Configuration, StructName.Configuration, 1, 1, out byte[] rdData)) - { - int eMeterState = (int)((SByte)rdData[0]); - switch (eMeterState) - { - case 1: // Idle -> Test -> Active - dataToBeWritten.Add(new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetTestMode }, "Set test mode")); - dataToBeWritten.Add(new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetActiveMode }, "Set active mode")); - break; - case 3: // Test Mode -> Active - dataToBeWritten.Add(new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetActiveMode }, "Set active mode")); - break; - } - } - - dataToBeWritten.Add(new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, new byte[] { (byte)1 }, "System Status")); - dataToBeWritten.Add(new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioParams, 0x1898, new byte[] { (byte)3 }, "WakeUpInterval")); - dataToBeWritten.Add(new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioParams, 0x18A2, new byte[] { (byte)0x4A, (byte)0x53, (byte)0x3B, (byte)0x8F, - (byte)0x70, (byte)0x31, (byte)0xC2, (byte)0x5D, - (byte)0x6F, (byte)0x2D, (byte)0xE8, (byte)0x07, - (byte)0x6E, (byte)0x0F, (byte)0x97, (byte)0xC3, }, "AES Key Crypted")); - - int successfyllyWrittenFlags = 0; /// Ones in this word represent communication failures, LSB represents the first step - int mask = 1; - foreach (var wData in dataToBeWritten) - { - bool isSuccessfullyWritten = false; - if (0 == WriteRequestPort(ihead, wData.MessageID, wData.StructName, wData.Offset, wData.Data.Length, wData.Data)) - { - isSuccessfullyWritten = true; - } - - if (!isSuccessfullyWritten) - { - /// Communication failed in this step - successfyllyWrittenFlags = (successfyllyWrittenFlags | mask); - } - - mask = (mask << 1); /// Adjust the mask for the next step - } - - if (successfyllyWrittenFlags == 0) - { - /// Success - if (ihead.ConfigStruct != null) - { - ihead.ConfigStruct.MeterState = MeterState.Active; - ihead.ConfigStruct.TestModeConfig = (byte)0xA0; - } - - resultStr = "OK"; - return CommErr.None; - } - else - { - return CommErr.Write; - } - } + // static CommErr DewaRework(IperlHead ihead, WaterMeter wm, FlowDir flowDir, ref string resultStr) + // { + // if (ihead.CommFailed) return CommErr.CommFailed; + // + // byte arrow = (flowDir == FlowDir.L_R) ? (byte)1 : (byte)2; /// L-R is reverse flow (=1), R-L is forward flow (=2)(default) + // + // List dataToBeWritten = new List + // { + // new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 33:0x19A1, new byte[] { (byte)0xA5 }, "Open Sealing"), // ????? + // new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 5:0x1985, new byte[] { arrow }, "Arrow"), + // new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 28:0x199C, new byte[5], "Clear S/N"), + // new iPerlDataWrite(MessageID.Configuration, StructName.Configuration, 0x0015, new byte[] { (byte)0xA0 }, "Test mode config = A0"), + // new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 14:0x198E, new byte[] { (byte)(2510 & 0xFF), (byte)((2510 >> 8) & 0xFF) }, "Receipt mean current") + // }; + // + // // check meter status: 1-Idle, 2-Active, 3-Test, 4-End Of Life + // if (0 == ReadRequestPort(ihead, MessageID.Configuration, StructName.Configuration, 1, 1, out byte[] rdData)) + // { + // int eMeterState = (int)((SByte)rdData[0]); + // switch (eMeterState) + // { + // case 1: // Idle -> Test -> Active + // dataToBeWritten.Add(new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetTestMode }, "Set test mode")); + // dataToBeWritten.Add(new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetActiveMode }, "Set active mode")); + // break; + // case 3: // Test Mode -> Active + // dataToBeWritten.Add(new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetActiveMode }, "Set active mode")); + // break; + // } + // } + // + // dataToBeWritten.Add(new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, new byte[] { (byte)1 }, "System Status")); + // dataToBeWritten.Add(new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioParams, 0x1898, new byte[] { (byte)3 }, "WakeUpInterval")); + // dataToBeWritten.Add(new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioParams, 0x18A2, new byte[] { (byte)0x4A, (byte)0x53, (byte)0x3B, (byte)0x8F, + // (byte)0x70, (byte)0x31, (byte)0xC2, (byte)0x5D, + // (byte)0x6F, (byte)0x2D, (byte)0xE8, (byte)0x07, + // (byte)0x6E, (byte)0x0F, (byte)0x97, (byte)0xC3, }, "AES Key Crypted")); + // + // int successfyllyWrittenFlags = 0; /// Ones in this word represent communication failures, LSB represents the first step + // int mask = 1; + // foreach (var wData in dataToBeWritten) + // { + // bool isSuccessfullyWritten = false; + // if (0 == WriteRequestPort(ihead, wData.MessageID, wData.StructName, wData.Offset, wData.Data.Length, wData.Data)) + // { + // isSuccessfullyWritten = true; + // } + // + // if (!isSuccessfullyWritten) + // { + // /// Communication failed in this step + // successfyllyWrittenFlags = (successfyllyWrittenFlags | mask); + // } + // + // mask = (mask << 1); /// Adjust the mask for the next step + // } + // + // if (successfyllyWrittenFlags == 0) + // { + // /// Success + // if (ihead.ConfigStruct != null) + // { + // ihead.ConfigStruct.StatusMode = ProtocolStatuses.Active; + // ihead.ConfigStruct.OpthoStatusMode = DiagnosticLedState.State4; + // } + // + // resultStr = "OK"; + // return CommErr.None; + // } + // else + // { + // return CommErr.Write; + // } + // } /// /// Start testing a sealed meter @@ -2345,68 +2261,68 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// Water meter object /// String passed to caller /// true on success - static CommErr StartTestingSealedMeter(IperlHead ihead, WaterMeter wm, ref string resultStr) - { - if (ihead.CommFailed) return CommErr.CommFailed; - - Byte testModeConfig = 0xA0; /// Default value - /// - if (multiTestParams[currentActivityStep].Activity.Length > StartTestingSealedMetersStr.Length) - { - string testModeConfigStr = multiTestParams[currentActivityStep].Activity.Substring(StartTestingSealedMetersStr.Length + 1); - UInt16 byteVal; - if (UInt16.TryParse(testModeConfigStr, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out byteVal) && byteVal <= 255) - { - testModeConfig = (Byte)byteVal; /// Update with specified value - } - } - - iPerlDataWrite[] dataToBeWritten = new iPerlDataWrite[] - { - new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 33:0x19A1, new byte[] { (byte)0xA5 }, "Open Sealing"), /// 0x5A=sealed, 0xA5=unsealed ?????? - new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, new byte[] { (byte)1 }, "System Status"), - new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetActiveMode }, "Set active mode"), - new iPerlDataWrite(MessageID.Configuration, StructName.Configuration, 0x0015, new byte[] { testModeConfig }, string.Format("Test mode config = {0:X2}", testModeConfig)), - }; - - if (ihead.ConfigStruct != null) ihead.OrigTestModeConfig = ihead.ConfigStruct.TestModeConfig; - - int successfyllyWrittenFlags = 0; /// Ones in this word represent communication failures, LSB represents the first step - int mask = 1; - foreach (var wData in dataToBeWritten) - { - bool isSuccessfullyWritten = false; - if (0 == WriteRequestPort(ihead, wData.MessageID, wData.StructName, wData.Offset, wData.Data.Length, wData.Data)) - { - isSuccessfullyWritten = true; - } - - if (!isSuccessfullyWritten) - { - /// Communication failed in this step - successfyllyWrittenFlags = (successfyllyWrittenFlags | mask); - } - - mask = (mask << 1); /// Adjust the mask for the next step - } - - if (successfyllyWrittenFlags == 0) - { - /// Success - if (ihead.ConfigStruct != null) - { - ihead.ConfigStruct.MeterState = MeterState.Active; - ihead.ConfigStruct.TestModeConfig = (byte)0xA0; - } - - resultStr = "OK"; - return CommErr.None; - } - else - { - return CommErr.Write; - } - } + // static CommErr StartTestingSealedMeter(IperlHead ihead, WaterMeter wm, ref string resultStr) + // { + // if (ihead.CommFailed) return CommErr.CommFailed; + // + // Byte testModeConfig = 0xA0; /// Default value + // /// + // if (multiTestParams[currentActivityStep].Activity.Length > StartTestingSealedMetersStr.Length) + // { + // string testModeConfigStr = multiTestParams[currentActivityStep].Activity.Substring(StartTestingSealedMetersStr.Length + 1); + // UInt16 byteVal; + // if (UInt16.TryParse(testModeConfigStr, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out byteVal) && byteVal <= 255) + // { + // testModeConfig = (Byte)byteVal; /// Update with specified value + // } + // } + // + // iPerlDataWrite[] dataToBeWritten = new iPerlDataWrite[] + // { + // new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 33:0x19A1, new byte[] { (byte)0xA5 }, "Open Sealing"), /// 0x5A=sealed, 0xA5=unsealed ?????? + // new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, new byte[] { (byte)1 }, "System Status"), + // new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetActiveMode }, "Set active mode"), + // new iPerlDataWrite(MessageID.Configuration, StructName.Configuration, 0x0015, new byte[] { testModeConfig }, string.Format("Test mode config = {0:X2}", testModeConfig)), + // }; + // + // if (ihead.ConfigStruct != null) ihead.OrigTestModeConfig = ihead.ConfigStruct.TestModeConfig; + // + // int successfyllyWrittenFlags = 0; /// Ones in this word represent communication failures, LSB represents the first step + // int mask = 1; + // foreach (var wData in dataToBeWritten) + // { + // bool isSuccessfullyWritten = false; + // if (0 == WriteRequestPort(ihead, wData.MessageID, wData.StructName, wData.Offset, wData.Data.Length, wData.Data)) + // { + // isSuccessfullyWritten = true; + // } + // + // if (!isSuccessfullyWritten) + // { + // /// Communication failed in this step + // successfyllyWrittenFlags = (successfyllyWrittenFlags | mask); + // } + // + // mask = (mask << 1); /// Adjust the mask for the next step + // } + // + // if (successfyllyWrittenFlags == 0) + // { + // /// Success + // if (ihead.ConfigStruct != null) + // { + // ihead.ConfigStruct.MeterState = MeterState.Active; + // ihead.ConfigStruct.TestModeConfig = (byte)0xA0; + // } + // + // resultStr = "OK"; + // return CommErr.None; + // } + // else + // { + // return CommErr.Write; + // } + // } /// /// End testing a sealed meter @@ -2415,70 +2331,70 @@ namespace TBF.Rig.TestMethods.iPerlCommunication /// Water meter object /// String passed to caller /// true on success - static CommErr EndTestingSealedMeter(IperlHead ihead, WaterMeter wm, ref string resultStr) - { - if (ihead.CommFailed) return CommErr.CommFailed; + // static CommErr EndTestingSealedMeter(IperlHead ihead, WaterMeter wm, ref string resultStr) + // { + // if (ihead.CommFailed) return CommErr.CommFailed; + // + // Byte testModeConfig = (ihead.OrigTestModeConfig != 0) ? ihead.OrigTestModeConfig : (byte)0x80; /// Restore original value (default is 0x80) + // + // iPerlDataWrite[] dataToBeWritten = new iPerlDataWrite[] + // { + // new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetActiveMode }, "Set active mode"), + // new iPerlDataWrite(MessageID.Configuration, StructName.Configuration, 0x0015, new byte[] { testModeConfig }, string.Format("Test mode config = {0:X2}", testModeConfig)), + // new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, new byte[] { (byte)0 }, "System Status"), + // new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 33:0x19A1, new byte[] { (byte)0x5A }, "Close Sealing") /// 0x5A=sealed, 0xA5=unsealed ?????? + // }; + // + // int successfyllyWrittenFlags = 0; /// Ones in this word represent communication failures, LSB represents the first step + // int mask = 1; + // foreach (var wData in dataToBeWritten) + // { + // bool isSuccessfullyWritten = false; + // if (0 == WriteRequestPort(ihead, wData.MessageID, wData.StructName, wData.Offset, wData.Data.Length, wData.Data)) + // { + // isSuccessfullyWritten = true; + // } + // + // if (!isSuccessfullyWritten) + // { + // /// Communication failed in this step + // successfyllyWrittenFlags = (successfyllyWrittenFlags | mask); + // } + // + // mask = (mask << 1); /// Adjust the mask for the next step + // } + // + // if (successfyllyWrittenFlags == 0) + // { + // /// Success + // if (ihead.ConfigStruct != null) + // { + // ihead.ConfigStruct.MeterState = MeterState.Active; + // ihead.ConfigStruct.TestModeConfig = (byte)0xA0; + // } + // + // resultStr = "OK"; + // return CommErr.None; + // } + // else + // { + // return CommErr.Write; + // } + // } - Byte testModeConfig = (ihead.OrigTestModeConfig != 0) ? ihead.OrigTestModeConfig : (byte)0x80; /// Restore original value (default is 0x80) - - iPerlDataWrite[] dataToBeWritten = new iPerlDataWrite[] - { - new iPerlDataWrite(MessageID.Command, StructName.Command, 0x0000, new byte[] { (byte)Command.SetActiveMode }, "Set active mode"), - new iPerlDataWrite(MessageID.Configuration, StructName.Configuration, 0x0015, new byte[] { testModeConfig }, string.Format("Test mode config = {0:X2}", testModeConfig)), - new iPerlDataWrite(MessageID.RadioPassthrough, StructName.RadioInfo, 0x1804, new byte[] { (byte)0 }, "System Status"), - new iPerlDataWrite(MessageID.MetrologyMemory, StructName.Calibration, ihead.CommInterface == CommunicationInterface.NFC? 33:0x19A1, new byte[] { (byte)0x5A }, "Close Sealing") /// 0x5A=sealed, 0xA5=unsealed ?????? - }; - - int successfyllyWrittenFlags = 0; /// Ones in this word represent communication failures, LSB represents the first step - int mask = 1; - foreach (var wData in dataToBeWritten) - { - bool isSuccessfullyWritten = false; - if (0 == WriteRequestPort(ihead, wData.MessageID, wData.StructName, wData.Offset, wData.Data.Length, wData.Data)) - { - isSuccessfullyWritten = true; - } - - if (!isSuccessfullyWritten) - { - /// Communication failed in this step - successfyllyWrittenFlags = (successfyllyWrittenFlags | mask); - } - - mask = (mask << 1); /// Adjust the mask for the next step - } - - if (successfyllyWrittenFlags == 0) - { - /// Success - if (ihead.ConfigStruct != null) - { - ihead.ConfigStruct.MeterState = MeterState.Active; - ihead.ConfigStruct.TestModeConfig = (byte)0xA0; - } - - resultStr = "OK"; - return CommErr.None; - } - else - { - return CommErr.Write; - } - } - - static CommErr GetQ2PreCorrectionsFormRest(int threadId, IperlHead ihead, WaterMeter wm, ref string resultStr) - { - if (!ProcessData.IsQ2PreCorrectionCalculated) - { - ProcessData.IsQ2PreCorrectionCalculated = true; - /*bool success = iPerlCommunicationSeq.GetQ2PreCorrectionsOrBackups(cfg, wm.WMTypeId(), - out ProcessData.CalculatedQ2PreCorrectionLR, - out ProcessData.CalculatedQ2PreCorrectionRL);*/ - } - - resultStr = string.Format("Q2 pre-corrections: LR={0} RL={1}", ProcessData.CalculatedQ2PreCorrectionLR, ProcessData.CalculatedQ2PreCorrectionRL); - return CommErr.None; - } + // static CommErr GetQ2PreCorrectionsFormRest(int threadId, IperlHead ihead, WaterMeter wm, ref string resultStr) + // { + // if (!ProcessData.IsQ2PreCorrectionCalculated) + // { + // ProcessData.IsQ2PreCorrectionCalculated = true; + // /*bool success = iPerlCommunicationSeq.GetQ2PreCorrectionsOrBackups(cfg, wm.WMTypeId(), + // out ProcessData.CalculatedQ2PreCorrectionLR, + // out ProcessData.CalculatedQ2PreCorrectionRL);*/ + // } + // + // resultStr = string.Format("Q2 pre-corrections: LR={0} RL={1}", ProcessData.CalculatedQ2PreCorrectionLR, ProcessData.CalculatedQ2PreCorrectionRL); + // return CommErr.None; + // } static CommErr SetIperlCommMilestoneReached(TestMethod testMethod, ConditionID id, ref string resultStr) { @@ -2731,34 +2647,35 @@ namespace TBF.Rig.TestMethods.iPerlCommunication private async Task ProcessTask(IperlHead iHead, object tag) { string txt = ""; + bool success = false; switch (tag) { case "ReadPCB": - txt = OpticalHeadTest.ReadRequest_PCB(iHead); + txt = OptoHeadTest.ReadRequest_PCB(ref iHead); break; case "WriteRequestPort_u8_Customer_Text": - txt = OpticalHeadTest.WriteRequestPort_u8_Customer_Text(iHead); + txt = "Not Supported NOW!";//OpticalHeadTest.WriteRequestPort_u8_Customer_Text(iHead); break; case "OpenSealing": - txt = OpticalHeadTest.OpenSealing(iHead); + txt = "Not Supported NOW!";//OpticalHeadTest.OpenSealing(iHead); break; case "StartTestMode": - txt = OpticalHeadTest.SetTestMode(iHead); + txt = OptoHeadTest.SetTestMode(ref iHead, ref success); break; case "TurnOffTestMode": - txt = OpticalHeadTest.SetActiveMode(iHead); + txt = OptoHeadTest.SetActiveMode(ref iHead, ref success); break; case "TurnOffRadio": - txt = OpticalHeadTest.TurnOffRadio(iHead); + txt = "Not Supported NOW!";//OpticalHeadTest.TurnOffRadio(iHead); break; case "SetProductionMode": - txt = OpticalHeadTest.SetProductionMode(iHead); + txt = "Not Supported NOW!";//OpticalHeadTest.SetProductionMode(iHead); break; case "SetRFID": - txt = OpticalHeadTest.SetRfidMode(iHead); + txt = "Not Supported NOW!";//OpticalHeadTest.SetRfidMode(iHead); break; case "SetNFC": - txt = OpticalHeadTest.SetNfcMode(iHead); + txt = "Not Supported NOW!";//OpticalHeadTest.SetNfcMode(iHead); break; } return txt; diff --git a/TBF/Rig/TestMethods/iPerlCommunication/iPerlCommunicationParams.cs b/TBF/Rig/TestMethods/iPerlCommunication/iPerlCommunicationParams.cs index ddf2df0f1..98a29fe4f 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/iPerlCommunicationParams.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/iPerlCommunicationParams.cs @@ -24,7 +24,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication public override void InitializeAll() { - Activity = "Read Configuration"; + Activity = iPerlCommunicationForm.ReadConfigurationStr; SimultWithPrevious = false; SimultWithNext = false; } diff --git a/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/ConfigStruct.cs b/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/ConfigStruct.cs index ee19bd1e4..5ae3ad7b9 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/ConfigStruct.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/ConfigStruct.cs @@ -3,264 +3,141 @@ /// using System; using System.IO; +using System.Text; +using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed; +using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons; namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead { public class ConfigStruct { - public const int Length = 32; + //public const int Length = 32; // dynamic - public Byte Version; /// 0: 1 byte - public MeterState MeterState; /// 1: 1 byte - public UInt32 TargetTimeVeryLowBatt; /// 2: 4 bytes in seconds - public UInt32 TargetTimeLowBatt; /// 6: 4 bytes, in seconds - public UInt32 TestModeTime; /// 10: 4 bytes, Max. test mode time in seconds - public UInt16 EmptyPipeThreshold; /// 14: 2 bytes - public byte[] PCBNumber; /// 16: 5 bytes - public byte TestModeConfig; /// 21: 1 byte - public UInt32 RadioAddress; /// 22: 4 bytes - public UInt16 TempCalibration; /// 26: 2 bytes - public UInt16 AlarmMask; /// 28: 2 bytes, Default 0xA3F7 - public UInt16 ConfigCheckSum; /// 30: 2 bytes + //public Byte Version; // 0: 1 byte + public string PCBNumberString; // dynamic + public ProtocolStatuses StatusMode; // byte + public DiagnosticLedState OpthoStatusMode;// byte + public string Version; // dynamic + public ConfigStruct() { - PCBNumber = new byte[5]; } - public byte[] ToByteArray() + //Optho test status mode + public DiagnosticLedState TestModeConfig { - byte[] result = new byte[Length]; - - result[0] = Version; - result[1] = (byte)MeterState; - - result[2] = (byte)(TargetTimeVeryLowBatt & 0x000000FF); - result[3] = (byte)((TargetTimeVeryLowBatt >> 8) & 0x000000FF); - result[4] = (byte)((TargetTimeVeryLowBatt >> 16) & 0x000000FF); - result[5] = (byte)((TargetTimeVeryLowBatt >> 24) & 0x000000FF); - - result[6] = (byte)(TargetTimeLowBatt & 0x000000FF); - result[7] = (byte)((TargetTimeLowBatt >> 8) & 0x000000FF); - result[8] = (byte)((TargetTimeLowBatt >> 16) & 0x000000FF); - result[9] = (byte)((TargetTimeLowBatt >> 24) & 0x000000FF); - - result[10] = (byte)(TestModeTime & 0x000000FF); - result[11] = (byte)((TestModeTime >> 8) & 0x000000FF); - result[12] = (byte)((TestModeTime >> 16) & 0x000000FF); - result[13] = (byte)((TestModeTime >> 24) & 0x000000FF); - - result[14] = (byte)(EmptyPipeThreshold & 0x00FF); - result[15] = (byte)((EmptyPipeThreshold >> 8) & 0x00FF); - - result[16] = PCBNumber[0]; - result[17] = PCBNumber[1]; - result[18] = PCBNumber[2]; - result[19] = PCBNumber[3]; - result[20] = PCBNumber[4]; - - result[21] = TestModeConfig; - - result[22] = (byte)(RadioAddress & 0x000000FF); - result[23] = (byte)((RadioAddress >> 8) & 0x000000FF); - result[24] = (byte)((RadioAddress >> 16) & 0x000000FF); - result[25] = (byte)((RadioAddress >> 24) & 0x000000FF); - - result[26] = (byte)(TempCalibration & 0x00FF); - result[27] = (byte)((TempCalibration >> 8) & 0x00FF); - - result[28] = (byte)(AlarmMask & 0x00FF); - result[29] = (byte)((AlarmMask >> 8) & 0x00FF); - - result[30] = (byte)(ConfigCheckSum & 0x00FF); - result[31] = (byte)((ConfigCheckSum >> 8) & 0x00FF); - - return result; + get { return OpthoStatusMode; } } - - /// - /// Create a configuration structure from a complete byte array - /// - /// A complete byte array data - /// ConfigStruct or null when byte array was not complete - public static ConfigStruct FromByteArray(byte[] data) + //Activity test status mode + public ProtocolStatuses MeterState { - if (data.Length != Length) return null; - - ConfigStruct result = new ConfigStruct(); - - result.Version = data[0]; - result.MeterState = (MeterState)data[1]; - result.TargetTimeVeryLowBatt = (((UInt32)data[5] * 256 + data[4]) * 256 + data[3]) * 256 + data[2]; - result.TargetTimeLowBatt = (((UInt32)data[9] * 256 + data[8]) * 256 + data[7]) * 256 + data[6]; - result.TestModeTime = (((UInt32)data[13] * 256 + data[12]) * 256 + data[11]) * 256 + data[10]; - result.EmptyPipeThreshold = (UInt16)(data[15] * 256 + data[14]); - result.PCBNumber[0] = data[16]; - result.PCBNumber[1] = data[17]; - result.PCBNumber[2] = data[18]; - result.PCBNumber[3] = data[19]; - result.PCBNumber[4] = data[20]; - result.TestModeConfig = data[21]; - result.RadioAddress = (((UInt32)data[25] * 256 + data[24]) * 256 + data[23]) * 256 + data[22]; - result.TempCalibration = (UInt16)(data[27] * 256 + data[26]); - result.AlarmMask = (UInt16)(data[29] * 256 + data[28]); - result.ConfigCheckSum = (UInt16)(data[31] * 256 + data[30]); - - return result; + get + { + return StatusMode; + } } - /// + + /// /// Update the configuration structure from an incomplete byte array /// /// Offset of byte array data in ConfigStruct /// Byte array data /// true when successful, false when data are not appropriate - public bool Update(int offset, byte[] data) - { - if (offset == 0 && data.Length == 2) - { - /// iPerl mode of function - Version = data[0]; - MeterState = (MeterState)data[1]; - return true; - } - else if (offset == 0 && data.Length == 4) - { - /// iPerl mode of function and extra 2 bytes - Version = data[0]; - MeterState = (MeterState)data[1]; - return true; - } - else if (offset == 21 && data.Length == 1) - { - /// TestModeConfig value - TestModeConfig = data[21 - offset]; - return true; - } - else if (offset == 0 && data.Length == Length) - { - /// Complete ConfigStruct - Version = data[0]; - MeterState = (MeterState)data[1]; - TargetTimeVeryLowBatt = (((UInt32)data[5] * 256 + data[4]) * 256 + data[3]) * 256 + data[2]; - TargetTimeLowBatt = (((UInt32)data[9] * 256 + data[8]) * 256 + data[7]) * 256 + data[6]; - TestModeTime = (((UInt32)data[13] * 256 + data[12]) * 256 + data[11]) * 256 + data[10]; - EmptyPipeThreshold = (UInt16)(data[15] * 256 + data[14]); - PCBNumber[0] = data[16]; - PCBNumber[1] = data[17]; - PCBNumber[2] = data[18]; - PCBNumber[3] = data[19]; - PCBNumber[4] = data[20]; - TestModeConfig = data[21]; - RadioAddress = (((UInt32)data[25] * 256 + data[24]) * 256 + data[23]) * 256 + data[22]; - TempCalibration = (UInt16)(data[27] * 256 + data[26]); - AlarmMask = (UInt16)(data[29] * 256 + data[28]); - ConfigCheckSum = (UInt16)(data[31] * 256 + data[30]); - return true; - } - else - return false; - } + // public bool Update(int offset, ) + // { + // + // /// Complete ConfigStruct + // Version = data[0]; + // MeterState = (MeterState)data[1]; + // TargetTimeVeryLowBatt = (((UInt32)data[5] * 256 + data[4]) * 256 + data[3]) * 256 + data[2]; + // TargetTimeLowBatt = (((UInt32)data[9] * 256 + data[8]) * 256 + data[7]) * 256 + data[6]; + // TestModeTime = (((UInt32)data[13] * 256 + data[12]) * 256 + data[11]) * 256 + data[10]; + // EmptyPipeThreshold = (UInt16)(data[15] * 256 + data[14]); + // PCBNumberString + // TestModeConfig = data[21]; + // RadioAddress = (((UInt32)data[25] * 256 + data[24]) * 256 + data[23]) * 256 + data[22]; + // TempCalibration = (UInt16)(data[27] * 256 + data[26]); + // AlarmMask = (UInt16)(data[29] * 256 + data[28]); + // ConfigCheckSum = (UInt16)(data[31] * 256 + data[30]); + // return true; + // } + // else + // return false; + // } /// /// Returns PCB number string (12 characters, 12 decimal digits) /// /// PCB number STRING - public string GetPcbNrString() - { - return PCBNumber2String(this.PCBNumber); - } + public string GetPcbNrString(){ + return PCBNumberString; + } - /// - /// Converts PCBNumber to string (12 characters, 12 decimal digits) - /// - /// - /// PCB number string - public static string PCBNumber2String(byte[] pcbNumber) - { - if (pcbNumber.Length != 5) return string.Empty; - Int64 number = 0; - for (int i = 4; i >= 0; i--) - { - number = 256 * number + (Int64)pcbNumber[i]; - } - - return number.ToString(); - } public override string ToString() { - return string.Format("Config: V{0} State={1} VLoBattT={2}s LoBattT={3}s TestModeT={4}s EPThld={5} PCB#={6} TMCfg={7} RadioAddr={8} TempCalib={9} AlarmMask={10} CfgCheckSum={11}", - Version, - MeterState, - TargetTimeVeryLowBatt, - TargetTimeLowBatt, - TestModeTime, - EmptyPipeThreshold, - GetPcbNrString(), - TestModeConfig.ToString("X2"), - RadioAddress, - TempCalibration, - AlarmMask.ToString("X4"), - ConfigCheckSum.ToString("X4")); + return string.Format( + "Config: V{0} PCB#={1} StatusMode={2}", + Version, + GetPcbNrString(), + StatusMode + ); } public string ToString(int sel) { - return string.Format("{1} PCB#={6} TMCfg={7}", + return string.Format("{0} PCB#={1} StatusMode={2}", Version, - MeterState, - TargetTimeVeryLowBatt, - TargetTimeLowBatt, - TestModeTime, - EmptyPipeThreshold, GetPcbNrString(), - TestModeConfig.ToString("X2"), - RadioAddress, - TempCalibration, - AlarmMask.ToString("X4"), - ConfigCheckSum.ToString("X4")); + StatusMode + ); } public virtual void WriteBinary(BinaryWriter writer) { - writer.Write(Version); - writer.Write((byte)MeterState); - writer.Write(TargetTimeVeryLowBatt); - writer.Write(TargetTimeLowBatt); - writer.Write(TestModeTime); - writer.Write(EmptyPipeThreshold); - writer.Write(PCBNumber[0]); - writer.Write(PCBNumber[1]); - writer.Write(PCBNumber[2]); - writer.Write(PCBNumber[3]); - writer.Write(PCBNumber[4]); - writer.Write(TestModeConfig); - writer.Write(RadioAddress); - writer.Write(TempCalibration); - writer.Write(AlarmMask); - writer.Write(ConfigCheckSum); + writer.Write(0x11); // mark new type of verison + // Convert string to bytes (UTF8 is standard) + byte[] versionBytes = Encoding.UTF8.GetBytes(Version); + // 1) write length + writer.Write(versionBytes.Length); + // 2) write string bytes + writer.Write(versionBytes); + //writer.Write(Version); + + writer.Write((byte)StatusMode); + + byte[] PCBNumberStringBytes = Encoding.UTF8.GetBytes(PCBNumberString); + // 1) write length + writer.Write(PCBNumberStringBytes.Length); + // 2) write string bytes + writer.Write(PCBNumberStringBytes); + } public virtual void ReadBinary(BinaryReader reader) { - Version = reader.ReadByte(); - MeterState = (MeterState)reader.ReadByte(); - TargetTimeVeryLowBatt = reader.ReadUInt32(); - TargetTimeLowBatt = reader.ReadUInt32(); - TestModeTime = reader.ReadUInt32(); - EmptyPipeThreshold = reader.ReadUInt16(); - PCBNumber[0] = reader.ReadByte(); - PCBNumber[1] = reader.ReadByte(); - PCBNumber[2] = reader.ReadByte(); - PCBNumber[3] = reader.ReadByte(); - PCBNumber[4] = reader.ReadByte(); - TestModeConfig = reader.ReadByte(); - RadioAddress = reader.ReadUInt32(); - TempCalibration = reader.ReadUInt16(); - AlarmMask = reader.ReadUInt16(); - ConfigCheckSum = reader.ReadUInt16(); + // ---- Test Data type ---- + var readByte = reader.ReadByte(); + if (readByte != 0x11) return; // not correct version + // ---- Version ---- + // 1) read length + int length = reader.ReadInt32(); + // 2) read string bytes + byte[] versionBytes = reader.ReadBytes(length); + // 3) convert back to string + Version = Encoding.UTF8.GetString(versionBytes); + // ---- PCB Number ---- + // 1) read length + int lengthPCB = reader.ReadInt32(); + // 2) read string bytes + byte[] bytesPCB = reader.ReadBytes(lengthPCB); + // 3) convert back to string + PCBNumberString = Encoding.UTF8.GetString(bytesPCB); + + } } } diff --git a/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/IperlHead.cs b/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/IperlHead.cs index fdff320f2..5d2fef6ac 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/IperlHead.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/IperlHead.cs @@ -1050,7 +1050,7 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead string line = optoSerialPort.ReadLine(); // string byte[] bytes = optoSerialPort.Encoding.GetBytes(line); received = HexFormatter.ToSerialHex(bytes); - Console.WriteLine("RX ← " + received); + log.Debug("RX ← " + received); } return received; } diff --git a/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/IperlHeadTestCtrl.cs b/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/IperlHeadTestCtrl.cs index b2ee75463..4b4e30c9c 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/IperlHeadTestCtrl.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/IperlHeadTestCtrl.cs @@ -79,13 +79,14 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead { ListItem rfidListItem = new ListItem(); rfidListItem.Attributes.Add("style", "font-weight:bold"); + bool isTestModeSuccessful = false; switch (rfidCommandComboBox.SelectedValue) { case "ReadPCB": - rfidListItem.Text = $"PCB: {OptoHeadTest.ReadRequest_PCB(iPerlHead)}"; + rfidListItem.Text = $"PCB: {OptoHeadTest.ReadRequest_PCB(ref iPerlHead)}"; break; case "SetTestMode": - rfidListItem.Text = OptoHeadTest.SetTestMode(iPerlHead); + rfidListItem.Text = OptoHeadTest.SetTestMode(ref iPerlHead, ref isTestModeSuccessful); optoListBox.Items.Clear(); stopWorkerThread = false; optoThread = new Thread(OptoWorker); @@ -96,7 +97,8 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead } break; case "SetActiveMode": - rfidListItem.Text = OptoHeadTest.SetActiveMode(iPerlHead); + + rfidListItem.Text = OptoHeadTest.SetActiveMode(ref iPerlHead, ref isTestModeSuccessful); stopWorkerThread = true; iPerlHead.StopDataStreamProcessing(); // close opto port break; diff --git a/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/SimulationServices.cs b/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/SimulationServices.cs index 5f6b46b69..0f90ae570 100644 --- a/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/SimulationServices.cs +++ b/TBF/Rig/TestMethods/iPerlCommunication/iPerlHead/SimulationServices.cs @@ -1,5 +1,8 @@ using System; +using System.IO; using System.Linq; +using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.diagnosticLed; +using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons; namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead { @@ -9,9 +12,32 @@ namespace TBF.Rig.TestMethods.iPerlCommunication.iPerlHead internal static int ReadRequest(TestMethodCfg cfg, IperlHead iperlHead, MessageID messageID, int offset, int length, out byte[] buffer) { - byte[] configurationBuffer = new byte[ConfigStruct.Length] { 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 160, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + + string pcbStr = iperlHead.RfidComPortNr.ToString().PadRight(10,'0') + iperlHead.Position.ToString("D2"); + long decVal = Convert.ToInt64(pcbStr); + string nHexStr = decVal.ToString("X4"); + + ConfigStruct configStruct = new ConfigStruct(); + configStruct.PCBNumberString = nHexStr; + configStruct.StatusMode = ProtocolStatuses.Active; + configStruct.OpthoStatusMode = DiagnosticLedState.State4; + configStruct.Version = "Good Version: 123456"; + + byte[] configurationBuffer; + + using (var ms = new MemoryStream()) + using (var writer = new BinaryWriter(ms)) + { + configStruct.WriteBinary(writer); + writer.Flush(); + configurationBuffer = ms.ToArray(); // ← this is the binary output + } + byte[] calibrationBuffer = new byte[CalibrationStructV4.Length] { 3, 0, 150, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 150, 10 }; buffer = new byte[length]; + + return 0;//switch off if (messageID == MessageID.Configuration) { diff --git a/TBF/TBF.csproj b/TBF/TBF.csproj index 05496974d..17680c08a 100644 --- a/TBF/TBF.csproj +++ b/TBF/TBF.csproj @@ -39,7 +39,7 @@ full false bin\Debug\ - TRACE;DEBUG;CAMERA;LANG_PL + TRACE;DEBUG;CAMERA;LANG_PL;IPERL prompt 4 true @@ -50,7 +50,7 @@ pdbonly true bin\Release\ - TRACE;CAMERA;LANG_PL + TRACE;CAMERA;LANG_PL;IPERL prompt 4 AnyCPU @@ -60,7 +60,7 @@ true bin\Debug\ - TRACE;DEBUG;CAMERA;LANG_PL + TRACE;DEBUG;CAMERA;LANG_PL;IPERL full AnyCPU prompt @@ -70,7 +70,7 @@ bin\x86\Release\ - TRACE;CAMERA;LANG_PL + TRACE;CAMERA;LANG_PL;IPERL true pdbonly AnyCPU @@ -1465,7 +1465,7 @@ - +