laatzen/Common/modbus_master_csharp/Communication/ValueEncoders/U32_IP_Encoder.cs

70 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYLEM.Base;
namespace XYLEM.Communication.ValueEncoders {
/// <summary>
/// IP Address encoder when it has to be converted to a u32 value
/// </summary>
internal static class U32_IP_Encoder {
/// <summary>
/// Check if string is okay and possible to encode
/// </summary>
/// <param name="stringForCheck"></param>
/// <returns></returns>
internal static bool IsOkay(string stringForCheck) {
try {
if (string.IsNullOrEmpty( stringForCheck )) {
return false; // if string empty, then this is off and there is nothing to check
}
try {
var test = Encode( stringForCheck );
} catch {
return false; // Error is not possible to convert
}
return true; // Okay to convert
} catch (Exception ex) {
throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "IsOkay" ) );
}
}
/// <summary>
/// Encode xxx.xxx.xxx.xxx to bytes
/// </summary>
/// <param name="ip_XXX_XXX_XXX_XXX"></param>
/// <returns></returns>
static internal byte[] Encode(string ip_XXX_XXX_XXX_XXX) {
try {
var splited = ip_XXX_XXX_XXX_XXX.Split( '.' );
if (splited.Count( ) != 4) {
throw new Exception( "IP must be formated xxx.xxx.xxx.xxx but is " + ip_XXX_XXX_XXX_XXX.ToString( ) );
}
var values = splited.Select( value => byte.Parse( value ) );
return values.ToArray( );
} catch (Exception ex) {
throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "Encode" ) );
}
}
/// <summary>
/// decode bytes
/// </summary>
/// <param name="data"></param>
/// <returns>xxx.xxx.xxx.xxx</returns>
static internal string Decode(byte[] data) {
try {
if ((data == null) || (data.Count( ) != 4)) {
throw new Exception( "Must be 4 bytes" );
}
return String.Format( "{0}.{1}.{2}.{3}", data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ] );
} catch (Exception ex) {
throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "Decode" ) );
}
}
}
}