1129 lines
48 KiB
C#
1129 lines
48 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using NCrunch.Framework;
|
|
using Xylem.Common.CommonCore.Consts;
|
|
using Xylem.Common.Hardware.WaterMeter.Genesis.Applications;
|
|
using Xylem.Common.Hardware.WaterMeter.Genesis.Applications.Const;
|
|
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisConfig;
|
|
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore;
|
|
using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile;
|
|
using Xylem.Common.Hardware.WaterMeter.Genesis.Registers;
|
|
using Xylem.Common.Hardware.WaterMeter.Genesis.Registers.DataTypes;
|
|
using Xylem.Common.Logic.ProductionOrderCore.OrderData;
|
|
using Xylem.Common.Logic.ProductionOrderCore.TestResults;
|
|
|
|
namespace Xylem.Common.Hardware.WaterMeter.Genesis.MockGenesis
|
|
{
|
|
/// <summary>
|
|
/// Mock Genesis for usage to simulate an original Genesis without any hardware:
|
|
/// - The communication will use buffers program internally instead a physical port,
|
|
/// - Login, Logout and all other operations will NOT use a database call.
|
|
/// </summary>
|
|
public class MockGenesis : GenesisMeter
|
|
{
|
|
#region -------------------------------- Properties -----------------------------------------------------------
|
|
|
|
/// <summary>
|
|
/// The application description file (ADF) will be used to install a simulated new firmware to
|
|
/// the mock Genesis
|
|
/// </summary>
|
|
private String _packageDescriptionFile = DefaultPackageDescriptionFile;
|
|
|
|
/// <summary>
|
|
/// The required mock firmware installation is based on the file application simulation an installation
|
|
/// based on the package description file.
|
|
/// </summary>
|
|
private List<FileApplications> _mockFw = new List<FileApplications>();
|
|
|
|
/// <summary>
|
|
/// A list of all config registers for debug.
|
|
/// </summary>
|
|
// ReSharper disable once CollectionNeverQueried.Local for DEBUG only
|
|
private readonly List<String> _configRegisterNames = new List<String>();
|
|
|
|
/// <summary>
|
|
/// A list of all FLASH registers for debug.
|
|
/// </summary>
|
|
// ReSharper disable once CollectionNeverQueried.Local for DEBUG only
|
|
private readonly List<String> _flashRegisterNames = new List<String>();
|
|
|
|
/// <summary>
|
|
/// Simulated permanent storage (FLASH memory) to keep the values set with store configuration.
|
|
/// </summary>
|
|
private readonly MeterRegisters _flashRegister = new MeterRegisters();
|
|
|
|
/// <summary>
|
|
/// A list of all known registers which do not return the written value.
|
|
/// EXAMPLES:
|
|
/// - SENSUSRADIO_SystemState writing 0xFF returns 0x02
|
|
/// - XXX_StoreConfiguration writing 0x01 returns 0x00
|
|
///
|
|
/// The registers can be fully qualified or contain a substring like _StoreConfiguration if it always
|
|
/// returns an identical reply!
|
|
///
|
|
/// The first value is the expected value which will be searched for and the second value is the reply!
|
|
/// Only it the first value is exact as described here the reply is going to be changed.
|
|
///
|
|
/// </summary>
|
|
private static readonly List<RecoveryRegisterItem> SpecialRegisterReplies = new List<RecoveryRegisterItem>
|
|
{
|
|
// (partial) name expected value reply value
|
|
new RecoveryRegisterItem("SENSUSRADIO_SystemState", new Byte[]{0xFF}, new Byte[]{0x02}),
|
|
new RecoveryRegisterItem("_StoreCalibration", new Byte[]{0x01}, new Byte[]{0x00}),
|
|
new RecoveryRegisterItem("_StoreConfiguration", new Byte[]{0x01}, new Byte[]{0x00})
|
|
};
|
|
|
|
/// <summary>
|
|
/// A list of all known registers to trigger a rest of the input bit.
|
|
/// EXAMPLES:
|
|
/// - CUSTOMER_TriggerAlarmCancel register value
|
|
/// before input 0000 0001 0001 1111
|
|
/// new reset input 0000 1111 1111 0000
|
|
/// output 0000 0000 0000 1111
|
|
///
|
|
/// </summary>
|
|
private static readonly List<RecoveryRegisterItem> SpecialRegisterResetBits = new List<RecoveryRegisterItem>
|
|
{
|
|
// (partial) name placeholder for input and output
|
|
new RecoveryRegisterItem("CUSTOMER_TriggerAlarmCancel", new Byte[4]),
|
|
};
|
|
|
|
|
|
/// <summary>
|
|
/// The root path for all mock FwPackaged.
|
|
/// </summary>
|
|
private const String RootMockFwPath = "MockFwExamples";
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite PcbId for test purposes and set password to null to avoid
|
|
/// usage of wrong password and lock of the device trying to log in with the wrong password
|
|
/// </summary>
|
|
public new String PcbId
|
|
{
|
|
set
|
|
{
|
|
base.PcbId = value;
|
|
ClearPassword();
|
|
}
|
|
get => base.PcbId;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite LutCrc for test purposes
|
|
/// </summary>
|
|
public new String LutCrc
|
|
{
|
|
set => base.LutCrc = value;
|
|
get => base.LutCrc;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite StrCoreRevision for test purposes
|
|
/// </summary>
|
|
public new String StrCoreRevision
|
|
{
|
|
set => base.StrCoreRevision = value;
|
|
get => base.StrCoreRevision;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite CoreRevision for test purposes
|
|
/// </summary>
|
|
public new Int32? CoreRevision
|
|
{
|
|
set => base.CoreRevision = value;
|
|
get => base.CoreRevision;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite RadioFrequencyMhz for test purposes
|
|
/// </summary>
|
|
public new Int32? RadioFrequencyMhz
|
|
{
|
|
set => base.RadioFrequencyMhz = value;
|
|
get => base.RadioFrequencyMhz;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite InstalledFwVersion for test purposes
|
|
/// </summary>
|
|
public new UInt32? InstalledFwVersion
|
|
{
|
|
set => base.InstalledFwVersion = value;
|
|
get => base.InstalledFwVersion;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite Region for test purposes
|
|
/// </summary>
|
|
public new String Region
|
|
{
|
|
set => base.Region = value;
|
|
get => base.Region;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite MeterSize for test purposes
|
|
/// </summary>
|
|
public new String MeterSize
|
|
{
|
|
private set => base.MeterSize = value;
|
|
get => base.MeterSize;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite length for test purposes
|
|
/// </summary>
|
|
public new String MeterLength
|
|
{
|
|
set => base.MeterLength = value;
|
|
get => base.MeterLength;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite pressure sensor is assembled for test purposes
|
|
/// </summary>
|
|
public new Boolean PressureSensorAssembled
|
|
{
|
|
private set => base.PressureSensorAssembled = value;
|
|
get => base.PressureSensorAssembled;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock object can overwrite FwVersion for test purposes
|
|
/// </summary>
|
|
public new String FwVersion
|
|
{
|
|
private set => base.FwVersion = value;
|
|
get => base.FwVersion;
|
|
}
|
|
/// <summary>
|
|
/// Mock object can overwrite login status for test purposes
|
|
/// </summary>
|
|
public new Boolean IsLoggedOn
|
|
{
|
|
set => base.IsLoggedOn = value;
|
|
get => base.IsLoggedOn;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The exec path of the assembly for debug in environment.
|
|
/// </summary>
|
|
private readonly String _assemblyExecRootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
|
|
|
/// <summary>
|
|
/// Fw package path relative to solution main folder.
|
|
/// </summary>
|
|
private readonly String _mockFwPackageRootPath;
|
|
|
|
#endregion ----------------------------- Properties -----------------------------------------------------------
|
|
|
|
#region --------------------------------- Default package description file ------------------------------------
|
|
|
|
/// <summary>
|
|
/// This file will be used to assign the default MeterApplications as simulated installation to the Genesis
|
|
/// meter. It contains only the important information:
|
|
/// - Each line starting with "Id" is an App,
|
|
/// - the "Maximum supported core revision" will be used as CoreRevision.
|
|
/// </summary>
|
|
private const String DefaultPackageDescriptionFile =
|
|
"Id 0x00, CRC16 0x39A8, size 37972 bytes, version 5.37\r\n" +
|
|
"Id 0x01, CRC16 0xB16C, size 3112 bytes, version 0.70\r\n" +
|
|
"Id 0x04, CRC16 0x8290, size 7944 bytes, version 2.38\r\n" +
|
|
"Id 0x08, CRC16 0x12D4, size 3972 bytes, version 0.18\r\n" +
|
|
"Id 0x11, CRC16 0x5796, size 12412 bytes, version 0.75\r\n" +
|
|
"Id 0x10, CRC16 0x0704, size 93488 bytes, version 5.30\r\n" +
|
|
"Id 0x0F, CRC16 0xA3A6, size 25164 bytes, version 3.02\r\n" +
|
|
"Id 0x09, CRC16 0xD56D, size 6196 bytes, version 1.59\r\n" +
|
|
"Id 0x12, CRC16 0x9BA6, size 7948 bytes, version 1.13\r\n" +
|
|
"Id 0x14, CRC16 0x2EB1, size 23324 bytes, version 2.06\r\n" +
|
|
"Id 0x15, CRC16 0x43F4, size 6808 bytes, version 0.59\r\n" +
|
|
"Id 0x18, CRC16 0xB2D5, size 116 bytes, version 13.0B\r\n" +
|
|
"Maximum supported core revision: \"Cordonel 1.78\"";
|
|
|
|
#endregion ------------------------------ Default package description file ------------------------------------
|
|
|
|
#region -------------------------------- Class handling -------------------------------------------------------
|
|
|
|
/// <summary>
|
|
/// Standard Ctor
|
|
/// </summary>
|
|
public MockGenesis()
|
|
{
|
|
var subFolder = Path.Combine("Hardware", "WaterMeter", "Genesis", "MockGenesis");
|
|
var solutionPath = "";
|
|
if (NCrunchEnvironment.NCrunchIsResident())
|
|
{
|
|
solutionPath = NCrunchEnvironment.GetOriginalSolutionPath().Replace("Common.sln", "");
|
|
}
|
|
else
|
|
{
|
|
if (_assemblyExecRootPath != null)
|
|
{
|
|
// We are in the Unit test folder "..\Common\Production\ProductionUiCordonel.UnitTests\bin\Debug"
|
|
// and need to go back to "..\Common"
|
|
var directoryInfo = Directory.GetParent(_assemblyExecRootPath)?.Parent?.Parent?.Parent?.Parent;
|
|
if (directoryInfo != null)
|
|
{
|
|
solutionPath = directoryInfo.FullName;
|
|
}
|
|
}
|
|
}
|
|
|
|
_mockFwPackageRootPath = Path.Combine(solutionPath, subFolder, "MockFwExamples");
|
|
Console.WriteLine($@"MOCK GENESIS: Search path for MockFwExamples: {_mockFwPackageRootPath}");
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region -------------------------------- Firmware update and modification -------------------------------------
|
|
|
|
/// <summary>
|
|
/// Install a new firmware to the mock with the package description file as serialized string
|
|
/// <see cref="DefaultPackageDescriptionFile"/> which is reduced to the important lines or alternative
|
|
/// a named FW Version string like "R1.3.0B" or "R130B" which has to be part of the MockFwExamples.
|
|
///
|
|
/// The filters to find the path in the root path is the region and FW release version
|
|
/// "EMEA" or "NA"
|
|
/// "R130B" or "R1.3.0B"
|
|
/// additional naming is allowed (e.g. "EMEA_R13F3_replaces_R1107_R1108")
|
|
///
|
|
/// The filters to accept the file is:
|
|
/// "product" and
|
|
/// ".txt"
|
|
/// additional naming is allowed (e.g. "rowproduct_R130B.txt")
|
|
///
|
|
/// The FW root path is the path where the FW update packages are stored.
|
|
/// All files needed to be stored directly in the main folder of the FW version:
|
|
///
|
|
/// EXAMPLE:
|
|
/// [Root path]\EMEA_R130B\rowproduct_xyz.txt (package description file, mandatory is "product" and ".txt")
|
|
/// \configuration.json
|
|
/// \binfile00_0537_xyz.bin (package description file, mandatory is "binfile" and ".bin")
|
|
/// \binfile01_0070_xyz.bin
|
|
/// \...
|
|
/// \binfile18_130B_xyz.bin
|
|
/// [Root path]\NA_R2006 \naproduct_xyz.txt (package description file, mandatory is "product" and ".txt")
|
|
/// \configuration.json
|
|
/// \binfile00_0533_xyz.bin (package description file, mandatory is "binfile" and ".bin")
|
|
/// \binfile01_0068_xyz.bin
|
|
/// \...
|
|
/// \binfile18_2006_xyz.bin
|
|
///
|
|
/// </summary>
|
|
/// <param name="packageDescriptionFile"></param>
|
|
/// <param name="fwName">if this is null, the description file will be installed</param>
|
|
/// <remarks date="2024-Dec-02" author="Thomas Wiedebusch">
|
|
/// - Initial
|
|
/// </remarks>
|
|
/// <remarks date="2024-Dec-12" author="Thomas Wiedebusch">
|
|
/// - Logout, clear FLASH, login.
|
|
/// </remarks>
|
|
/// <remarks date="2024-Dec-18" author="Thomas Wiedebusch">
|
|
/// - Take FW version from MockFwExamples if explicit named with the release string.
|
|
/// </remarks>
|
|
/// <remarks date="2024-Dec-19" author="Thomas Wiedebusch">
|
|
/// - Returns bool.
|
|
/// </remarks>
|
|
public Boolean InstallNewMockFw(String packageDescriptionFile = null, String fwName = null)
|
|
{
|
|
if (fwName != null)
|
|
{
|
|
var releaseName = FwVersion.Replace(".", "");
|
|
|
|
if (!FwVersion.Equals(fwName) && !releaseName.Contains(fwName))
|
|
{
|
|
//Load new rawproduct.txt or naproduct.txt and install it to MockGenesis
|
|
if (!MeterFwUpdate.LoadPackageFile(_mockFwPackageRootPath, fwName, out _packageDescriptionFile))
|
|
return false;
|
|
}
|
|
}
|
|
else if (packageDescriptionFile != null)
|
|
{
|
|
// Set the new package file which will be parsed and used as simulation for all installed
|
|
// applications
|
|
_packageDescriptionFile = packageDescriptionFile;
|
|
}
|
|
else
|
|
{
|
|
return false;
|
|
}
|
|
|
|
Logout();
|
|
_flashRegister.MeterRegisterDic.Clear();
|
|
_flashRegisterNames.Clear();
|
|
|
|
// Force re-generation of the meter app and config register lists
|
|
MeterAppListVersion.Clear();
|
|
ConfigRegister.MeterRegisterDic.Clear();
|
|
ConfigApplications.Clear();
|
|
|
|
// Login to build initial registers being able to use the FLASH register dictionary immediately.
|
|
Login();
|
|
|
|
return RebootGenesis() == StatusReturn.Okay;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Prepare the mock installed firmware by parsing the package description file.
|
|
/// </summary>
|
|
/// <remarks date="2024-Dec-01" author="Thomas Wiedebusch">
|
|
/// - Initial
|
|
/// </remarks>
|
|
private void ParsePackageDescriptionFile()
|
|
{
|
|
if (string.IsNullOrEmpty(_packageDescriptionFile))
|
|
return;
|
|
|
|
if (_mockFw == null)
|
|
_mockFw = new List<FileApplications>();
|
|
_mockFw.Clear();
|
|
|
|
MeterFwUpdate.GetPackageFileApplications(_packageDescriptionFile, _mockFw);
|
|
CoreRevision = MeterFwUpdate.GetCoreRevisionMax(_packageDescriptionFile);
|
|
if (CoreRevision != null)
|
|
StrCoreRevision = BuildFwVersionStringFromDec(CoreRevision);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Modify or erase one mock app to simulate an application error of the firmware package.
|
|
/// This will be used for test purposes to manually change installed app-properties.
|
|
///
|
|
/// REMIND: All Apps are required to stay in MeterAppListVersion as this is a list of all Apps found in the
|
|
/// configuration.json. Does mean, for erasure just change the status to
|
|
/// <see cref="MeterAppState.MeterAppNotInstalled"/> !
|
|
///
|
|
/// </summary>
|
|
/// <param name="appId"></param>
|
|
/// <param name="version">null doesn't change actual version</param>
|
|
/// <param name="crc">null doesn't change actual CRC</param>
|
|
/// <param name="eraseApp"></param>
|
|
/// <returns>true if modification could be done</returns>
|
|
/// <remarks date="2024-Dec-04..05" author="Thomas Wiedebusch">
|
|
/// - Initial
|
|
/// </remarks>
|
|
public Boolean ModifyMockApp(Byte appId, UInt32? version = null, UInt16? crc = null, Boolean eraseApp = false)
|
|
{
|
|
if (MeterAppListVersion == null ||
|
|
MeterAppListVersion.Count == 0 ||
|
|
MeterAppListVersion.All(app => app.AppId != appId))
|
|
return false;
|
|
|
|
Logout();
|
|
|
|
foreach (var app in MeterAppListVersion.Where(app => app.AppId == appId))
|
|
{
|
|
if (eraseApp)
|
|
{
|
|
app.IsInstalled = false;
|
|
app.Status = MeterAppState.MeterAppNotInstalled;
|
|
app.StrVersion = "0.0";
|
|
app.Version = 0;
|
|
}
|
|
if (version != null)
|
|
{
|
|
app.Version = (UInt32)version;
|
|
app.StrVersion = BuildFwVersionStringFromDec((Int32?)version);
|
|
}
|
|
|
|
if (crc != null)
|
|
{
|
|
app.Crc = (UInt16)crc;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
#endregion ----------------------------- Firmware update and modification -------------------------------------
|
|
|
|
#region -------------------------------- Mock Genesis Initialization ------------------------------------------
|
|
/// <summary>
|
|
/// Mock reading all applications from a predefined package description file instead from the Meter.
|
|
/// </summary>
|
|
/// <remarks date="2024-Dec-01" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
/// <remarks date="2025-Jun-19" author="Thomas Wiedebusch">
|
|
/// - Avoid overwriting of list combined with valid register dictionary.
|
|
/// </remarks>
|
|
/// <remarks date="2025-Aug-07" author="Thomas Wiedebusch">
|
|
/// - Check interface compatibility.
|
|
/// </remarks>
|
|
protected override void ReadMeterFirmwareAndAssignRegisters()
|
|
{
|
|
// Avoid overwriting of list if this already exits
|
|
if (MeterAppListVersion.Any() && MeterAppListVersion.All(f => f.Status != MeterAppState.Unknown) &&
|
|
ConfigRegister.MeterRegisterDic.Count != 0)
|
|
{
|
|
Logger.Warn($"Slot:{Slot} - Trying to overwride installed FW. Skipping generation of new " +
|
|
"App list and meter register dictionary");
|
|
return;
|
|
}
|
|
|
|
// This loads the configuration.json from the exec directory
|
|
LoadConfiguration(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
|
|
|
|
// Simulate a firmware installation using the package description file to assign applications
|
|
ParsePackageDescriptionFile();
|
|
|
|
// Use the _mockFw created out of the package description file and which is a file application list
|
|
if (_mockFw == null || _mockFw.Count < MeterFwUpdate.MinAppsRequiredForOperation)
|
|
{
|
|
return;
|
|
}
|
|
|
|
UInt32 interfaceMaxEmeaVersion = 0;
|
|
UInt32 interfaceMaxNaVersion = 0;
|
|
var strInterfaceMaxEmeaVersion = "";
|
|
var strInterfaceMaxNaVersion = "";
|
|
|
|
//Get all existing applications from meter register dictionary
|
|
foreach (var meterApp in ConfigApplications.OrderBy(o => o.AppId))
|
|
{
|
|
if (meterApp.AppName.Equals("OPTICALINTERFACE"))
|
|
{
|
|
// Build the interface id for information of compatibility from FW to configuration.json
|
|
InterfaceVersion = BuildFwVersionStringFromDec(meterApp.AppVersion);
|
|
// Build the max supported versions for EMEA and NA to check the supported FW
|
|
strInterfaceMaxEmeaVersion = BuildFlexnetFwVersion(out interfaceMaxEmeaVersion,
|
|
meterApp.InterfaceMaxEmeaVersion);
|
|
strInterfaceMaxNaVersion = BuildFlexnetFwVersion(out interfaceMaxNaVersion,
|
|
meterApp.InterfaceMaxNaVersion);
|
|
continue;
|
|
}
|
|
|
|
// Take all listed config apps even if not installed
|
|
var app = new MeterApplications
|
|
{
|
|
AppId = meterApp.AppId,
|
|
Version = 0,
|
|
StrVersion = "0.00",
|
|
AppName = meterApp.AppName,
|
|
Crc = 0x0000,
|
|
Status = MeterAppState.MeterAppNotInstalled,
|
|
IsInstalled = false
|
|
};
|
|
|
|
foreach (var fileApp in _mockFw)
|
|
{
|
|
if (fileApp.AppId == meterApp.AppId)
|
|
{
|
|
app.Version = fileApp.Version;
|
|
app.StrVersion = fileApp.StrVersion;
|
|
app.Crc = fileApp.Crc;
|
|
app.Status = MeterAppState.MeterAppUpToDate;
|
|
app.IsInstalled = true;
|
|
}
|
|
|
|
// The FLEXNETVERSION is the overall firmware version
|
|
if (fileApp.AppId == MeterFwUpdate.FlexnetVersionAppId)
|
|
{
|
|
InstalledFwVersion = fileApp.Version;
|
|
FwVersion = fileApp.StrVersion;
|
|
}
|
|
}
|
|
|
|
MeterAppListVersion.Add(app);
|
|
}
|
|
|
|
try
|
|
{
|
|
// Initial list of ALL registers defined in configuration.json read from local bin directory
|
|
var tempConfigRegisters = ConfigRegister.MeterRegisterDic.ToList();
|
|
|
|
// Reduce registers to valid registers for a specific application with a specific version
|
|
// The old register dictionary is going to be cleared automatically calling this method.
|
|
BuildValidMeterRegisters(tempConfigRegisters);
|
|
|
|
// Fill the meter register dictionary with defaults are stored values in simulated FLASH memory
|
|
InitConfigAndFlashRegisters();
|
|
|
|
// Check for SENSUSRADIO as indication for region "EMEA", else it is regin "NA"
|
|
Region = "NA";
|
|
if (ConfigRegister.MeterRegisterDic.Any(app => app.Key.AppName.Equals("SENSUSRADIO")))
|
|
{
|
|
var value = ConfigRegister.Get("SENSUSRADIO_FrequencyIndicator");
|
|
if (value != null)
|
|
{
|
|
RadioFrequencyMhz = RegisterConverter.ByteArrayToValue<Int32>(value);
|
|
Region = "EMEA";
|
|
}
|
|
}
|
|
|
|
// Assign the max supported FW version of the interface depending on the region
|
|
if (Region.Equals("EMEA"))
|
|
InterfaceMaxFwVersion = strInterfaceMaxEmeaVersion;
|
|
if (Region.Equals("NA"))
|
|
InterfaceMaxFwVersion = strInterfaceMaxNaVersion;
|
|
|
|
// Check if the interface supports the FW
|
|
if (InstalledFwVersion != null &&
|
|
((Region.Equals("EMEA") && interfaceMaxEmeaVersion >= InstalledFwVersion) ||
|
|
(Region.Equals("NA") && interfaceMaxNaVersion >= InstalledFwVersion)))
|
|
{
|
|
InterfaceSupportsFwVersion = true;
|
|
Logger.Info($"Slot:{Slot} - Interface supports FW version: {FwVersion}");
|
|
}
|
|
else
|
|
{
|
|
InterfaceSupportsFwVersion = false;
|
|
Logger.Warn($"Slot:{Slot} - Interface does not support FW version! Installed FW version: {FwVersion}, " +
|
|
$"Interface supports max FW version: {InterfaceMaxFwVersion}");
|
|
}
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.Error($"Slot:{Slot} - {ex.Message}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Use the app name to flash all contents:
|
|
/// - Take all values from RAM memory (config register dictionary) and copy it to FLASH memory (flash
|
|
/// register dictionary) which simulates the non-volatile memory of the Genesis.
|
|
/// </summary>
|
|
/// <param name="appName"></param>
|
|
/// <remarks date="2024-Dec-03" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
private void FlashMemory(String appName)
|
|
{
|
|
if (_flashRegister == null || ConfigRegister == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
// Safe all data from config to FLASH register dictionary for App.
|
|
foreach (var reg in ConfigRegister.MeterRegisterDic)
|
|
{
|
|
try
|
|
{
|
|
var regName = reg.Key.GetIdent();
|
|
|
|
// Filter for all registers of a specific App
|
|
if (regName.Contains(appName))
|
|
{
|
|
// Avoid writing of NOT writable registers, only read write makes sense as others cannot be
|
|
// read back!
|
|
if (reg.Key.RegisterDetail.Privilege.Lvl8 == Access.RW &&
|
|
reg.Key.DataType != typeof(Rpc))
|
|
{
|
|
var flashData = ConfigRegister.Get(regName);
|
|
// Throws an exception if register doesn't exist, but we want to go ahead with the others
|
|
var regDef = _flashRegister.GetRegisterDefinitionByName(regName);
|
|
_flashRegister.Set(regDef, flashData);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.Error($"Slot:{Slot} - {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Store one single parameter to flash memory to simulate FW internal change of register or the
|
|
/// "GENESISFLOW_StoreCalibration":
|
|
/// - Avoid to check of RO or WO to force an update as it would be done by the FW.
|
|
/// </summary>
|
|
/// <param name="regName"></param>
|
|
/// <remarks date="2024-Dec-07" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
private void SingleParameterFlashMemory(String regName)
|
|
{
|
|
if (_flashRegister == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
var flashData = ConfigRegister.Get(regName);
|
|
// Throws an exception if register doesn't exist, but we want to go ahead with the others
|
|
var regDef = _flashRegister.GetRegisterDefinitionByName(regName);
|
|
_flashRegister.Set(regDef, flashData);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.Error($"Slot:{Slot} - {ex.Message}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fill the meter register dictionary with the stored values of the simulated FLASH memory:
|
|
/// - If FLASH memory register dictionary doesn't exist (initial start) generate a copy of
|
|
/// the config register dictionary and fill it with default values from configuration.json,
|
|
/// - Copy ALWAYS the content of the FLASH to the config register dictionary.
|
|
///
|
|
/// REMIND:
|
|
/// If an application has received a store configuration, the FLASH content will be overwritten
|
|
/// from default value to the actual value of the config register dictionary as this is the
|
|
/// temporary value (RAM simulation) of the Genesis.
|
|
///
|
|
/// </summary>
|
|
/// <remarks date="2024-Dec-03..10" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
private void InitConfigAndFlashRegisters()
|
|
{
|
|
if (_flashRegister == null || ConfigRegister == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_configRegisterNames.Clear();
|
|
// If the FLASH registers do not exist, create those and fill it with default values
|
|
if (_flashRegister.MeterRegisterDic.Count == 0)
|
|
{
|
|
foreach (var reg in ConfigRegister.MeterRegisterDic)
|
|
{
|
|
var regName = reg.Key.GetIdent();
|
|
_flashRegisterNames.Add(regName);
|
|
var regDef = ConfigRegister.GetRegisterDefinitionByName(regName);
|
|
|
|
// First clone entire register set to avoid exception if register is not available
|
|
_flashRegister.MeterRegisterDic.TryAdd(reg.Key, null);
|
|
|
|
// Avoid writing of NOT writable registers
|
|
if (reg.Key.RegisterDetail.Privilege.Lvl8 == Access.RW) // && reg.Key.DataType != typeof(Rpc))
|
|
{
|
|
// Add default value to FLASH register dictionary
|
|
RegisterConverter.SetToDefault(regDef, out var value);
|
|
_flashRegister.Set(regDef, value);
|
|
}
|
|
}
|
|
|
|
_flashRegisterNames.Sort();
|
|
}
|
|
|
|
// Preset at initial login after start or reboot all config registers with the FLASH register values.
|
|
// Those are set to default on initial start and after store configuration on a predefined value.
|
|
foreach (var reg in ConfigRegister.MeterRegisterDic)
|
|
{
|
|
try
|
|
{
|
|
var regName = reg.Key.GetIdent();
|
|
_configRegisterNames.Add(regName);
|
|
var regDef = ConfigRegister.GetRegisterDefinitionByName(regName);
|
|
|
|
// Avoid writing of NOT writable registers, only read write makes sense as others cannot be read
|
|
// back!
|
|
if (reg.Key.RegisterDetail.Privilege.Lvl8 == Access.RW) //&& reg.Key.DataType != typeof(Rpc))
|
|
{
|
|
var flashData = _flashRegister.Get(regName);
|
|
|
|
// Throws an exception if register doesn't exist, but we want to go ahead with the others
|
|
ConfigRegister.Set(regDef, flashData);
|
|
}
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.Error($"Slot:{Slot} - {ex.Message}");
|
|
}
|
|
_configRegisterNames.Sort();
|
|
}
|
|
}
|
|
|
|
#endregion ----------------------------- Mock Genesis Initialization ------------------------------------------
|
|
|
|
#region -------------------------------- Mock Genesis Simulation ----------------------------------------------
|
|
/// <inheritdoc />
|
|
/// <summary>
|
|
/// Simulate login to mock Genesis for test purposes
|
|
/// </summary>
|
|
/// <remarks date="2024-Nov-28" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
public override Boolean Login()
|
|
{
|
|
ReadMeterFirmwareAndAssignRegisters();
|
|
IsLoggedOn = true;
|
|
return IsLoggedOn;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
/// <summary>
|
|
/// Simulate logout to mock Genesis for test purposes
|
|
/// </summary>
|
|
/// <remarks date="2024-Nov-28" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
public override Boolean Logout()
|
|
{
|
|
IsLoggedOn = false;
|
|
return IsLoggedOn;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
/// <summary>
|
|
/// Set the meter size if previously unlocked.
|
|
/// - MockGenesis allows additional empty string or question mark string!
|
|
/// </summary>
|
|
/// <param name="meterSize">true if setting is allowed</param>
|
|
/// <returns>true if possible</returns>
|
|
public override Boolean SetMeterSize<T>(T meterSize)
|
|
{
|
|
if (!UnlockEssentialProperties)
|
|
return false;
|
|
|
|
if (meterSize is String)
|
|
{
|
|
var ms = meterSize.ToString();
|
|
// MockGenesis allows 'killing' of MeterSize
|
|
if (Equals(meterSize,"") || Equals(meterSize,"?"))
|
|
{
|
|
|
|
}
|
|
else if (Logic.ProductionOrderCore.OrderData.MeterSize.NA == MeterSizeConverter.ConvertMeterSizeNameToEnum(ms))
|
|
{
|
|
return false;
|
|
}
|
|
MeterSize = ms;
|
|
}
|
|
else if (meterSize.GetType() == typeof(MeterSize))
|
|
{
|
|
var ms = Convert.ToInt32(meterSize);
|
|
MeterSize = MeterSizeConverter.ConvertMeterSizeEnumToSizeName((MeterSize)ms);
|
|
}
|
|
else // Type is unknown
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
/// <summary>
|
|
/// Simulate login with password to mock Genesis for test purposes
|
|
/// </summary>
|
|
/// <remarks date="2024-Nov-28" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
public override Boolean Login(String password, Boolean runImmediately = true,
|
|
Boolean skipReadMeterFwAndAssignRegisters = false)
|
|
{
|
|
Password = password;
|
|
return Login();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock Write Register:
|
|
/// - Optional: wait for result and validate.
|
|
/// </summary>
|
|
/// <typeparam name="T">Data type of Register</typeparam>
|
|
/// <param name="regName">Register to change</param>
|
|
/// <param name="value">Value to save</param>
|
|
/// <param name="waitForResult">wait until result is ready</param>
|
|
/// <param name="checkRegister">check the content of the register by read back</param>
|
|
/// <param name="skipRetryErrorCode">skip retries on this error code return</param>
|
|
/// <returns>true on successful operation</returns>
|
|
/// <remarks date="2024-Dec-02..03" author="Thomas Wiedebusch">
|
|
/// - Initial mock implementation.
|
|
/// </remarks>
|
|
/// <remarks date="2024-Dec-10" author="Thomas Wiedebusch">
|
|
/// - Capture "SYSTEM_TriggerUpgrade" to force a reboot and install the FW defined in the actual FW package
|
|
/// description file.
|
|
/// - Store calibration executed on calibration registers.
|
|
/// </remarks>
|
|
public override Boolean WriteRegister<T>(String regName, T value, Boolean waitForResult = true,
|
|
Boolean checkRegister = false, UInt16 skipRetryErrorCode = CommunicationConfig.SkipRetryErrorCode)
|
|
{
|
|
try
|
|
{
|
|
var regDef = ConfigRegister.GetRegisterDefinitionByName(regName);
|
|
var data = RegisterConverter.ValueToByteArray(value);
|
|
var hideDataInLog = regDef.RegisterName.Contains("EncryptionKey") ||
|
|
regDef.RegisterName.Contains("Password");
|
|
|
|
var rawMsg = RegisterConverter.GetRegisterRawText(regDef, data, hideDataInLog);
|
|
Logger.Info($"Slot:{Slot} - Write register({regDef.GetIdent()}), record({rawMsg})");
|
|
|
|
// Check for special response for predefined registers which reply with a changed
|
|
// parameter like SENSUSRADIO_SystemState set to 0xFF creates a reply of 0x02.
|
|
// This has to be done BEFORE ConfigRegister.Set!
|
|
CheckAndModifySpecialReplies(regName, data);
|
|
|
|
// Avoid writing of NOT writable registers and out of range of register value
|
|
if (!PreRegisterWrite(regDef, data))
|
|
return false;
|
|
|
|
// Throws an exception if register doesn't exist
|
|
ConfigRegister.Set(regDef, data);
|
|
|
|
// For mock simulation the write register is going to kick-off special activities
|
|
CheckSpecialActivities(regName, value);
|
|
|
|
// If no further action like check register or read-back is required, exit here with success
|
|
if (!waitForResult && !checkRegister)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
// If register check by read back is not required we return the acknowledgment state
|
|
if (!checkRegister || regDef.RegisterDetail.Privilege.Lvl8 == Access.WO)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
var readBackData = ReadRegister(regName, data.Length, skipRetryErrorCode);
|
|
if (readBackData == null)
|
|
return false;
|
|
|
|
// Check if register read was okay and read and written data are EQUAL
|
|
for (var i = 0; i < data.Length; i++)
|
|
{
|
|
if (readBackData[i] != data[i])
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Logger.Error($"Slot:{Slot} - {e.Message}");
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check for special activities needed to execute on register write access:
|
|
/// - Store configuration to safe all values of a single App to the simulated FLASH memory,
|
|
/// - Store calibration stores all defined register <see cref="CalibrationResults.CalibrationRegisterNames"/>,
|
|
/// to the simulated FLASH memory,
|
|
/// - Trigger upgrade forces a reboot of the meter including a reload of all applications and regeneration of
|
|
/// all registers.
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="regName"></param>
|
|
/// <param name="value"></param>
|
|
/// <remarks date="2024-Dec-10" author="Thomas Wiedebusch">
|
|
/// - Initial MockGenesis simulation.
|
|
/// </remarks>
|
|
private void CheckSpecialActivities<T>(String regName, T value)
|
|
{
|
|
// Capture "StoreConfiguration" to copy config register contents of App to FLASH
|
|
var searchString = "_StoreConfiguration";
|
|
if (regName.Contains(searchString))
|
|
{
|
|
var appName = regName.Replace(searchString, "");
|
|
FlashMemory(appName);
|
|
}
|
|
|
|
// Capture "StoreCalibration" to copy config register contents of App to FLASH
|
|
searchString = "GENESISFLOW_StoreCalibration";
|
|
if (regName.Contains(searchString))
|
|
{
|
|
// Store single parameter to FLASH
|
|
foreach (var registerName in CalibrationResults.CalibrationRegisterNames)
|
|
SingleParameterFlashMemory(registerName);
|
|
}
|
|
|
|
// Capture "UpgradePermissions" to copy config register contents of App to FLASH as
|
|
// SYSTEM doesn't have a "StoreConfiguration" command
|
|
searchString = "SYSTEM_UpgradePermissions";
|
|
if (regName.Contains(searchString))
|
|
{
|
|
SingleParameterFlashMemory(searchString);
|
|
}
|
|
|
|
// Capture "SYSTEM_TriggerUpgrade" to force a reboot and install the actual given firmware
|
|
// package description file as FW.
|
|
searchString = "SYSTEM_TriggerUpgrade";
|
|
if (regName.Equals(searchString) && typeof(T) == typeof(Boolean))
|
|
{
|
|
var forceTriggerUpgrade = (Boolean)Convert.ChangeType(value, typeof(Boolean));
|
|
if (forceTriggerUpgrade)
|
|
RebootGenesis();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Check for special response for predefined registers which reply with a changed parameter like
|
|
/// SENSUSRADIO_SystemState set to 0xFF creates a reply of 0x02. This should simulate the real
|
|
/// GenesisMeter reply.
|
|
/// </summary>
|
|
/// <param name="regName"></param>
|
|
/// <param name="data"></param>
|
|
/// <remarks date="2024-Dec-10" author="Thomas Wiedebusch">
|
|
/// - Initial MockGenesis simulation.
|
|
/// </remarks>
|
|
/// <remarks date="2025-Jul-11" author="Thomas Wiedebusch">
|
|
/// - Simulation of reset bits.
|
|
/// </remarks>
|
|
private void CheckAndModifySpecialReplies(String regName, Byte[] data)
|
|
{
|
|
// Reset a bit mask
|
|
if (SpecialRegisterResetBits.Any(n => regName.Contains(n.RegisterIdent)))
|
|
{
|
|
var readValue = ReadRegister(regName);
|
|
if (readValue != null)
|
|
{
|
|
for (var c = 0; c < data.Length; c++)
|
|
{
|
|
if (c < readValue.Length)
|
|
{
|
|
data[c] = (Byte)(readValue[c] & (Byte)~data[c]);
|
|
}
|
|
else
|
|
{
|
|
data[c] = 0;
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
for (var c = 0; c < data.Length; c++)
|
|
{
|
|
data[c] = 0x00;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Input value forces a constant reply if the input matches
|
|
if (SpecialRegisterReplies.Any(n => regName.Contains(n.RegisterIdent)))
|
|
{
|
|
foreach (var special in SpecialRegisterReplies.Where(special =>
|
|
regName.Contains(special.RegisterIdent)))
|
|
{
|
|
var retVal = true;
|
|
|
|
// Avoid buffer overflow
|
|
if (data.Length < special.ReadBackValue.Length)
|
|
break;
|
|
|
|
for (var i = 0; i < special.WriteValue.Length; i++)
|
|
{
|
|
// Check the required input which forces a change of the response
|
|
if (data[i] != special.WriteValue[i])
|
|
retVal = false;
|
|
}
|
|
|
|
if (!retVal)
|
|
break;
|
|
|
|
// Exchange the received value with the special reply
|
|
for (var i = 0; i < special.ReadBackValue.Length; i++)
|
|
{
|
|
data[i] = special.ReadBackValue[i];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock Read Register and return byte array for test purposes stored in the config register dictionary.
|
|
/// </summary>
|
|
/// <param name="regName"></param>
|
|
/// <param name="expectedLength">expected length for response</param>
|
|
/// <param name="skipRetryErrorCode">skip retries on this error code return</param>
|
|
/// <returns></returns>
|
|
/// <remarks date="2024-Dec-02..03" author="Thomas Wiedebusch">
|
|
/// - Initial mock implementation.
|
|
/// </remarks>
|
|
public override Byte[] ReadRegister(String regName, Int32? expectedLength = null,
|
|
UInt16 skipRetryErrorCode = CommunicationConfig.SkipRetryErrorCode)
|
|
{
|
|
try
|
|
{
|
|
var regDef = ConfigRegister.GetRegisterDefinitionByName(regName);
|
|
var hideDataInLog = regDef.RegisterName.Contains("EncryptionKey");
|
|
|
|
// Avoid reading of NOT readable registers
|
|
if (regDef.RegisterDetail.Privilege.Lvl8 != Access.RW &&
|
|
regDef.RegisterDetail.Privilege.Lvl8 != Access.RO)
|
|
return null;
|
|
|
|
var result = ConfigRegister.Get(regName);
|
|
// Avoid access of not present register
|
|
if (result == null)
|
|
{
|
|
Logger.Error($"Slot:{Slot} - Read register({regDef.GetIdent()}) returns value (null)");
|
|
return null;
|
|
}
|
|
|
|
var rawMsg = RegisterConverter.GetRegisterRawText(regDef, result, hideDataInLog);
|
|
Logger.Info($"Slot:{Slot} - Read register({regDef.GetIdent()}), record({rawMsg})");
|
|
|
|
return result;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Logger.Error($"Slot:{Slot} - {e.Message}");
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The simulation of the Genesis reboot:
|
|
/// - Login to create the actual installed
|
|
/// Kill all old applications,
|
|
/// this will force a regeneration of a valid application list and config register dictionary!
|
|
/// This will include the copy of FLASH register values or defaults to the config meter dictionary.
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
/// <remarks date="2024-Dec-03" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
/// <remarks date="2024-Dec-07" author="Thomas Wiedebusch">
|
|
/// - Reboot count used to check for success of reboot.
|
|
/// </remarks>
|
|
/// <remarks date="2024-Dec-11..12" author="Thomas Wiedebusch">
|
|
/// - Prepared to override the Genesis reboot used in <see cref="MeterResetPsu"/>.
|
|
/// </remarks>
|
|
public override StatusReturn RebootGenesis()
|
|
{
|
|
// ReLogin to build initial registers if it has not been performed in advance
|
|
ReLogin();
|
|
|
|
const String registerName = "CUSTOMER_RebootCount";
|
|
var rebootCountBeforeReboot = RegisterConverter.ByteArrayToValue<UInt32>(ReadRegister(registerName));
|
|
|
|
// Simulate reboot execution by increasing the reboot count by one
|
|
rebootCountBeforeReboot++;
|
|
if (WriteRegister(registerName, rebootCountBeforeReboot))
|
|
{
|
|
SingleParameterFlashMemory(registerName);
|
|
}
|
|
|
|
// Kill all old applications to force a regeneration of a valid application list
|
|
// and config register dictionary!
|
|
Logout();
|
|
FwVersion = "";
|
|
InstalledFwVersion = 0;
|
|
Region = "";
|
|
RadioFrequencyMhz = null;
|
|
MeterAppListVersion.Clear();
|
|
ConfigRegister.MeterRegisterDic.Clear();
|
|
ConfigApplications.Clear();
|
|
|
|
// Login to build initial registers if it has not been performed in advance
|
|
Login();
|
|
var rebootCountAfterReboot = RegisterConverter.ByteArrayToValue<UInt32>(ReadRegister(registerName));
|
|
|
|
return rebootCountAfterReboot == rebootCountBeforeReboot ? StatusReturn.Okay : StatusReturn.Failed;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Clear the config registers to simulate an invalid load or invalid configuration.json
|
|
/// </summary>
|
|
/// <remarks date="2025-Feb-17" author="Thomas Wiedebusch">
|
|
/// - Initial.
|
|
/// </remarks>
|
|
public void KillConfigRegisters()
|
|
{
|
|
ConfigRegister.MeterRegisterDic.Clear();
|
|
}
|
|
|
|
#endregion ----------------------------- Mock Genesis simulation ----------------------------------------------
|
|
}
|
|
}
|