Files
laatzen/Common/Hardware/WaterMeter/Genesis/Registers/RegisterConverter.cs
T
2023-08-16 11:18:55 +02:00

344 lines
12 KiB
C#

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Xylem.Common.Hardware.WaterMeter.Genesis.Registers.DataTypes;
namespace Xylem.Common.Hardware.WaterMeter.Genesis.Registers
{
/// <summary>
/// Helper to convert genesis register values store in bytes to data types and back
/// </summary>
public static class RegisterConverter
{
/// <summary>
/// Convert single register from Genesis and return a message of the result.
/// The raw value is swapped byte-wise to get a human readable value with MSB at leftmost and LSB at rightmost.
/// The message contains the swapped raw value and the converted value.
/// </summary>
/// <returns>message with register name, swapped raw value and converted value to use for logging</returns>
/// <remarks date="2023-Jul-19" author="Thomas Wiedebusch">
/// - Initial.
/// </remarks>
public static String GetRegisterParameterInfo(MeterRegisters registersDefinitions, String registerName,
Byte[] registerValue)
{
String msg;
var strValueResult = "?";
var strRawResult = "?";
try
{
// build value for logging
var regDef = registersDefinitions.GetRegisterDefinitionByName(registerName);
var strValue = ConvertToText(registerValue, regDef.DataType);
// remove non printable char
strValueResult = Regex.Replace(strValue, @"\p{C}+", string.Empty);
// inverse the raw value to get a readable byte order MSB left and LSB last right position
var tmpList = registerValue.ToList();
tmpList.Reverse();
strRawResult = BitConverter.ToString(tmpList.ToArray());
}
catch (Exception)
{
// nothing to do
}
finally
{
msg = $"{registerName} - {strRawResult} - {strValueResult}";
}
return msg;
}
/// <summary>
/// Convert a value (T) into byte[]
/// </summary>
/// <typeparam name="T">Type to convert from</typeparam>
/// <param name="value">value to convert</param>
/// <returns>byte[] like it store in genesis meter</returns>
/// <remarks date="????" author="Roland Drabesch">
/// - Init.
/// </remarks>
/// <remarks date="2023-Jul-19" author="Thomas Wiedebusch">
/// - Used <see cref="TimeT"/> to calculate time in UTC based on 01. Jan 2000
/// and the given offset in seconds.
/// </remarks>
public static Byte[] ConvertFrom<T>(T value)
{
var converted = new Byte[] { 0 };
if (value == null)
return converted;
if (value.GetType() == typeof(TimeT))
{
var teaTime = value as TimeT;
if (teaTime != null)
{
// the value contains always the seconds since 01.Jan 2000
var intValue = Convert.ToInt32(teaTime.SecondsSince2000);
return BitConverter.GetBytes(intValue);
}
}
if (value is Boolean)
{
var tmp = Convert.ToBoolean(value);
return BitConverter.GetBytes(tmp);
}
if (value is UInt16)
{
var tmp = Convert.ToUInt16(value);
return BitConverter.GetBytes(tmp);
}
if (value is UInt32)
{
var tmp = Convert.ToUInt32(value);
return BitConverter.GetBytes(tmp);
}
if (value is UInt64)
{
var tmp = Convert.ToUInt64(value);
return BitConverter.GetBytes(tmp);
}
if (value is Int16)
{
var intValue = Convert.ToInt16(value);
return BitConverter.GetBytes(intValue);
}
if (value is Int32)
{
var intValue = Convert.ToInt32(value);
return BitConverter.GetBytes(intValue);
}
if (value is Int64)
{
var tmp = Convert.ToInt64(value);
return BitConverter.GetBytes(tmp);
}
if (value is String)
{
return Encoding.ASCII.GetBytes(value.ToString());
}
if (value is Byte || value is Enum8)
{
converted[0] = Convert.ToByte(value);
}
else if (value is SByte)
{
return BitConverter.GetBytes(Convert.ToSByte(value));
}
else if (value is Byte[])
{
return (Byte[])Convert.ChangeType(value, typeof(Byte[]));
}
else
{
throw new ApplicationException($"Data type {typeof(T)} not implemented");
}
return converted;
}
/// <summary>
/// Giving types not generic and returns string
/// </summary>
/// <param name="value">byte value for conversion</param>
/// <param name="type">Type to cast from</param>
/// <returns></returns>
/// <remarks date="????" author="Roland Drabesch">
/// - Init.
/// </remarks>
/// <remarks date="2023-Jul-19" author="Thomas Wiedebusch">
/// - Used <see cref="TimeT"/> to calculate time in UTC based on 01. Jan 2000
/// and the given offset in seconds.
/// </remarks>
public static String ConvertToText(Byte[] value, Type type)
{
try
{
if (type == typeof(Boolean))
{
return ConvertTo<Boolean>(value).ToString();
}
if (type == typeof(TimeT))
{
var teaTime = ConvertTo<TimeT>(value);
return teaTime.ToString();
}
if (type == typeof(UInt16))
{
return ConvertTo<UInt16>(value).ToString();
}
if (type == typeof(UInt32))
{
return ConvertTo<UInt32>(value).ToString();
}
if (type == typeof(UInt64))
{
return ConvertTo<UInt64>(value).ToString();
}
if (type == typeof(Int16))
{
return ConvertTo<Int16>(value).ToString();
}
if (type == typeof(Int32))
{
return ConvertTo<Int32>(value).ToString();
}
if (type == typeof(Int64))
{
return ConvertTo<Int64>(value).ToString();
}
if (type == typeof(Byte) || type == typeof(Enum8))
{
return ConvertTo<Byte>(value).ToString();
}
if (type == typeof(SByte))
{
return ConvertTo<SByte>(value).ToString();
}
return ConvertTo<String>(value);
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// convert form byte (meter) to data type
/// </summary>
/// <typeparam name="T">Type to cast in</typeparam>
/// <param name="value">byte value for conversion</param>
/// <returns>converted value</returns>
/// <remarks date="????" author="Roland Drabesch">
/// - Init.
/// </remarks>
/// <remarks date="2023-Jul-19" author="Thomas Wiedebusch">
/// - Used <see cref="TimeT"/> to calculate time in UTC based on 01. Jan 2000
/// and the given offset in seconds.
/// - String removed from first zero in string until the end to avoid ghost signs!
/// </remarks>
public static T ConvertTo<T>(Byte[] value)
{
try
{
Object convertedObj;
var type = typeof(T);
if (type == typeof(Boolean))
{
convertedObj = BitConverter.ToBoolean(value, 0);
}
else if (type == typeof(UInt16))
{
convertedObj = BitConverter.ToUInt16(value, 0);
}
else if (type == typeof(UInt32))
{
convertedObj = BitConverter.ToUInt32(value, 0);
}
else if (type == typeof(UInt64))
{
convertedObj = BitConverter.ToUInt64(value, 0);
}
else if (type == typeof(Int16))
{
convertedObj = BitConverter.ToInt16(value, 0);
}
else if (type == typeof(Int32))
{
convertedObj = BitConverter.ToInt32(value, 0);
}
else if (type == typeof(Int64))
{
convertedObj = BitConverter.ToInt64(value, 0);
}
else if (type == typeof(Byte) || type == typeof(Enum8))
{
convertedObj = value[0];
}
else if (type == typeof(SByte))
{
// set all others to 0 as only the LSB is of interest
for (var idx = 1; idx < value.Length; idx++)
value[idx] = 0;
convertedObj = Convert.ToSByte((SByte)value[0]);
}
else if (type == typeof(Boolean))
{
convertedObj = Convert.ToBoolean(value[0]);
}
else if (type == typeof(String))
{
// the value may contain zeros at the beginning of the value-record, these have to be removed
var zeroPaddingCounter = 0;
while (value.Length > zeroPaddingCounter && value[zeroPaddingCounter] == 0)
zeroPaddingCounter += 1;
var trimmedValue = new Byte[value.Length - zeroPaddingCounter];
Int32 i;
for (i = 0; i < value.Length - zeroPaddingCounter; i++)
trimmedValue[i] = value[i + zeroPaddingCounter];
// as a string is terminated with a zero all following elements after including the initial
// zero have to be removed. This is caused due to the 4 byte chunks which will be sent.
var validCharCtr = 0;
// find the first zero in the trimmed value array
while (trimmedValue.Length > validCharCtr && trimmedValue[validCharCtr] != 0)
validCharCtr += 1;
// reserve space for valid chr plus the trailing 0 which will be added if
var rawResult = new Byte[validCharCtr + 1];
for (i = 0; i < validCharCtr; i++)
rawResult[i] = trimmedValue[i];
if (validCharCtr < trimmedValue.Length)
{
rawResult[i] = 0;
convertedObj = Encoding.ASCII.GetString(rawResult);
}
else
{
convertedObj = Encoding.ASCII.GetString(trimmedValue);
}
}
else if (type == typeof(TimeT))
{
// the value contains always the seconds since 01.Jan 2000
var teaTime = new TimeT { SecondsSince2000 = ConvertTo<Int32>(value) };
return (T)Convert.ChangeType(teaTime, typeof(TimeT));
}
else
{
throw new ApplicationException($"Data type {type} not implemented");
}
return (T)Convert.ChangeType(convertedObj, Type.GetTypeCode(typeof(T)));
}
catch (Exception)
{
return default(T);
}
}
}
}